Beispiel #1
0
    def __remove_row_from_file(self, value):
        file = read_file()
        record = [row for row in file if value in row]
        file.remove(record[0])

        file = [';'.join(row) for row in file]
        rewrite_file(file)
Beispiel #2
0
def solve(identifier):
    user = myself()

    challenge = next((x for x in CHALLENGES if x.identifier == identifier),
                     None)
    if challenge is None:
        raise InvalidUsage('challenge not found', status_code=404)

    records = user.records.where(Record.challenge == identifier).limit(1)
    record = records[0]
    record.start()

    codechallenge = {
        "user": user.json,
        "challenge": challenge.json,
    }

    readme = read_file(challenge.readme)

    return render_template("solve.html",
                           codechallenge=json.dumps(codechallenge,
                                                    indent=4,
                                                    sort_keys=True),
                           fullname=user.email,
                           readme=readme,
                           challenge=challenge)
Beispiel #3
0
def read_order_file(input_file_name):
    """
    Reads input order file invalid (InvalidOrder) orders
    :param input_file_name: Path to orders input file
    :return:                1 - list of valid orders (ValidOrder)
                            2 - list of invalid orders (InvalidOrder)
                            3 - read_successful True if reading file is successful, else False
    """
    # read & validate orders file (valid_orders and/or invalid_orders may be length = 0)
    valid_orders = []
    invalid_orders = []
    read_successful = True
    try:
        valid_orders, invalid_orders = model.read_file(input_file_name)

    except FileNotFoundError as ex:
        msg = 'FileNotFoundError (check file path) occurred while reading {path}.  Exception=[{exception}'. \
            format(path=input_file_name, exception=ex)
        view.display_msg(msg)
        read_successful = False

    except StopIteration:
        msg = 'StopIteration (check file size) occurred while reading {path}.'. \
            format(path=input_file_name)
        view.display_msg(msg)
        read_successful = False

    except Exception as ex:
        msg = 'Unknown exception {ex} occurred while reading {path}.'. \
            format(ex=ex, path=input_file_name)
        view.display_msg(msg)
        read_successful = False

    finally:
        return valid_orders, invalid_orders, read_successful
Beispiel #4
0
    def all(self, sort=None):
        file = read_file()

        if sort:
            model = ['NOME', 'CPF', 'EMAIL', 'TELEFONE']
            file = sorted(file, key=(lambda item: item[model.index(sort)]))

        return file
def handle_request(request):
    if request.GET.button:
        if __is_authenticated(request):
            return successfully_authenticated(request.GET.user)

        write_file(request.GET.user)
        attempts = ', '.join(read_file())

        return access_denied(attempts)

    return login_page()
def handle_request(request):
    if request.GET.button:
        if __is_authenticated(request):
            return successfully_authenticated(request.GET.user)

        write_file(request.GET.user)
        file_content = read_file()
        users = set(file_content)
        user_attempts = []

        for user in users:
            attemps = file_content.count(user)
            user_attempts.append((user, attemps))

        return access_denied(user_attempts)

    return login_page()
def handle_add_contacts_request():
    if request.GET.button:
        name = request.GET.name
        age = request.GET.age
        gender = request.GET.gender

        if name or age or gender:
            if name and age and gender:
                write_file(f'{name};{age};{gender}')
            else:
                return add_contact('Preencha todos os dados')

        file = read_file()

        return (redirect('/list-contacts')
                if file else add_contact('O arquivo está vazio'))

    return add_contact()
def handle_add_contacts_request():
    if request.GET.button:
        name = request.GET.name
        id = request.GET.id
        email = request.GET.email
        phone = request.GET.phone

        if name or id or email or phone:
            if name and id and email and phone:
                write_file(f'{name};{id};{email};{phone}')
            else:
                return add_contact('Preencha todos os dados')

        file = read_file()

        return (redirect('/list-contacts') if file
                else add_contact('O arquivo está vazio'))

    return add_contact()
Beispiel #9
0
def test_model_read_file():
    #
    # test successful read file
    #
    input_file_name = os.path.join('../input', 'orders.csv')
    valid_orders, invalid_orders = model.read_file(input_file_name)
    assert len(valid_orders) == 4
    assert len(invalid_orders) == 0
    #
    # test missing file exception is raised
    #
    input_file_name = os.path.join('../input', 'orders_xxx.csv')
    pytest.raises(FileNotFoundError, model.read_file, input_file_name)
    #
    # test zero length file exception is raised
    #
    input_file_name = 'file_size_zero.txt'
    os.system('touch {0}'.format(input_file_name))
    os.truncate(input_file_name, 0)
    pytest.raises(StopIteration, model.read_file, input_file_name)
    os.system('rm {0}'.format(input_file_name))
Beispiel #10
0
 def get(self, value):
     file = read_file()
     file = [row for row in file if value in str(row)]
     return file
def handle_list_contacts_request():
    return list_contacts(read_file())
# Karl Jiang, karljiang
#
# Generate plots and print text answers for the CITY data
#
import sys
from model import linear_regression, apply_beta, read_file, Model, r_squared_table\
, compute_r_squared, print_model, get_highest_pair, forward_selection_r_squared, \
output_sel, select_best_k, test_foward_select


