Beispiel #1
0
def create_aplication():
    element_list = [common.random_id()]
    question = input("Is it accepted? ")
    element_list.append(question)

    student_check = True
    while student_check:
        id_ = 0
        student_id = input("Enter the ID of the student: ")
        table = data_manager.get_data("Student/students.txt")
        for element in table:
            if element[id_] == student_id:
                element_list.append(student_id)
                student_check = False

    position_check = True
    while position_check:
        id_ = 0
        position_id = input("Enter the ID of the position: ")
        table = data_manager.get_data("Positions/position.txt")
        for element in table:
            if element[id_] == position_id:
                element_list.append(position_id)
                position_check = False

    return element_list
Beispiel #2
0
def save_new_status():
    status_title = request.get_json()['title']
    board_id = request.get_json()['boardId']
    board_statuses = data_manager.get_data({'key': 'id', 'value': board_id}, 'boards')[0]['status_ids']
    try:
        if not data_manager.get_data({'key': 'title', 'value': status_title}, 'statuses'):
            data_manager.save_new_status(status_title)
        status_id = data_manager.get_data({'key': 'title', 'value': status_title}, 'statuses')[0]['id']
        if status_id not in board_statuses:
            data_manager.add_status_to_board(board_id, status_id)
    except:
        return jsonify({'done': False, 'message': 'Database error'})
    else:
        return jsonify({'done': True, 'message': 'Status added', 'result': status_id})
Beispiel #3
0
def route_new_comment(question_id: int, answer_id: int):
    if 'user_name' in session:
        if request.method == 'POST':
            new_comment = request.form
            data_manager.post_comment(new_comment, question_id, answer_id)
            return redirect('/question/' + question_id)
        questions = data_manager.get_data('question')
        answers = data_manager.get_data('answer')
        return render_template("comment.html",
                               question_id=int(question_id),
                               answer_id=int(answer_id),
                               questions=questions,
                               answers=answers)
    else:
        return redirect('/')
Beispiel #4
0
def create_position():
    element_list = [common.random_id()]
    question = input("Describe the new position: ") 
    element_list.append(question)
    
    while True:
        question = input("Number of seats: ")
        try:
            if int(question) > 0:
                element_list.append(question)
                break
        except:
            pass

    process = True
    while process:
        id_ = 0
        company_id = input("Company ID for the position: ")
        table = data_manager.get_data("Company/company.txt")
        for element in table:
            if element[id_] == company_id:
                element_list.append(company_id)
                process = False

    return element_list
def update_authentication_password(form):
    data = get_data()

    def set_authentication_password(password):
        new_password = generate_password_hash(password=password,
                                              method='pbkdf2:sha256',
                                              salt_length=8)
        password_data = {"secret_password": new_password}
        data.update(password_data)
        update_data(data)

    try:
        authentication_password = data['secret_password']
    except KeyError:
        authentication_password = None
    try:
        if authentication_password:
            if check_password_hash(authentication_password,
                                   form.old_password.data):
                set_authentication_password(form.new_password.data)
                return redirect(url_for('website_settings.menu', mode='admin'))
            else:
                flash("Incorrect authentication password.")
                return redirect(
                    url_for('website_settings.authentication_configuration'))
        else:
            set_authentication_password(form.new_password.data)
            return redirect(url_for('website_settings.menu', mode='admin'))
    except (AttributeError, TypeError):
        return abort(400)
def train():
    header, train, val, test, data_dict = get_data(
        N_CLASSES, MERGE_TAGS, SPLIT_RANDOMLY)
    print header

    weights, biases = get_vars()

    coord = tf.train.Coordinator()

    data_man_train, pred, cost, auc_op, update_auc_op = get_end_ops(
        train, data_dict, coord, weights, biases)
    data_man_val, pred_val, cost_val, auc_op_val, update_auc_op_val = get_end_ops(
        val, data_dict, coord, weights, biases)

    optimizer = tf.train.AdamOptimizer(
        learning_rate=LEARNING_RATE).minimize(cost)

    saver = tf.train.Saver()
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    sess.run(tf.initialize_local_variables())

    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    data_man_train.start_threads(sess)
    data_man_val.start_threads(sess)

    if not os.path.exists(SAVE_DIR):
        os.mkdir(SAVE_DIR)

    try:
        print 'Starting training'
        step = 0
        start = time.time()
        while True:
            sess.run(optimizer, feed_dict={keep_prob: DROPOUT})
            if step % PRINT_EVERY == 0:
                loss, _ = sess.run(
                    [cost, update_auc_op], feed_dict={keep_prob: 1})
                print 'Step', step, 'Epochs', float(step) * BATCH_SIZE / len(train), \
                    'Minibatch loss', loss, 'Time', time.time() - start
            if step % EVAL_EVERY == 0 and step != 0:
                total_loss = 0
                for _ in range(len(val) / BATCH_SIZE):
                    loss, _ = sess.run(
                        [cost_val, update_auc_op_val], feed_dict={keep_prob: 1})
                    total_loss += loss
                auc, auc_val = sess.run([auc_op, auc_op_val])
                print 'Train set AUC', auc
                print 'Validation set loss', total_loss / (len(val) / BATCH_SIZE), 'Validation set AUC', auc_val
                print ''
                saver.save(sess, SAVE_DIR + 'model', global_step=step)
                sess.run(tf.initialize_local_variables())
            step += 1
    except:
        pass
    finally:
        coord.request_stop()

    coord.join(threads)
    sess.close()
