Example #1
0
def orders_function(bot, types, message):
    order = Order(message.chat.id)
    if not order.is_orders():
        bot.send_message(message.chat.id, inscriptions.no_orders_text)
    elif order.is_orders():
        markup = create_orders_markup(types, message)
        bot.send_message(message.chat.id,
                         inscriptions.some_orders_here,
                         reply_markup=markup)
Example #2
0
 def test_valid_status_setter(self):
     order = Order()
     order.setStatus(validStatus1)
     correctValue = validStatus1
     self.assertEqual(
         order.getStatus(),
         correctValue,
         msg=
         f"Error in the email setter and getter values:\n\n{order.getStatus()}\n\n{correctValue}"
     )
Example #3
0
 def test_valid_customerId_setter(self):
     order = Order()
     order.setCustomerId(validCustomerId1)
     correctValue = validCustomerId1
     self.assertEqual(
         order.getCustomerId(),
         correctValue,
         msg=
         f"Error in the customerId setter and getter values:\n\n{order.getCustomerId()}\n\n{correctValue}"
     )
Example #4
0
def requestOrder(postBody):
    response = {}
    try:
        order = Order(postBody["serviceType"], postBody["pickupAddress"],
                      postBody["dropoffAddress"], postBody["customerId"])
        orderObj = order.__dict__
        client = mongoConnect()
        db = client.team12_demand
        orders = db.orders
        publicId = orders.count_documents({}) + 1000
        orderObj["publicId"] = publicId
        orderId = orders.insert_one(orderObj).inserted_id
        address1 = (orderObj["pickupAddress"]).replace(" ", "+")
        address2 = (orderObj["dropoffAddress"]).replace(" ", "+")
        #### Uncomment this block when supply is up on server ####
        routeResponse = requests.get(
            f"http://localhost:8081/vehicles/req?service_type={orderObj['serviceType']}&order_id={orderId}&customer_id={orderObj['customerId']}&destination={address1}"
        )
        # routeResponse = requests.get(f"https://supply.team12.sweispring21.tk/api/vehicles/req?service_type={orderObj['serviceType']}&order_id={orderId}&customer_id={orderObj['customerId']}&destination={address1}")
        responseObj = routeResponse.json()
        routeObj = responseObj["data"]
        if responseObj['status'] == "OK":
            order.setStatus("vehicle on route")
            response = {
                'status': responseObj['status'],
                'data': {
                    "_id": orderId,
                    "publicId": publicId,
                    "status": order.getStatus(),
                    "routeObj": routeObj
                }
            }
            dbRouteObj = routeObj
        else:
            response = {
                'status': responseObj['status'],
                'data': responseObj['data']
            }
            order.setStatus("unfulfilled")
            dbRouteObj = routeObj

        orders.update_one(
            {"_id": orderId},
            {"$set": {
                "status": order.getStatus(),
                "routeObj": dbRouteObj
            }})
    except ValueError as err:
        response = {'status': 'CONFLICT', 'data': {'msg': err}}
    except Exception as err:
        logging.error(err)
        response = {
            'status': 'INTERNAL_SERVER_ERROR',
            'data': {
                'msg': 'Server stopped working, please try again later'
            }
        }

    return response
Example #5
0
def callback_data_order(bot, call):
    orders = Order(call.message.chat.id)
    # If order in user`s order list
    for order in orders.orders:
        if call.data == order[0]:
            bot.send_message(call.message.chat.id,
                             order.return_items_note_str())
Example #6
0
def create_orders_markup(types, message):
    orders = Order(message.chat.id)
    markup = types.InlineKeyboardMarkup(row_width=2)
    for order in orders.orders:
        item = types.InlineKeyboardButton(order[0], callback_data=order[0])
        markup.add(item)
    return markup
Example #7
0
def add_order():
    if request.method == 'GET':
        # show create form
        return render_template('addOrderForm.html')
    else:
        nom = request.form['orderName']
        order = Order(name=nom, status='ongoing')
        db.session.add(order)
        db.session.commit()
        return redirect(url_for('index'))
Example #8
0
 def get_amount_cost(self, date):
     orders_before = [op for op in self.list_orders if op.date <= date]
     if len(orders_before) > 0:
         op_sum = sum(orders_before, Order())
         amount = op_sum.amount
         cost = op_sum.price*amount
     else:
         amount = 0
         cost = 0.0
     return amount, cost