# useful defined constants for the city data
COMPLAINT_COLS = range(0, 7)
CRIME_TOTAL_COL = 7

file = "city"
variables, data = read_file("data/{}/training.csv".format(file))

if __name__ == "__main__":

    #Task 1a 
    print(file, "Task", "1A")
    print(r_squared_table(variables, data, CRIME_TOTAL_COL) )
    print() #\n

    #Task 1b
    print(file, "Task", "1B")
    model_1b = Model(variables, data, CRIME_TOTAL_COL, list(COMPLAINT_COLS) )
    r2 = compute_r_squared(model_1b.beta, model_1b.pre_col, model_1b.dep_col)
    print(print_model (model_1b.pre_var, r2) ) 
    print()#\n
Beispiel #13
0
# CS121 Linear regression assignment
# 
# Kristen Witte, kwitte
#
# Generate plots and print text answers for the STOCK data
#
import sys
import model

# useful defined constants for the stock data
#STOCKS = range(0, 11)
#DJIA = 11
#### Did not use

col_names, data = model.read_file("data/stock/training.csv")
col_names, test_data = model.read_file("data/stock/testing.csv")

##TASK 1A
print("Task 1A")
all_r2 = model.get_R2(col_names, data, "Single")
names_1A = col_names[:7]
model.make_table(all_r2, names_1A)


##TASK 1B
print("Task 1B")
combined_r2 = model.get_R2(col_names, data, "Multi")
names_1B = ["All"]
model.make_table(combined_r2, names_1B)

# CS121 Linear regression assignment
# 
# Manuel Aragones and CNET ID(s) 446154
#
# Generate plots and print text answers for the ELECTION data
#
import sys
import numpy as np
import model
from model import *

# create a list of names and numpy array
col_names, data_train = model.read_file('data/election/training.csv')
col_names_test, data_test = model.read_file('data/election/testing.csv')

print(col_names)
print(col_names[11])

# useful defined constants for the election data
COUNTY_DATA_COLS = range(0, 11)
VOTE_DIFFERENCE_COL = 11


# define the dependant variable
Y_NAME = 'VOTES_DIFF'
# get the index of the variable
y_index = col_names.index(Y_NAME)

# slice the data with a mechanism compatible with linear_regression 
# and apply_beta
y = data_train[:,y_index]
Beispiel #15
0
# CS121 Linear regression assignment
# 
# Manuel Aragones and CNET ID(s) 446154
#
# Generate plots and print text answers for the CITY data
#
import sys
import numpy as np
import model
from model import *

# create a list of names and numpy array
col_names, data_train = model.read_file('data/city/training.csv')
col_names_test, data_test = model.read_file('data/city/testing.csv')

# define the dependant variable
Y_NAME = 'CRIME_TOTALS'
# get the index of the variable
y_index = col_names.index(Y_NAME)

# slice the data with a mechanism compatible with linear_regression 
# and apply_beta
y = data_train[:,y_index]
y_test = data_test[:,y_index]

# define the independant variables. This method is better than using
# numbers as you see the name of the variables
X_NAMES = ['GRAFFITI',
			 'POT_HOLES',
			 'RODENTS',
			 'GARBAGE',
Beispiel #16
0
 def all(self, filter=None):
     return read_file()
Beispiel #17
0
from __future__ import print_function

import numpy as np
import tensorflow as tf
import time
import model


# Parameter definitions
batch_size = 200
learning_rate = 0.05
max_steps = 1000


# Prepare data
X_train, Y_train = model.read_file("../data/downgesture_train.list")
X_test, Y_test = model.read_file("../data/downgesture_test.list")
#print(Y_train)

# input placeholders
images_placeholder = tf.placeholder(tf.float32, shape=[None, 960])
labels_placeholder = tf.placeholder(tf.int64, shape=[None],name="label")

# variables (these are the values we want to optimize)
w1 = tf.Variable(tf.random_normal([960, 100]) * 0.01)
b1 = tf.Variable(tf.random_normal([100]) * 0.01)
y1 = tf.matmul(images_placeholder, w1) + b1

w2 = tf.Variable(tf.random_normal([100,2]) * 0.01)
b2 = tf.Variable(tf.random_normal([2]) * 0.01)
Beispiel #18
0
##################
# Tests for PA6
#
#

import numpy as np
import model

#data = np.array([[0, 0 , 0, 6], [0, 1, 0, 0], [0, 1, 1, 96]])

#col_names = ["G", "R", "T", "CR"]

col_names, data_training = model.read_file("data/city/training.csv")
col_names, data_testing = model.read_file("data/city/testing.csv")

#all_r2 = model.get_R2(col_names, data, "Single")
#combined_r2 = model.get_R2(col_names, data, "Multi")
#bivar_r2 = model.get_R2(col_names, data, "BiVar")

#print(bivar_r2)

def get_R2(col_names, data_training, data_testing, num_vars):

    total_cols = len(col_names)
    y_testing = data_testing[:, (total_cols - 1)]
    y_training = data_training[:, (total_cols - 1)]
    all_training = data_training[: , 0:total_cols - 1]
    all_testing = data_testing[: , 0:total_cols - 1]

    y_mean = (y_testing.sum()/len(y_testing))