Ejemplo n.º 1
0
def test_prefers_current_stock_batches_to_shipments():
    in_stock_batch = Batch("in-stock-batch", "RETRO-CLOCK", 100, eta=None)
    shipment_batch = Batch("shipment-batch", "RETRO-CLOCK", 100, eta=tomorrow)
    line = OrderLine("oref", "RETRO-CLOCK", 10)
    allocate(line, [in_stock_batch, shipment_batch])
    assert in_stock_batch.available_quantity == 90
    assert shipment_batch.available_quantity == 100
def insert_item(argv):
    '''Takes the system arguments as parameter and then inserts the item.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    if argv[2] == "school":
        school = School.create(name=argv[3])
        print "New school: " + str(School.get(School.name == argv[3]))
    elif argv[2] == "batch":
        batch = Batch.create(school=argv[3], name=argv[4])
        print "New batch: " + str(Batch.get(Batch.name == argv[4]))
    elif argv[2] == "student":
        print "New student:",
        if len(argv) > 6:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5],
                                     first_name=argv[6])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5] and
                                  Student.first_name == argv[6]))
        else:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5]))
    elif argv[2] == "exercise":
        exercise = Exercise.create(student=argv[3],
                                   subject=argv[4],
                                   note=argv[5])
        print "New Exercise: " + str(exercise)
def test_allocating_to_batch_reduces_availability():
    batch = Batch("batch-001",
                  "SMALL-TABLE",
                  qty=20,
                  eta=datetime.date.today())
    line = OrderLine('order-ref', "SMALL-TABLE", 2)
    batch.allocate(line)
    assert batch.available_quantity == 18
Ejemplo n.º 4
0
def test_allocate_prefers_warehouse():
    batch_warehouse = Batch(sku="SMALL-TABLE", qty=20)
    batch_shipping = Batch(sku="SMALL-TABLE", qty=20, eta=10)
    order_line = OrderLine(ref="bla", sku="SMALL-TABLE", qty=20)
    allocate(order_line, [batch_shipping, batch_warehouse])

    assert batch_warehouse.qty == 0
    assert batch_shipping.qty == 20
def test_allocating_in_stock_over_shipment():
    in_stock_batch = Batch('in-stock-batch', 'CLOCK', 100, eta=None)
    shipment_batch = Batch("shipment-batch", "CLOCK", 100, eta=tomorrow)
    line = OrderLine("oref", "CLOCK", 10)

    allocate(line, [in_stock_batch, shipment_batch])

    assert in_stock_batch.available_quantity == 90
    assert shipment_batch.available_quantity == 100
Ejemplo n.º 6
0
def test_prefers_earlier_batches():
    earliest = Batch('speedy-batch', 'MINIMALIST-SPOON', 100, eta=today)
    medium = Batch("normal-batch", 'MINIMALIST-SPOON', 100, eta=tomorrow)
    latest = Batch("slow-batch", "MINIMALIST-SPOON", 100, eta=later)
    line = OrderLine("order1", "MINIMALIST-SPOON", 10)
    allocate(line, [medium, earliest, latest])
    assert earliest.available_quantity == 90
    assert medium.available_quantity == 100
    assert latest.available_quantity == 100
Ejemplo n.º 7
0
def test_allocate_quickest_warehouse():
    batch_warehouse_slow = Batch(sku="SMALL-TABLE", qty=20, eta=10)
    batch_shipping_unavaiable = Batch(sku="SMALL-TABLE", qty=2, eta=1)
    batch_shipping_ok = Batch(sku="SMALL-TABLE", qty=20, eta=5)
    order_line = OrderLine(ref="bla", sku="SMALL-TABLE", qty=20)
    allocate(
        order_line, [batch_warehouse_slow, batch_shipping_unavaiable, batch_shipping_ok]
    )
    assert batch_warehouse_slow.qty == 20
    assert batch_shipping_unavaiable.qty == 2
    assert batch_shipping_ok.qty == 0
Ejemplo n.º 8
0
def test_returns_allocated_batch_ref():
    in_stock_batch = Batch("in-stock-batch-ref",
                           "HIGHBROW-POSTER",
                           100,
                           eta=None)
    shipment_batch = Batch("shipment-batch-ref",
                           "HIGHBROW-POSTER",
                           100,
                           eta=tomorrow)
    line = OrderLine("oref", "HIGHBROW-POSTER", 10)
    allocation = allocate(line, [in_stock_batch, shipment_batch])
    assert allocation == in_stock_batch.reference
def print_batch_by_school(argv):
    '''Takes the system arguments as parameter and then prints the batch based
    on the school id. Prints 'School not found' if the id does not exist.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    i = 0
    for item in Batch.select():
        if str(item.school.id) == str(argv[2]):
            print item
            break
        i += 1
    if i == len(Batch.select()):
        print "School not found"