Example #9
0
def buy(args):

    path = args.config['book-path']
    # Check if the file book.json exist and if not create it
    # and iniate it with '[]'
    if not os.path.isfile(path):
        data = "[]"
        file = open(path, 'a+')
        file.write(data)
        file.close()
    order = Order(args)
    data = json.loads(open(path).read())
    data.append(order.toDict())
    with open(path, 'w') as outfile:
        json.dump(data, outfile, indent=4)

    # Display the order with a nice table
    table_data = [['id', 'Exchange', 'Market', 'Price'],
                  [order.id, order.exchange, order.market, order.last]]
    table = SingleTable(table_data)
    table.title = 'Buy Order'
    print(table.table)
Example #10
0
 def test_valid_order_2(self):
     validOrder2 = Order(validService2, validPickup2, validDropoff2,
                         validCustomerId2)
     orderObj = validOrder2.__dict__
     match = {
         'serviceType': validService2,
         'pickupAddress': validPickup2,
         "dropoffAddress": validDropoff2,
         "customerId": validCustomerId2,
         "route": None,
         "status": "pending confirmation"
     }
     self.assertEqual(
         orderObj,
         match,
         msg=
         f"orderObj does not match\n\norderObj: {orderObj}\n\ncorrect: {match}"
     )
Example #11
0
 def load_orders(self, path_orders, path_dividends, country):
     print('Loading orders and dividends for {} wallet...'.format(country))
     orders = pd.read_csv(path_orders, sep=';', index_col=0, header=0)
     dividends = pd.read_csv(path_dividends, sep=';', index_col=0, header=0)
     list_stocks = []
     for ticker in orders.index.unique():
         list_orders = []
         for row in orders.loc[[ticker]].iterrows():
             list_orders.append(
                 Order(row[1]['Date'], row[1]['Amount'], row[1]['Price'],
                       row[1]['Kind']))
         list_dividends = []
         if ticker in dividends.index:
             for row in dividends.loc[[ticker]].iterrows():
                 list_dividends.append(
                     Dividend(row[1]['Date'], row[1]['Value'],
                              row[1]['Kind']))
         list_stocks.append(Stock(ticker, list_orders, list_dividends))
     return Wallet(list_stocks, country)
Example #12
0
 def test_valid_order_1(self):
     validOrder1 = Order(validService1,
                         validPickup1,
                         validDropoff1,
                         validCustomerId1,
                         route=validRoute1)
     orderObj = validOrder1.__dict__
     match = {
         'serviceType': validService1,
         'pickupAddress': validPickup1,
         "dropoffAddress": validDropoff1,
         "customerId": validCustomerId1,
         "route": validRoute1,
         "status": "pending confirmation"
     }
     self.assertEqual(
         orderObj,
         match,
         msg=
         f"orderObj does not match\n\norderObj: {orderObj}\n\ncorrect: {match}"
     )
Example #13
0
 def test_invalid_status_setter(self):
     with self.assertRaises(
             ValueError,
             msg="Values passed should have raised a Value Error"):
         order = Order()
         order.setStatus(invalidStatus1)
Example #14
0
from classes.pizza import *
from classes.characteristic import Ingredient, Size
from classes.order import Order
from util.pizzaUtil import *
from util.cliMsg import *
from util.cliUtil import *

if __name__ == '__main__':
    print(welcomeTitle)
    order = Order()
    while True:
        print("Pizza nĂºmero {0}".format(len(order.pizzas) + 1))
        while True:
            sizeOption = input("{0}:".format(showPizzaSizes()))
            if not isValidSize(sizeOption):
                print("{0}".format(sizeSelectionError))
                continue
            zoneTopping = ynCliOption(zoneQuestion)
            zonesQuantity = int(input(
                "{0}".format(zoneOptions))) if zoneTopping else 0
            pizza = pizzaFactory.getPizza(zoneTopping, zones=zonesQuantity)
            order.addPizza(pizza)
            setPizzaSize(pizza, sizeOption)
            setPizzaIngredients(pizza, order)
            pizza.showPizzaSummary()
            break
        continueOrder = ynCliOption(continueQuestion)
        if continueOrder:
            continue
        else:
            break