Beispiel #7
0
def display_q():
    questions = data_manager.get_data('question')
    entries = questions
    sort_by = 'submission_time'
    if request.args.get('sort_by') == 'sorted_by' and request.args.get(
            'asc_dsc') == 'asc' or request.args.get(
                'sort_by') == 'sorted_by' and request.args.get(
                    'asc_dsc') == 'desc':
        entries = sorted(questions, key=lambda questions: questions[sort_by])
    elif request.args.get('sort_by') is not None and request.args.get(
            'asc_dsc') is not None:
        ascdsc = request.args.get('asc_dsc')
        sort_by = request.args.get('sort_by')
        if ascdsc == 'asc':
            entries = sorted(questions,
                             key=lambda questions: questions[sort_by],
                             reverse=False)
        elif ascdsc == 'desc':
            entries = sorted(questions,
                             key=lambda questions: questions[sort_by],
                             reverse=True)

    return render_template('list.html',
                           questions=entries,
                           sort_by=sort_by,
                           asc_dsc=request.args.get('asc_dsc'))
def update_configuration(configuration,
                         form,
                         new_email=False,
                         flash_message=None):
    data = get_data()
    try:
        keys = CONFIG_KEYS[configuration]
    except KeyError:
        return abort(400)
    else:
        new_data = {
            configuration: {
                key:
                form[key].data if key != 'support_email' and new_email is False
                else data[configuration]['support_email']
                for key in keys
            }
        }
        new_configuration = new_data[configuration]
        keys_lst = list(new_configuration.keys())
        values_lst = list(new_configuration.values())
        log_changes(configuration=configuration,
                    new_configuration=new_configuration,
                    keys_lst=keys_lst,
                    values_lst=values_lst)
        data.update(new_data)
        update_data(data)
        flash(flash_message) if flash_message else None
        return redirect(url_for('website_settings.menu', mode='admin'))
Beispiel #9
0
def get_social():
    try:
        soc = get_data()["website_configuration"]
        return dict(
            social={
                "twitter": soc["twitter_link"],
                "facebook": soc["facebook_link"],
                "github": soc["github_link"],
                "youtube": soc["youtube_link"],
                "linkedin": soc["linkedin_link"],
                "instagram": soc["instagram_link"],
                "dev": soc["dev_link"],
                "whatsapp": soc["whatsapp_link"],
                "reddit": soc["reddit_link"],
                "pinterest": soc["pinterest_link"],
                "telegram": soc["telegram_link"]
            })
    except KeyError:
        return dict(
            social={
                "twitter": "https://www.twitter.com",
                "github": "https://www.github.com",
                "facebook": "https://www.github.com",
                "instagram": "https://www.instagram.com",
                "youtube": "https://www.youtube.com",
                "linkedin": "https://www.linkedin.com",
                "dev": "https://dev.to",
                "whatsapp": "https://www.whatsapp.com",
                "reddit": "https://www.reddit.com",
                "pinterest": "https://www.pinterest.com",
                "telegram": "https://www.telegram.com"
            })
Beispiel #10
0
def edit_question(question_id, title, message):
    if request.method == 'POST':
        question_data = data_manager.get_data()
        title = request.form['Title']
        message = request.form['Message']
        data_manager.push_data(question_data)
        return redirect(f'/question_list/{question_id}')
    return render_template('add_edit_page.html', question_id=question_id)
Beispiel #11
0
def get_name(configuration=None):
    data = get_data()
    try:
        return dict(name=data["website_configuration"]["name"]) if configuration is None else \
            data["website_configuration"]["name"]
    except (TypeError, IndexError, KeyError):
        return dict(
            name="Website"
        ) if configuration is None else data["website_configuration"]["name"]
Beispiel #12
0
def route_question(question_id):
    if 'user_name' in session:
        if request.method == 'GET':
            question = data_manager.get_data('question', question_id)
            answers = data_manager.get_data('answer', question_id=question_id)
            question_comments = data_manager.get_question_comments(question_id)
            answer_comments = data_manager.get_answer_comments(question_id)
            return render_template("question-only.html",
                                   question_id=int(question_id),
                                   question=question,
                                   answers=answers,
                                   question_comments=question_comments,
                                   answer_comments=answer_comments)
        elif request.method == 'POST':
            data_manager.delete_question(question_id)
            return redirect('/list')
    else:
        return redirect('/')
