Ejemplo n.º 1
0
    def move_stacks(self):
        game = self.__game

        game.stages[3].receive_delivery(game.stacks[15])
        game.stacks[15] = game.stacks[14]

        game.stages[2].receive_delivery(game.stacks[13])
        game.stacks[13] = game.stacks[12]

        game.stages[1].receive_delivery(game.stacks[11])
        game.stacks[11] = game.stacks[10]

        game.stages[0].receive_delivery(game.stacks[9])
        game.stacks[9] = game.stacks[8]

        d = Delivery(0)
        if game.stacks[7]:
            d.amount = game.stacks[7].amount
        game.stacks[8] = d

        game.stacks[7] = game.stacks[6]

        game.stages[0].receive_order(game.stacks[5])
        game.stacks[5] = game.stacks[4]

        game.stages[1].receive_order(game.stacks[3])
        game.stacks[3] = game.stacks[2]

        game.stages[2].receive_order(game.stacks[1])
        game.stacks[1] = game.stacks[0]
Ejemplo n.º 2
0
 def on_brieven( self, button ):
     dieren = []
     self.dialog = self.builder.get_object('dialog1')
     self.buffer = self.builder.get_object('briefresultaten')
     textview=self.builder.get_object('textview1')
     textview.set_buffer(self.buffer)
     self.next   = self.builder.get_object('button7')
     self.previous = self.builder.get_object('button6')
     self.first = self.builder.get_object('button9')
     
     self.type = 'Brief'
     for index, row in enumerate(self.store):
         if row[0]:
             dieren.append(row[2])
             order = self.find_order(index)
             if order:
                 result = order.get_result()
                 if not result:
                     self.letters[index] = 'bestelling voor {0},{1} nog niet uitgevoerd. Kies "picklijst" eerst.'.format(row[1], row[2]),\
                                           order.get_owner(), order.get_animal()
                 else:
                     if   order.get_ras() == 'KAT' and order.get_kind() == '100':
                         self.brief = self.kat100
                     elif order.get_ras() == 'HOND' and order.get_kind() == '100':
                         self.brief = self.hond100
                     elif order.get_ras() == 'KAT' and order.get_kind() == 'COMBI':
                         self.brief = self.katcombi
                     elif order.get_ras() == 'HOND' and order.get_kind() == 'COMBI':
                         self.brief = self.hondcombi
                     elif order.get_ras() == 'KAT' and order.get_kind() == 'PLUS':
                         self.brief = self.katplus
                     else:
                         self.brief = self.hondplus
                     d = Delivery(self.testdir, order, result)
                     res = d.csvout(True)
                     print res
                     weight = float(row[6])*order.get_weight()
                     if order.get_ras() == 'KAT':
                         weight *= 35
                     else:
                         weight *= 25
                     brief = self.brief.format("{:%d %B %Y}".format(datetime.date.today()),
                             order.get_owner(),
                             order.get_kind(),
                             order.get_animal(), order.get_weight(), weight,
                             order.get_kind(), order.get_kind())
                     self.letters[index] = brief+res, order.get_owner(), order.get_animal()
             else:
                 self.letters[index] = 'Geen bestelling voor {0},{1}'.format(row[1], row[2]), order.get_owner(), order.get_animal()
         #else:
         #    self.letters[index] = 'Geen bestelling voor {0},{1}'.format(row[1], row[2]), order.get_owner(), order.get_animal()
     self.buffer.set_text(self.letters[self.position][0])
     self.dialog.set_title("Brief voor {0},{1}".format(*self.letters[self.position][1:]))
     self.results = self.letters
     response = self.dialog.run()