Example #15
0
def tl_worker_new(tl_list, merged_count_dict, loop_type_order,
                  total_merged_count, input_settings, spatial_loop_comb,
                  mem_scheme, precision, layer, mac_costs):
    """
    New tl_worker function to handle the multiset loop orderings.

    These orderings still require a memory allocation, followed by a cost model evaluation.
    """

    # Get the different MemoryNodes we need to allocate
    nodes = mem_scheme.nodes
    n_mem_levels = len(nodes)

    # Layer
    [layer_origin, layer_rounded] = layer

    # Spatial unrolling
    [spatial_loop, spatial_loop_fractional] = spatial_loop_comb

    # Get the active and idle MAC cost
    [active_mac_cost, idle_mac_cost] = mac_costs

    # loop_type order ['B','K','C','OY','OX','FY','FX']
    # Adjust the merged_count_dict for the first loop_type, as this got chunked in caller function
    first_loop_type = loop_type_order[0]
    merged_count_dict[first_loop_type] = len(tl_list[first_loop_type])

    # Get the orderings for all possible loop_types (some might be non-existent)
    tl_list_B = tl_list.get('B', [None])
    tl_list_K = tl_list.get('K', [None])
    tl_list_C = tl_list.get('C', [None])
    tl_list_OY = tl_list.get('OY', [None])
    tl_list_OX = tl_list.get('OX', [None])
    tl_list_FY = tl_list.get('FY', [None])
    tl_list_FX = tl_list.get('FX', [None])

    # Get the smallest prime factor for each loop type (required for loop merging)
    smallest_pfs = {
        7: get_smallest_pf(tl_list_B[0]),
        6: get_smallest_pf(tl_list_K[0]),
        5: get_smallest_pf(tl_list_C[0]),
        4: get_smallest_pf(tl_list_OY[0]),
        3: get_smallest_pf(tl_list_OX[0]),
        2: get_smallest_pf(tl_list_FY[0]),
        1: get_smallest_pf(tl_list_FX[0])
    }

    # Init minimal energy and max utilization results
    min_en = float('inf')
    min_en_ut = 0
    max_ut_en = float('inf')
    max_ut = 0

    # Init energy,latency,utilization collect
    energy_collect = None
    utilization_collect = None
    latency_collect = None
    save_all_tm = input_settings.tm_search_result_saving
    if save_all_tm:
        energy_collect = []
        utilization_collect = []
        latency_collect = []

    # Loop through all the number of elements in each tl_list element
    ctr = 0
    skipped = 0
    merged_set = set()
    for order_B in tl_list_B:
        for order_K in tl_list_K:
            order_B_K = combine_orderings(order_B, order_K)
            for order_C in tl_list_C:
                order_B_K_C = combine_orderings(order_B_K, order_C)
                for order_OY in tl_list_OY:
                    order_B_K_C_OY = combine_orderings(order_B_K_C, order_OY)
                    for order_OX in tl_list_OX:
                        order_B_K_C_OY_OX = combine_orderings(
                            order_B_K_C_OY, order_OX)
                        for order_FY in tl_list_FY:
                            order_B_K_C_OY_OX_FY = combine_orderings(
                                order_B_K_C_OY_OX, order_FY)
                            for order_FX in tl_list_FX:
                                ctr += 1

                                # Final order with all X's filled in
                                nonmerged_order = combine_orderings(
                                    order_B_K_C_OY_OX_FY, order_FX)

                                # Merge loops of same type
                                merged_order = merge_loops(
                                    nonmerged_order, smallest_pfs)

                                # Check if merged order was already processed
                                hashed = hash(merged_order)
                                if hashed in merged_set:
                                    skipped += 1
                                    continue
                                else:
                                    merged_set.add(hashed)

                                ################################## MEMORY ALLOCATION ##################################

                                # Initialize Order object
                                order = Order(merged_order, spatial_loop,
                                              layer_origin, input_settings,
                                              n_mem_levels)

                                # Loop through all the nodes in each level to allocate the LPFs to the memories
                                for level in range(n_mem_levels):
                                    if level == n_mem_levels - 1:
                                        # If the level is the last level in the hierarchy, allocate all remaning LPFs.
                                        allocated_order = order.allocate_remaining(
                                        )
                                        break
                                    for node in nodes[level]:
                                        order.allocate_memory(node, level)

                                # print(merged_order)
                                # print('W\t', allocated_order['W'])
                                # print('I\t', allocated_order['I'])
                                # print('O\t', allocated_order['O'])

                                # if merged_order == ((5, 2), (5, 288), (4, 7), (6, 6)):
                                #     print(allocated_order['I'])

                                ################################## COST MODEL EVALUATION ##################################
                                # temporal_loop = TemporalLoopLight(layer_rounded, allocated_order, spatial_loop, order.loop_cycles, order.irrelevant_loop)
                                # loop = LoopLight(layer_rounded, temporal_loop, spatial_loop, input_settings.precision,
                                #                 input_settings.fixed_temporal_mapping)
                                temporal_loop = cls.TemporalLoop.extract_loop_info(
                                    layer_rounded, allocated_order,
                                    spatial_loop)
                                loop = cls.Loop.extract_loop_info(
                                    layer_rounded, temporal_loop, spatial_loop,
                                    input_settings.precision,
                                    input_settings.fixed_temporal_mapping)

                                # Greedy mapping: loop_fractional required
                                if input_settings.spatial_unrolling_mode in [
                                        4, 5
                                ]:
                                    ############# Advanced User Configuration #############
                                    # mem_energy_saving_when_BW_under_utilized = True
                                    #######################################################
                                    temporal_loop_fractional = cls.TemporalLoop.extract_loop_info(
                                        layer_origin, allocated_order,
                                        spatial_loop_fractional)
                                    loop_fractional = cls.Loop.extract_loop_info(
                                        layer_origin, temporal_loop_fractional,
                                        spatial_loop_fractional,
                                        input_settings.precision,
                                        input_settings.fixed_temporal_mapping)
                                    # if mem_energy_saving_when_BW_under_utilized is False:
                                    #     loop_fractional = mem_access_count_correct(loop_fractional, loop)

                                else:
                                    loop_fractional = loop

                                utilization = cls.Utilization.get_utilization(
                                    layer_rounded, temporal_loop,
                                    spatial_loop_comb, loop,
                                    input_settings.mac_array_info,
                                    mem_scheme.mem_size, mem_scheme.mem_share,
                                    mem_scheme.mem_type,
                                    input_settings.mac_array_stall,
                                    input_settings.precision,
                                    mem_scheme.mem_bw)
                                operand_cost = {'W': [], 'I': [], 'O': []}
                                total_cost_layer = 0
                                for operand in ['W', 'I', 'O']:
                                    for level in range(
                                            0, len(allocated_order[operand])):
                                        operand_cost[operand].append(
                                            cmf.get_operand_level_energy_cost(
                                                operand, level,
                                                mem_scheme.mem_cost,
                                                input_settings.mac_array_info,
                                                0, loop_fractional,
                                                mem_scheme.mem_fifo,
                                                mem_scheme,
                                                input_settings.precision,
                                                utilization, False))
                                    total_cost_layer += np.sum(
                                        operand_cost[operand])
                                total_cost_layer += active_mac_cost + idle_mac_cost

                                ############################# COMPARISON WITH BEST SO FAR #############################
                                en = total_cost_layer
                                ut = utilization.mac_utilize_no_load

                                if (en < min_en) or (en == min_en
                                                     and ut > min_en_ut):
                                    min_en = en
                                    min_en_ut = ut
                                    min_en_order = allocated_order
                                if (ut > max_ut) or (ut == max_ut
                                                     and en < max_ut_en):
                                    max_ut = ut
                                    max_ut_en = en
                                    max_ut_order = allocated_order
                                if save_all_tm:
                                    energy_collect.append(int(en))
                                    utilization_collect.append(ut)
                                    latency_collect.append(
                                        utilization.latency_no_load)

                                # if ctr % 1000 == 0:
                                #     print(ctr, "Execution time =", time.time()-t_start)
                                #     t_start = time.time()

    return (min_en, min_en_ut, min_en_order, max_ut_en, max_ut, max_ut_order,
            energy_collect, utilization_collect, latency_collect)