Beispiel #13
0
def is_page_valid():
    valid = True
    try:
        support_email = get_data()["contact_configuration"]["support_email"]
    except KeyError:
        valid = False
    else:
        if support_email is None:
            valid = False
    return valid
Beispiel #14
0
def newsletter_functionality(configuration=None):
    try:
        config_data = get_data()["newsletter_configuration"]
    except KeyError:
        enabled = False
    else:
        try:
            enabled = config_data["enabled"]
        except KeyError:
            enabled = False
    return dict(newsletter_enabled=enabled) if not configuration else enabled
Beispiel #15
0
def get_background(configuration='website_configuration'):
    try:
        if configuration == 'website_configuration':
            return dict(
                background_image=get_data()[configuration]["background_image"])
        else:
            try:
                background = get_data()[configuration]["background_image"]
                if background == '':
                    return get_data(
                    )["website_configuration"]["background_image"]
                return background
            except (KeyError, TypeError):
                try:
                    return get_data(
                    )["website_configuration"]["background_image"]
                except (KeyError, TypeError):
                    return ''
    except (KeyError, TypeError):
        return dict(background_image="")
Beispiel #16
0
def get_route_status(route):
    try:
        data = get_data()["api_configuration"]
    except KeyError:
        return "unavailable"
    else:
        try:
            if data[route] is False:
                return "blocked"
            return True
        except KeyError:
            return "unavailable"
Beispiel #17
0
def get_page_elements():
    try:
        contact_config = get_data()['contact_configuration']
    except KeyError:
        heading = "Contact us"
        subheading = "We'll get to you as soon as we can."
        description = "Want to get in touch? Fill out the form below and we'll respond as soon as we can!"
    else:
        heading = contact_config.get('page_heading')
        subheading = contact_config.get('page_subheading')
        description = contact_config.get('page_description')
    return heading, subheading, description
Beispiel #18
0
def route_new_answer(question_id):
    if 'user_name' in session:
        if request.method == 'POST':
            new_user_answer = request.form
            data_manager.add_new_answer(new_user_answer, question_id)
            return redirect('/question/' + question_id)
        questions = data_manager.get_data('question')
        return render_template("answer.html",
                               question_id=int(question_id),
                               questions=questions)
    else:
        return redirect('/')
Beispiel #19
0
def check_position(table, id_):
    app_position_id = -1
    app_student_id = -2
    aplication_table = data_manager.get_data("Application/aplication.txt")
    student_table = data_manager.get_data("Student/students.txt")
    student_id = 0
    result = []

    for element in table:
        if id_ == element[student_id]:
            result.append(element)
            for elem in aplication_table:
                if elem[app_position_id] == id_:
                    print("hi")
                    for item in student_table:
                        if item[student_id] == elem[app_student_id]:
                            result.append(item)
    
    if result:
        return result
    
    return ["No such ID in the list."]
Beispiel #20
0
def get_subscription_page_elements():
    try:
        subscription_page = get_data()['newsletter_configuration']
    except KeyError:
        heading = "Subscribe to our newsletter!"
        subheading = "Enjoy all of our internet doses."
    else:
        heading = subscription_page.get('subscription_title',
                                        "Enjoy all of our internet doses.")
        subheading = subscription_page.get('subscription_subtitle',
                                           "Enjoy all of our internet doses.")

    return heading, subheading
Beispiel #21
0
def count_neighbor_average_array_and_save(dimension: int, id_indx: int,
                                          tag: str):
    '''
    Use this function to count neighbour pixels' average intensities and save the csv 
    file for ML process.
    Use show_data_info function to find out dimension, id_inx and tags, which exist.

    Parameters:
    -----------
    dimension: 2 or 3. 
        Dimension of phantom Euclidian space

    id_indx: 1,2,3,etc.
        id for phantom with certain porosity, blobiness and experiment parameters

    tag: 'test', 'train' or another
        This parameter controls conflicts if several csv files are generated for 1 phanom.
        Keep it different for staging different images with similar parameters
    
    results:
    --------
    out: csv file
        See in the  script's directory in the folder 'database'
        To open use data_manager.get_data(args) function
    '''

    orig_phantom = dm.get_data(dimension, id_indx, tag, 'orig_phantom')
    proc_phantom = dm.get_data(dimension, id_indx, tag, 'processed_phantom')

    neighbor_pixel_average = count_neighbor_average_array(proc_phantom)

    data = {
        'neighbor_average': np.concatenate(neighbor_pixel_average),
        'proc_phantom_pixel_values': np.concatenate(proc_phantom),
        'pixel_real_value': np.concatenate(orig_phantom)
    }
    csv_file = pd.DataFrame(data)

    dm.add_csv(dimension, id_indx, tag, csv_file)