Ejemplo n.º 3
0
 def on_picklijst( self, button ):
     dieren = []
     self.dialog = self.builder.get_object('dialog1')
     self.buffer = self.builder.get_object('picklijstresultaten')
     textview=self.builder.get_object('textview1')
     textview.set_buffer(self.buffer)
     self.next   = self.builder.get_object('button7')
     self.previous = self.builder.get_object('button6')
     self.first = self.builder.get_object('button9')
     
     self.type = 'Picklijst'
     for index, row in enumerate(self.store):
         if row[0]:
             dieren.append(row[2])
             order = self.find_order(index)
             order.set_portie(row[9])
             if order:
                 result = self.oervoer.process_order(order) #mealsize adjusted by factor
                 for ex in self.oervoer.exceptions:
                     warning('Geen {0} voor {1} afzondering\n {2}'.format(*ex), self.window)
                 self.oervoer.exceptions = []
                 d = Delivery(self.testdir, order, result)
                 res = '''datum: {7}\ndier: {0}\npakket: {1}\ngewicht dier: {2}\ngewicht pakket: {3}\nvermijd: {5}\nmaaltijd: {6}\n{4}'''.format(row[3],row[4],row[5], row[7], d.csvout(),
                                                                     ','.join(order.get_donts()),order.get_meal_size(),
                                                                     "{:%d %B %Y}".format(datetime.date.today() ))
                 print res
                 self.picklists[index] = res,order.get_owner(), order.get_animal()
             else:
                 self.picklists[index] = 'geen bestelling voor {0},{1}'.format(row[1], row[2]),'',''
     self.buffer.set_text(self.picklists[self.position][0])
     self.dialog.set_title('Picklijst voor {0},{1}'.format(*self.picklists[self.position][1:]))
     self.results = self.picklists
     response = self.dialog.run()
Ejemplo n.º 4
0
    def added_distance(self, delivery_start_time,
                       delivery_to_measure: Delivery):
        """
        Complexity: Big O(n)
        Calculate HOw many miles would be added if appending this delivery to this route
        """
        if len(self.deliveries) == 0:
            distance = get_distance(self.starting_location.address,
                                    delivery_to_measure.location.address)
            delivery_ETA = get_ETA(delivery_start_time,
                                   [delivery_to_measure]).time()
            if delivery_to_measure.earliest_deadline() > delivery_ETA:
                return distance, 0

        min_distance = None
        add_index = None
        for index in range(0, len(self.deliveries) + 1):
            deliveries_copy = self.deliveries.copy()
            deliveries_copy.insert(index, delivery_to_measure)
            added_distance_for_delivery = get_miles_of_delivery_route(
                self.starting_location, deliveries_copy)
            checks_pass = check_all_deliveries_arrive_by_deadline(
                delivery_start_time, deliveries_copy)
            if checks_pass is False:
                continue
            if (min_distance is None
                    or added_distance_for_delivery < min_distance):
                min_distance = round(added_distance_for_delivery, 2)
                add_index = index
        return (min_distance, add_index)
Ejemplo n.º 5
0
def main():
    db = Connector('danfes.db')

    while True:
        choice = menu()
        keys = []
        #Check
        if choice == 1:
            keys = db.retrieve_all_keys()
            key = menu_keys(keys)
            #If the selected key is higher than 0
            if key != 0:
                print(Delivery(key).get_events())
            else:
                continue
        #Register
        elif choice == 2:
            key = input("\nChave da DANFe: ")
            if len(key) >= 36:
                db.register(key)
            else:
                print("\nChave inválida!")
                continue
        #Delete
        elif choice == 3:
            keys = db.retrieve_all_keys()
            key = menu_keys(keys)
            #If the selected key is higher than 0
            if key != 0:
                db.delete(key)
            else:
                continue
Ejemplo n.º 6
0
 def get_delivery_by_type_no(self, delivery_type: str,
                             delivery_no: int) -> Delivery:
     raw_delivery = self.data.get_delivery_manager().get_each_delivery(
         delivery_type, delivery_no)
     if raw_delivery == 404:
         return None
     delivery = Delivery.from_json(raw_delivery)
     return delivery
Ejemplo n.º 7
0
    def deliver(self, stage: Stage, stackNumber):
        num_to_deliver = min(stage.inventory, stage.backlog)

        print(f"    Deliver {num_to_deliver}")
        stage.inventory -= num_to_deliver
        stage.backlog -= num_to_deliver

        d = Delivery(num_to_deliver)
        self.__game.stacks[stackNumber] = d