Example #16
0
from classes.order import Order

# create prodcut model
pm = ProductModel(db)
# create a product
# product = Product("Pinon",5000,"Togo")
# insert the product
# product = pm.insertProduct(product)

products = pm.getProducts()
product_list = []

for product in products:
    product_list.append(
        Product(product['name'], product['price'], product['country'],
                product['_id']))

cm = CustomerModel(db)
customer = Customer("Serge", "Kossi", "M", "92639417")
customer = cm.insertCustomer(customer)

om = OrderModel(db)
order = Order(customer)

for product in product_list:
    order.add_product(product)

order = om.insertOrder(order)

print(order)
Example #17
0
 def update_amount(self):
     op_sum = sum(self.list_orders, Order())
     self.amount = op_sum.amount
     self.cost = op_sum.price*self.amount
Example #18
0
 def test_invalid_customerId_setter(self):
     with self.assertRaises(
             ValueError,
             msg="Values passed should have raised a Value Error"):
         order = Order()
         order.setCustomerId(invalidCustomerId1)
Example #19
0
 def test_invalid_order_2(self):
     with self.assertRaises(
             ValueError,
             msg="Values passed should have raised a Value Error"):
         Order(invalidService2, invalidPickup2, invalidDropoff2,
               invalidCustomerId2, invalidStatus2)