Ejemplo n.º 10
0
def get_posts():
    batch = Batch()
    db_session.add(batch)
    db_session.commit()

    s = requests.Session()
    s.headers.update({'Accept-Language': 'sv', 'Accept': 'application/json'})

    for county in County.query.all():
        app.logger.info('Getting posts for %s' % county)
        _get_posts(s, batch, county.id, 10000, 1)
    batch.end_time = datetime.now()
    batch.complete = True
    batch.last_in = db_session.query(func.max(Post.external_id)).scalar()
    db_session.add(batch)
    db_session.commit()
Ejemplo n.º 11
0
def predict(batch: Batch):
    # Remove empty texts
    batch.texts = list(filter(lambda x: len(x) > 0, batch.texts))
    model = ModelWrapper()
    res = model(batch)

    return {"documents": res}
Ejemplo n.º 12
0
def get_posts():
    batch = Batch()
    db_session.add(batch)
    db_session.commit()

    s = requests.Session()
    s.headers.update({'Accept-Language': 'sv', 'Accept': 'application/json'})

    for county in County.query.all():
        app.logger.info('Getting posts for %s' % county)
        _get_posts(s, batch, county.id, 10000, 1)
    batch.end_time = datetime.now()
    batch.complete = True
    batch.last_in = db_session.query(func.max(Post.external_id)).scalar()
    db_session.add(batch)
    db_session.commit()
def print_student_by_batch(argv):
    '''Takes the system arguments as parameter and then prints the students
    in that batch based on the student id. Prints 'School not found' if the id
    does not exist.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    i = 0
    for student in Student.select().where(Student.batch == argv[2]):
        print student
    for item in Batch.select():
        if str(item.school.id) == str(argv[2]):
            break
        i += 1
    for batch in Batch.select():
        if str(batch.id) == str(argv[2]):
            return
    print "School not found"
def export_json(argv):
    '''Export all data in JSON format.

    Keyword arguments:
    argv -- An array of command line arguments.
    '''
    data = []
    for school in School.select():
        dict = {"name": school.name}
        data.append(dict)

    '''Add the batches.'''
    for dict in data:
        batches = []
        for batch in Batch.select():
            if batch.school.name == dict["name"]:
                batch_dict = {}
                dict["batches"] = batches
                batch_dict["name"] = batch.name
                batches.append(batch_dict)

    '''Add the students in their batch.'''
    for dict in data:
        if dict.get("batches") is not None:
            for batch in dict.get("batches"):
                students = []
                for student in Student.select():
                    if str(student.batch.name) == str(batch["name"]):
                        student_dict = {}
                        batch["students"] = students
                        student_dict["first_name"] = student.first_name
                        student_dict["last_name"] = student.last_name
                        student_dict["age"] = student.age
                        students.append(student_dict)

    '''Add the exercises to the corresponding student.'''
    for dict in data:
        if dict.get("batches") is not None:
            for batch in dict.get("batches"):
                for student in batch["students"]:
                    exercises = []
                    for e in Exercise.select():
                        if e.student.first_name == student.get("first_name"):
                            exercsie_dict = {}
                            student["exercises"] = exercises
                            exercsie_dict["note"] = e.note
                            exercsie_dict["subject"] = e.subject
                            exercises.append(exercsie_dict)

    print json.dumps(data)
def print_all(argv):
    '''Print all data in database, ordered with tab heirarchy.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    for school in School.select():
        print school
        for batch in Batch.select():
            if batch.school.id == school.id:
                print "\t" + str(batch)
                for student in Student.select():
                    if student.batch.id == batch.id:
                        print "\t\t" + str(student)
                        for exercise in Exercise.select():
                            if exercise.student.id == student.id:
                                print "\t\t\t" + str(exercise)