Ejemplo n.º 8
0
def fix_wrong_package_address(package_id, new_address):
    """
    Complexity: Big O(n^2)
    Fix the wrong package address
    update the deliveries the package is associated with
    """
    print('==================================================')
    print(f'correcting wrong address for package {package_id}')
    print('==================================================')
    correct_location = get_location_by_address(new_address)
    package_with_wrong_location = get_package_by_id(package_id)
    # Create a new delivery
    package_with_correct_address = package_with_wrong_location.update_location(correct_location)
    new_delivery = Delivery(correct_location, [package_with_correct_address])
    cfg.deliveries.append(new_delivery)
    cfg.truck3.assign_delivery(new_delivery, 0)
Ejemplo n.º 9
0
    def generate(self):
        numOfTrips = random.randint(1, parameters.customers)
        numOfDrones = random.randint(1, min(numOfTrips, parameters.maxDrones))

        #create deliveries for each customer (node)
        self.deliveries = [Delivery(x) for x in self.customers]
        #assign random delivery time to each delivery
        for delivery in self.deliveries:
            delivery.time = random.randint(parameters.minimumDeliveryTime,
                                           parameters.dayLength)

        #ensure each drone has at least one delivery
        for idx in range(numOfDrones):
            self.droneDeliveryAllocation[idx] = [self.deliveries[idx]]

        #populate rest of delivery assignment dictionary
        for idx in range(numOfDrones, len(self.deliveries)):
            droneAllocation = random.randrange(numOfDrones)
            self.droneDeliveryAllocation[droneAllocation].append(
                self.deliveries[idx])

        #create trips for each drone
        for droneNo, assignedDeliveries in self.droneDeliveryAllocation.items(
        ):
            assignedDeliveries.sort(
                key=lambda x: x.time
            )  #sort each drones deliveries so trips are in order

            #create trips within drone and add deliveries to trips
            trips = []
            startTime = 0
            while len(assignedDeliveries) > 0:
                if parameters.droneCargoSlots > len(assignedDeliveries):
                    maxNumber = len(assignedDeliveries)
                else:
                    maxNumber = parameters.droneCargoSlots
                numberInTrip = random.randint(
                    1, maxNumber
                )  #randomly choose a number of packages to be in the trip, min = 1, max = cargoSize
                trips.append(Trip(*assignedDeliveries[:numberInTrip]))
                del assignedDeliveries[:numberInTrip]
            self.drones.insert(droneNo, Drone(*trips))

        self.values = self.stringBuilder(
        )  #called last for problem file to be accurate
Ejemplo n.º 10
0
    def test_create_order(self):
        pizza_size = "small"
        pizza_type = "none"
        toppings = []
        drink = "coke"
        delivery_type = "pickup"
        address = "17 Wall Street"
        order = OrderCreator.get_instance().create_order(
            pizza_size,
            pizza_type,
            toppings,
            drink,
            delivery_type,
        )

        self.assertEqual(
            DeliveryCreator.get_instance().create_delivery(
                address, order, order.get_order_no()),
            Delivery(OrderCreator._delivery_no - 1, address, order,
                     order.get_order_no()))