def get_form_elements(configuration):
    try:
        requested_configuration = get_data()[configuration]
    except KeyError:
        return {}
    else:
        try:
            form_arguments = {
                key: requested_configuration[key]
                for key in requested_configuration
            }
        except KeyError:
            form_arguments = {}
        return form_arguments
Beispiel #23
0
def get_unsubscription_page_elements():
    try:
        config_data = get_data()['newsletter_configuration']
    except KeyError:
        heading = "Unsubscribe from our newsletter"
        subheading = "Not satisfied with our newsletter? Unsubscribe here."
    else:
        heading = config_data.get("unsubscription_title",
                                  "Unsubscribe from our newsletter")
        subheading = config_data.get(
            "unsubscription_subtitle",
            "Not satisfied with our newsletter? Unsubscribe here.")

    return heading, subheading
Beispiel #24
0
def display_question(question_id):
    answer = []
    question_data = data_manager.get_data()
    answer_data = data_manager.get_data_answer()
    for i in question_data:
        if i[0] == question_id:
            question = i
            break
    for i in answer_data:
        if i[3] == question_id:
            answer.append(i)
    return render_template('question_page.html',
                           question=question,
                           answer=answer)
Beispiel #25
0
def list_questions():
    sort_by = ''
    direction = ''
    if request.method == "POST":
        sort_by = request.form.get('sort')
        direction = request.form.get('direction')
        data = data_manager.sort_csv(sort_by, direction)
    else:
        data = data_manager.get_data()
    return render_template('list.html',
                           data=data,
                           sort_by=sort_by,
                           direction=direction,
                           searching=True)
def set_notification(category, email, name, action_user, action_reason):
    try:
        support_email = get_data()["contact-configuration"]["support_email"]
    except KeyError:
        msg = Message(f'Account set as {category}', sender=EMAIL, recipients=[email])
    else:
        msg = Message(f'Account set as {category}', sender=EMAIL, recipients=[email,
                                                                              support_email])
    msg.body = f"Hello {name}, this is an automatic email from {get_name('m')} to notify you of recent" \
               f" events that occurred in regards to your account.\n\n" \
               f'Your account was set as an {category} by {action_user}.\n\n' \
               f'Reasoning by actioning staff member:\n\n{html2text(action_reason)}\n\n' \
               f'Congratulations, if you have any inquires, contact us by replying to this email or via our website.'
    send_mail(msg)
Beispiel #27
0
def delete_company(table, id_):
    company_id = 0
    tmp = []
    position_id = -1
    position_table = data_manager.get_data("Positions/position.txt")
    for field in position_table:
        if field[position_id] == id_:
            ui.print_result(["Can't delete a company with open position."])
            return table
            
    for element in table:
        if element[company_id] != id_:
            tmp.append(element)
    return tmp
Beispiel #28
0
def make_db_query(criteria, table):
    if criteria:
        key = list(criteria.keys())[0]
        value = criteria[key]
        criteria = {"key": key, "value": value}
    try:
        query_result = data_manager.get_data(criteria, table)
    except:
        return jsonify({"done": False, "reason": "Database error"})
    else:
        return jsonify({
            "done": True,
            "message": "Successful query",
            "result": query_result
        })
def redirect_after_verification(user_id, password, redirect_to, salt, auth_func):
    if not User.query.get(user_id):
        return abort(400)
    try:
        contents = get_data()
        secret_password = contents['secret_password']
    except (KeyError, TypeError, IndexError):
        flash("Authentication Password is not available. Deletion cannot be performed at this time.")
        return redirect(url_for('home.home_page', category='danger'))
    if check_password_hash(secret_password, password):
        token = serializer.dumps(current_user.email, salt=salt)
        link = url_for(redirect_to, token=token, email=current_user.email, user_id=user_id)
        return redirect(link)
    else:
        flash("Incorrect authorization code.")
        return redirect(url_for(f"verification.{auth_func}", user_id=user_id))
def handle_support_confirmation(token, email):
    load_token(token=token, salt='support-verify')
    if not any(email):
        return abort(400)
    config_data = get_data()
    try:
        if config_data["contact_configuration"]["support_email"] != email:
            config_data["contact_configuration"]["support_email"] = email
            update_data(config_data)
            flash("This email was successfully set as the support email.")
            return redirect(url_for('home.home_page', category='success'))
        else:
            flash("This email is already set as the support email.")
            return redirect(url_for('home.home_page', category='danger'))
    except KeyError:
        return abort(500)