def change_batch(argv):
    '''Takes the system arguments as parameter. argv[2] is id of the student to
    change, argv[3] is the batch to change the student to.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    student_found = False
    batch_found = False
    for student in Student.select():
        if str(student.id) == str(argv[2]):
            student_found = True
    for batch in Batch.select():
        if str(batch.id) == str(argv[3]):
            batch_found = True
    if student_found is False:
        print "Student not found"
        return
    if batch_found is False:
        print "Batch not found"
        return

    for student in Student.select():
        if str(student.id) == str(argv[2]):
            if str(student.batch.id) == str(argv[3]):
                student_found = True
                print student,
                print "already in " + str(student.batch)
            else:
                '''If the student is not already in the batch, then reassign.'''
                tmp_id = student.id
                tmp_age = student.age
                tmp_first_name = student.first_name
                tmp_last_name = student.last_name

                d = Student.delete().where(Student.id == tmp_id)
                d.execute()
                new = Student.create(id=tmp_id,
                                     batch=argv[3],
                                     age=tmp_age,
                                     last_name=tmp_last_name,
                                     first_name=tmp_first_name)

                print student,
                print "has been move to",
                print new.batch
Ejemplo n.º 17
0
def main():
    today = strftime('%Y%m%d')
    batch_name = 'Median_Home_Values_Data_%s.csv' % today

    # Mark all current jobs_data batches inactive
    db_session.query(Batch).filter_by(datasource_id=5).update(
        {'is_active': False})
    batch = Batch(datasource_id=5, name=batch_name, is_active=True)
    db_session.add(batch)
    db_session.flush()
    db_session.commit()

    cities = db_session.query(City).order_by(City.code)
    for city in cities:
        print "city: %s" % city.code
        data = get_home_values(city.code)
        push_to_hadoop(data, batch_name)
        push_to_sql(data, city.code, batch.batch_id)
Ejemplo n.º 18
0
def main():
    today = strftime('%Y%m%d')
    batch_name = 'Jobs_Data_%s.csv' % today

    # Mark all current jobs_data batches inactive
    db_session.query(Batch).filter_by(datasource_id=6).update(
        {'is_active': False})
    batch = Batch(datasource_id=6, name=batch_name, is_active=True)
    db_session.add(batch)
    db_session.flush()
    db_session.commit()

    categories = range(1, 34)
    for c in categories:
        print "processing category %s" % c
        data = get_job_stats(c)
        push_to_hadoop(data, batch_name, c)
        push_to_sql(data['response']['cities'], batch.batch_id, c)

    db_session.close()
Ejemplo n.º 19
0
def test_allocation():
    batch = Batch(sku="SMALL-TABLE", qty=20)
    order_line = OrderLine(sku="SMALL-TABLE", qty=2, ref="some order")
    allocate(order_line, batch)
    assert batch.qty == 18
Ejemplo n.º 20
0
def test_cant_allocate_twice():
    batch = Batch(sku="SMALL-TABLE", qty=20)
    order_line = OrderLine(ref="some orderline", sku="SMALL-TABLE", qty=2)
    allocate(order_line, batch)
    allocate(order_line, batch)
    assert batch.qty == 18
Ejemplo n.º 21
0
def make_batch_and_line(sku,batch_qty,line_qty):
    return (
        Batch("batch-001",sku,batch_qty,eta=date.today()),
        OrderLine("order-123",sku,line_qty)
    )
Ejemplo n.º 22
0
def test_cannot_allocate_if_skus_do_not_match():
    batch=Batch("batch-001","UNCONFORTABLE-CHARE",100,eta=None)
    different_sku_line=OrderLine("order-123","EXPENIVE-TOASTER",10)
    assert batch.can_allocate(different_sku_line) is False
actions = ['create', 'print', 'insert', 'delete', 'print_batch_by_school', 'print_student_by_batch', 'print_student_by_school', 'print_family', 'age_average', 'change_batch', 'print_all', 'note_average_by_student', 'note_average_by_batch', 'note_average_by_school', 'top_batch', 'top_school']
if len(sys.argv) < 2:
	print 'Please enter an action'
elif sys.argv[1] not in actions:
	print 'Undefined action' + ' ' + sys.argv[1]
else:
	if sys.argv[1] == 'create':
		
		try:
			School.create_table()
		except peewee.OperationError:
			pass

		try:
			Batch.create_table()
		except peewee.OperationError:
			pass

		try:
			User.create_table()
		except peewee.OperationError:
			pass

		try:
			Student.create_table()
		except peewee.OperationError:
			pass
		try:
			Exercise.create_table()
		except peewee.OperationError:
Ejemplo n.º 24
0
def test_allocation_not_enough():
    batch = Batch(sku="BLUE-CUSHION", qty=1)
    order_line = OrderLine(sku="BLUE-CUSHION", qty=2, ref="some order")
    allocate(order_line, batch)
    assert batch.qty == 1
Ejemplo n.º 25
0
def test_raises_out_of_stock_exception_if_cannot_allocate():
    batch = Batch('batch1', 'SMALL-FORK', 10, eta=today)
    allocate(OrderLine('order1', 'SMALL-FORK', 10), [batch])
    with pytest.raises(OutOfStock, match='SMALL-FORK'):
        allocate(OrderLine('order2', 'SMALL-FORK', 1), [batch])
Ejemplo n.º 26
0
    print "Please enter an action"
elif sys.argv[1] in ["create", "print", "insert", "delete"]:
    # print sys.argv[1]
    # if "create":

else:
    print "Undefined action " + sys.argv[1]

if (sys.argv[1] == "create"):
try:
    School.create_table()
except peewee.OpertationalError:
    pass

try:
    Batch.create_table()
except peewee.OpertationalError:
    pass

try:
    User.create_table()
except peewee.OpertationalError:
    pass

try:
    Student.create_table()
except peewee.OpertationalError:
    pass


        print "Please set a JSON string"
        return
    except ValueError, e:
        batch_id = 0
        student_id = 0
        for k in loaded_json:
            for batch in k["batches"]:
                for student in batch["students"]:
                    for exercise in student["exercises"]:
                        insert_item(["", "insert", "school", k["name"]])
                        for school in School.select():
                            if school.name == k["name"]:
                                school_id = school.id
                        insert_item(["", "insert", "batch", school_id,
                                     batch.get("name")])
                        for orig_batch in Batch.select():
                            if orig_batch.name == batch.get("name"):
                                batch_id = orig_batch.id
                        insert_item(["", "insert", "student", batch_id,
                                     student.get("age"),
                                     student.get("last_name"),
                                     student.get("first_name")])
                        for s in Student.select():
                            if s.first_name == student.get("first_name"):
                                student_id = s.id
                        insert_item(["", "insert", "exercise", student_id,
                                     exercise.get("subject"),
                                     exercise.get("note")])


def export_json(argv):
Ejemplo n.º 28
0
def batch(product):
    return Batch('ref-0001', product, 20, eta=date.today())
def test_matching_in_allocation():
    batch = Batch('Batch-03', 'Nails', qty=50, eta=datetime.date.today())
    line = OrderLine('R-32', 'Wood', qty=3)
    batch.can_allocate(line) is False