def compare_mkp_solutions():
    print("Comparing up to brute force limits (n=8)")
    results = results_init()
    for i in range(10):
        deliveries = Delivery.generate(8)
        weight_limit = 250
        for algo in algorithms:
            t0 = perf_counter()
            path = algo(D=deliveries, W=weight_limit)
            results[algo.__name__]['time'] += perf_counter() - t0
            results[algo.__name__]['profit'] += path.profit
        print(f"Round {i+1}/10")
    pprint(results, width=50)

    print('Compared to brute force:')
    bf_res = results[algorithms[0].__name__]
    for algo in algorithms[1:]:
        n = algo.__name__
        print(f"{n}: "
              f"{results[n]['profit'] / bf_res['profit']:.1%} profit, "
              f"{bf_res['time'] / results[n]['time']:.0f}x faster")

    del algorithms[0]

    print("\nComparing up to combinatorial mst limits (n=16)")
    results = results_init()
    for i in range(10):
        deliveries = Delivery.generate(16)
        weight_limit = 250
        for algo in algorithms:
            t0 = perf_counter()
            path = algo(D=deliveries, W=weight_limit)
            results[algo.__name__]['time'] += perf_counter() - t0
            results[algo.__name__]['profit'] += path.profit
        print(f"Round {i+1}/10")
    pprint(results, width=50)

    print('Compared to combinatorial mst:')
    cmst_res = results[algorithms[0].__name__]
    for algo in algorithms[1:]:
        n = algo.__name__
        print(f"{n}: "
              f"{results[n]['profit'] / cmst_res['profit']:.1%} profit, "
              f"{cmst_res['time'] / results[n]['time']:.0f}x faster")

    del algorithms[0]

    print("\nComparing the two fast approximation algorithms (n=200)")
    results = results_init()
    for i in range(10):
        deliveries = Delivery.generate(250)
        weight_limit = 2000
        for algo in algorithms:
            t0 = perf_counter()
            path = algo(D=deliveries, W=weight_limit)
            results[algo.__name__]['time'] += perf_counter() - t0
            results[algo.__name__]['profit'] += path.profit
        print(f"Round {i+1}/10")
    pprint(results, width=50)

    print('Comparing:')
    for index in (0, 1):
        n1 = algorithms[index].__name__
        n2 = algorithms[not index].__name__
        print(f"{n1}: "
              f"{results[n1]['profit'] / results[n2]['profit']:.1%} profit, "
              f"{results[n2]['time'] / results[n1]['time']:.2f}x faster")

def mkp_mst(D, W):
    best_approx = DeliveryPath()

    for count in range(1, len(D)):
        continue_ = False
        for haul in combinations(D, count):
            shortest_path = DeliveryPath(haul)

            if shortest_path.weight > W:
                continue
            continue_ = True

            approx = DeliveryPath(haul)
            if approx > best_approx:
                best_approx = approx
        if not continue_:
            break

    return best_approx


if __name__ == '__main__':
    deliveries = Delivery.generate(20)
    weight_limit = 250
    path = mkp_mst(D=deliveries, W=weight_limit)
    path.plot(all_deliveries=deliveries)
    print(f"best profit: ${path.profit:.2f}")
    print(f"capacity used: {path.weight / weight_limit:.1%}")
Ejemplo n.º 13
0
 def create_delivery(self, address: str, order: Order,
                     order_no: int) -> Delivery:
     delivery = Delivery(order.get_delivery_no(), address, order, order_no)
     return delivery
Ejemplo n.º 14
0
# -*- coding: utf-8 -*-
try:
    from delivery import Delivery
except ModuleNotFoundError:
    from ejercicio_4.delivery import Delivery

if __name__ == '__main__':
    print(f"\n*********************************************")
    print(f"Executing exercise 3. ")
    print(f"First you'll be asked to name a table into enviame.db SQLite")
    print(f"If it's not created tell me")

    name_your_table = input('The name of the table?: ')
    delivery = Delivery(table=name_your_table)
    exists = input('Do you need to create the table first? (y/n): ')
    if exists.lower().index('y') != -1 or exists.lower().index('yes') != -1:
        delivery.create_db()
    print('Creating delivery! please wait...')
    delivery.create('BLX')
    print("You can see the result of api rest in backend/enviame.db")
    print("with your preferred DB browser.")

def brute_force_mkp(D, W):
    best_path = DeliveryPath()

    for count in range(len(D)):
        for haul in combinations(D, count + 1):
            new_path = DeliveryPath(haul, make_mst=False)

            if new_path.weight > W:
                continue

            for path in permutations(haul):
                path = DeliveryPath(path, make_mst=False)
                if path > new_path:
                    new_path = path

            if new_path.profit > best_path.profit:
                best_path = new_path

    return best_path


if __name__ == '__main__':
    deliveries = Delivery.generate(10)
    weight_limit = 250
    path = brute_force_mkp(D=deliveries, W=weight_limit)
    path.plot(all_deliveries=deliveries)
    print(f"best profit: ${path.profit:.2f}")
    print(f"capacity used: {path.weight / weight_limit:.1%}")
Ejemplo n.º 16
0
    def write_inventory(self):
        import csv
        name = '.'.join(self.productname.split('.')[:-1])+'.new.csv'
        
        f = file(name, 'w')
        fcsv = csv.writer(f)
        fcsv.writerow('store sku qty is_in_stock geschiktmenu name smaak type_vlees shelf weight'.split())
        
        for prodtype in self.prodlists.values():
            for prod in prodtype:
                fcsv.writerow (['admin', prod.sku, prod.qty, 1, 'Ja', prod.name, prod.smaak, prod.type, prod.shelf, prod.weight])
             
                
if __name__ == '__main__':
    testdir = os.getenv('OERVOERTESTENV') 
    if not testdir:
        testdir = '../test/'
    oervoer = Oervoer(testdir+'products.csv',testdir+'orders.csv',testdir+'picklists.csv')
    oervoer.parse_products()
    oervoer.parse_orders()
    for order in oervoer.ordlist:
        try:
            result = oervoer.process_order(order)
            d = Delivery(testdir, order, result)
            print d.csvout()
            oervoer.write_inventory()
        except NoProductsException,e:
            print e
            print '%s\nKan order %s-%s niet vervullen.\n%s\n' % ('^'*70, order.owner, order.animal,'#$'*35 )
    oervoer.dump()
Ejemplo n.º 17
0
def process_delivery(delivery: Delivery):
    delivery.calculate_delivery()
    print(delivery.show)
Ejemplo n.º 18
0
  1 Postal Service -> {PostalDelivery.percentage_to_increase_by}% increase
  2 Fedex -> {FedExDelivery.percentage_to_increase_by}% increase
  3 Opay -> {OpayDelivery.percentage_to_increase_by}% increase
""")


def process_delivery(delivery: Delivery):
    delivery.calculate_delivery()
    print(delivery.show)


while True:
    try:
        user_delivery_choice = int(input("Select 1 for postal, 2 for Fedex or 3 for Opay: "))
        if user_delivery_choice == 1:
            postal_delivery = Delivery(recipient_information, PostalDelivery())
            process_delivery(postal_delivery)
            break
        elif user_delivery_choice == 2:
            postal_delivery = Delivery(recipient_information, FedExDelivery())
            process_delivery(postal_delivery)
            break
        elif user_delivery_choice == 3:
            postal_delivery = Delivery(recipient_information, OpayDelivery())
            process_delivery(postal_delivery)
            break
        else:
            print("\nplease try again, so we can process your order\n")
    except ValueError:
        print("\nplease try again, so we can process your order\n")
Ejemplo n.º 19
0

def simple_scoring_func(de, order):
    # use vincenty distance and inverse it to give a score
    return 1000 - vincenty(de.get_latlong(), order.get_latlong()).km


if __name__ == "__main__":
    delivery_execs = []
    orders = []

    with open("conf.yaml", 'r') as stream:
        try:
            conf = yaml.load(stream)
            for d in conf["de"]:
                delivery_execs.append(Executive(d['id'], d['lat'], d['long']))
            for o in conf["orders"]:
                orders.append(Order(o['id'], o['lat'], o['long'], o['value']))
        except Exception as exc:
            print(exc)
            exit(1)

    # delivery_execs = [(12.9279232, 77.6271078), (12.92488806, 77.64945745)]
    # orders = [(12.92279665, 77.65190363), (12.92965641, 77.62925506)]

    driver = Delivery(delivery_execs, orders, simple_scoring_func)
    assignment, score = driver.assign()
    for d, o in assignment.iteritems():
        print d.id + "->" + o.id
    print score