示例#1
0
    def __init__(self, config_file):
        with open(config_file, 'r') as f:
            self.rows, self.cols, self.num_drones, self.num_turns, self.max_payload = get_line(f.readline())
            self.num_product_types = get_line_first(f.readline())
            weights = get_line(f.readline())
            self.products = []
            for idx in range(self.num_product_types):
                self.products.append(Product(idx, weights[idx]))

            self.num_warehouses = get_line_first(f.readline())
            self.warehouses = []
            for warehouse_idx in range(self.num_warehouses):
                loc = tuple(get_line(f.readline()))
                warehouse = Warehouse(warehouse_idx, loc)
                for prod_idx, prod_quant in enumerate(get_line(f.readline())):
                    prod = self.products[prod_idx]
                    warehouse.add_product(prod, prod_quant)
                self.warehouses.append(warehouse)

            self.num_orders = get_line_first(f.readline())
            self.orders = []
            for order_idx in range(self.num_orders):
                loc = tuple(get_line(f.readline()))
                order = Order(order_idx, loc)
                f.readline() #just skip cause we know it from the next line
                for prod_id in get_line(f.readline()):
                    prod = self.products[prod_id]
                    order.add_product(prod)
                self.orders.append(order)

            self.drones = [Drone(drone_idx, self.warehouses[0].location, self.max_payload) \
                           for drone_idx in range(self.num_drones)]
示例#2
0
 def test_give_unit_of_type(self):
     warehouse = Warehouse()
     unit = Unit('company', 'model1')
     warehouse.add_unit(unit)
     given_unit = warehouse.give_unit_of_type(Unit)
     self.assertEqual(unit, given_unit)
     self.assertRaises(NoUnitsLeft, warehouse.give_unit_of_type, Unit)
示例#3
0
 def __init__(self, name):
     self.position = [0, 0]
     self.docks = []
     self.unloading_warehouse = Warehouse(name="Unloading warehouse")
     self.loading_warehouse = Warehouse(name="Loading warehouse")
     self.fuel_magazine = FuelMagazine()
     self.size = 30
     self.name = name
 def setUp(self) -> None:
     super().setUp()
     self.warehouse = Warehouse(":memory:", create_tables=True)
     self.warehouse.create_product(Product("W1", "Вино", "Бутылка"))
     self.warehouse.create_product(Product("P1", "Пармезан", "Килограмм"))
     self.warehouse.create_product(Product("C1", "Колбаса", "Килограмм"))
     customer = self.warehouse.create_customer("Виталий Брагилевский")
     self.cid = customer.id
    def test_customer_placing_correct_order_creates_order(self):
        p = Product()
        w = Warehouse()
        w.add_product(p)
        c = Customer('test name', 'test address')
        initial_length = len(OPDept.orders)

        self.assertIsInstance(OPDept.create_order(c, p), Order)
        self.assertEqual(initial_length + 1, len(OPDept.orders))
示例#6
0
 def test_fill_board(self):
     warehouse = Warehouse(True)
     warehouse.board_width = 10
     warehouse.board_height = 10
     warehouse.init_board()
     test_item = [123, 'apples', 1, 6, 6]
     warehouse.add_item(test_item)
     warehouse.fill_board(0, warehouse.new_item_list[0], 1)
     self.assertEqual('1', warehouse.new_board[0][0], 'Passed')
示例#7
0
 def test_add_item(self):
     warehouse = Warehouse(True)
     test_list = [123, 'apples', 5, 6, 6]
     warehouse.add_item(test_list)
     self.assertEqual('apples', warehouse.new_item_list[0].name, 'Passed')
     self.assertEqual(123, warehouse.new_item_list[0].item_id, 'Passed')
     self.assertEqual(5, warehouse.new_item_list[0].quantity, 'Passed')
     self.assertEqual(6, warehouse.new_item_list[0].length, 'Passed')
     self.assertEqual(6, warehouse.new_item_list[0].width, 'Passed')
示例#8
0
 def test_packing(self):
     warehouse = Warehouse(True)
     warehouse.board_width = 10
     warehouse.board_height = 10
     warehouse.init_board()
     test_item = [123, 'apples', 1, 6, 6]
     warehouse.add_item(test_item)
     self.assertEqual(0, len(warehouse.complete_list), 'Passed')
     warehouse.packing(warehouse.new_item_list)
     self.assertEqual(1, len(warehouse.complete_list), 'Passed')
示例#9
0
 def test_create_rect(self):
     warehouse = Warehouse(test_flag=True)
     visualize = VisualizeWarehouse(test_flag=True)
     visualize.screen_buffer = 10
     visualize.width_segment = 40
     visualize.height_segment = 40
     test_board = [['0', '0', '1', '1', '0'], ['0', '0', '1', '1', '0'],
                   ['0', '0', '1', '1', '0']]
     test_item = [123, 'apples', 1, 6, 6]
     warehouse.add_item(test_item)
     result = visualize.create_item_rect(test_board,
                                         warehouse.new_item_list)
     self.assertEqual(1, len(visualize.rectangle_list), 'Passed')
示例#10
0
    def test_not_enough_inventory_for_multiple_items(self):
        # no warehouses
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, []))

        # warehouse object is null
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, [Warehouse()]))

        # warehouse exist, but does not have item
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, [Warehouse('wh1', {'item2': 10})]))

        # not enough quantity in a single warehouse
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, [Warehouse('wh1', {'item1': 5})]))

        # not enough quantity in a multiple warehouses
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, [
                                 Warehouse('wh1', {'item1': 5}),
                                 Warehouse('wh2', {'item1': 2}),
                                 Warehouse('wh3', {'item1': 2})
                             ]))

        # enough quantity in for an item, but not the rest of the order
        self.assertEqual([],
                         InventoryAllocator().allocate_order(
                             {
                                 'item1': 10,
                                 'item2': 10
                             }, [
                                 Warehouse('wh1', {'item1': 5}),
                                 Warehouse('wh2', {'item1': 5}),
                                 Warehouse('wh3', {'item1': 5})
                             ]))
示例#11
0
文件: main.py 项目: grugnog/pylytics
    def run(self, command, *facts):
        """ Run command for each fact in facts.
        """
        all_fact_classes = get_all_fact_classes()

        # Normalise the collection of facts supplied to remove duplicates,
        # expand "all" and report unknown facts.
        if 'all' in facts:
            facts_to_run = all_fact_classes
        elif 'scheduled' in facts:
            facts_to_run = find_scheduled(all_fact_classes)
        else:
            facts_to_run = []
            fact_names = [type(fact()).__name__ for fact in all_fact_classes]
            for fact_name in facts:
                try:
                    index = fact_names.index(fact_name)
                except ValueError:
                    log.debug('Unrecognised fact %s' % fact_name)
                else:
                    facts_to_run.append(all_fact_classes[index])

            # Remove any duplicates:
            facts_to_run = list(set(facts_to_run))

        if command != 'template':
            _connection = connection.get_named_connection(settings.pylytics_db)
            Warehouse.use(_connection)

        # Execute the command on each fact class.
        for fact_class in facts_to_run:
            try:
                command_function = getattr(fact_class, command)
            except AttributeError:
                log.error("Cannot find command %s for fact class %s", command,
                          fact_class)
                continue

            try:
                command_function()
            except Exception as exception:
                # Catch all exceptions so one failed command doesn't bring
                # down all facts.
                log.error("%s.%s failed: %s, %s", fact_class, command,
                          exception.__class__, exception.message)

        if command != 'template':
            # Close the Warehouse connection.
            log.info('Closing Warehouse connection.')
            Warehouse.get().close()
示例#12
0
    def test_enough_inventory_for_single_item(self):
        # single warehouse with single item in inventory -- exact quantity
        self.assertEqual([{
            'wh1': {
                'item1': 10
            }
        }],
                         InventoryAllocator().allocate_order(
                             {'item1': 10}, [Warehouse('wh1', {'item1': 10})]))

        # single warehouse with single item in inventory -- over quantity
        self.assertEqual([{
            'wh1': {
                'item1': 10
            }
        }],
                         InventoryAllocator().allocate_order(
                             {'item1': 10}, [Warehouse('wh1', {'item1': 20})]))

        # multiple warehouses -- multiple items in inventory -- over quantity in first warehouse
        self.assertEqual([{
            'wh1': {
                'item1': 10
            }
        }],
                         InventoryAllocator().allocate_order({'item1': 10}, [
                             Warehouse('wh1', {'item1': 10}),
                             Warehouse('wh2', {'item1': 20})
                         ]))

        # multiple warehouses -- multiple items in inventory -- not enough quantity in first warehouse
        self.assertEqual([{
            'wh1': {
                'item1': 4
            }
        }, {
            'wh2': {
                'item1': 6
            }
        }],
                         InventoryAllocator().allocate_order({'item1': 10}, [
                             Warehouse('wh1', {'item1': 4}),
                             Warehouse('wh2', {'item1': 20})
                         ]))

        # multiple warehouses -- exact quantity needed
        self.assertEqual([{
            'wh1': {
                'item1': 4
            }
        }, {
            'wh2': {
                'item1': 6
            }
        }],
                         InventoryAllocator().allocate_order({'item1': 10}, [
                             Warehouse('wh1', {'item1': 4}),
                             Warehouse('wh2', {'item1': 6})
                         ]))
    def setUp(self):
        """ Create some objects: one Warehouse, one Shelf, three of each
            Container type (Bin, Box, Bag), and three each of four different
            sizes of Item.
        """
        self.warehouse = Warehouse()
        self.shelf = Shelf()
        self.bin1, self.bin2, self.bin3 = [Bin() for _ in range(3)]
        self.box1, self.box2, self.box3 = [Box() for _ in range(3)]
        self.bag1, self.bag2, self.bag3 = [Bag() for _ in range(3)]

        self.itemS1, self.itemS2, self.itemS3 = [Item(1) for _ in range(3)]
        self.itemM1, self.itemM2, self.itemM3 = [Item(6) for _ in range(3)]
        self.itemL1, self.itemL2, self.itemL3 = [Item(10) for _ in range(3)]
        self.itemXL1, self.itemXL2, self.itemXL3 = [Item(15) for _ in range(3)]
    def transfer_remaining_orders_to_warehouses(self):
        # find the closest warehouse pairs.
        w2w_distances = Warehouse.calc_w2w_distances(self.warehouses)
        orders = dd(list)
        for w in self.warehouses:
            for order in w.orders:
                for product in order:
                    # product id
                    w1 = Warehouse.find_product_closest_warehouse(product, w2w_distances[w.id])
                    # key: (from_warehouse, to_warehouse)
                    orders[(w1.id, w.id)].append(product)

        optimized_orders = {}
        for k, order_list in orders.iteritems():
            optimized_orders[k] = Counter(order_list)
示例#15
0
    def run(self, command, *facts):
        """ Run command for each fact in facts.
        """
        all_fact_classes = get_all_fact_classes()

        # Normalise the collection of facts supplied to remove duplicates,
        # expand "all" and report unknown facts.
        if "all" in facts:
            facts_to_run = all_fact_classes
        elif "scheduled" in facts:
            facts_to_run = find_scheduled(all_fact_classes)
        else:
            facts_to_run = []
            fact_names = [type(fact()).__name__ for fact in all_fact_classes]
            for fact_name in facts:
                try:
                    index = fact_names.index(fact_name)
                except ValueError:
                    log.debug("Unrecognised fact %s" % fact_name)
                else:
                    facts_to_run.append(all_fact_classes[index])

            # Remove any duplicates:
            facts_to_run = list(set(facts_to_run))

        if command != "template":
            _connection = connection.get_named_connection(settings.pylytics_db)
            Warehouse.use(_connection)

        # Execute the command on each fact class.
        for fact_class in facts_to_run:
            try:
                command_function = getattr(fact_class, command)
            except AttributeError:
                log.error("Cannot find command %s for fact class %s", command, fact_class)
                continue

            try:
                command_function()
            except Exception as exception:
                # Catch all exceptions so one failed command doesn't bring
                # down all facts.
                log.error("%s.%s failed: %s, %s", fact_class, command, exception.__class__, exception.message)

        if command != "template":
            # Close the Warehouse connection.
            log.info("Closing Warehouse connection.")
            Warehouse.get().close()
示例#16
0
def main():
    rospy.init_node('warehouse')

    if not rospy.has_param('~size'):
        raise rospy.ROSInitException('Parameter "size" must be set [length, height]')
    if not rospy.has_param('~offset'):
        raise rospy.ROSInitException('Parameter "offset" must be set [length, height]')
    if not rospy.has_param('~warehouse'):
        raise rospy.ROSInitException('Parameter "warehouse" muse be set "raws" or "goods"')
    if not rospy.has_param('~content'):
        raise rospy.ROSInitException('Items type must be specified in parameter "content"')

    warehouse_size = ast.literal_eval(rospy.get_param('~size'))
    global warehouse_offset
    warehouse_offset = ast.literal_eval(rospy.get_param('~offset'))

    global wh
    wh = Warehouse(warehouse_size)

    rospy.Service('~place', Place, handle_place)  # put item in cell
    rospy.Service('~order', Order, handle_order)  # get item from cell
    rospy.Service('~fill_all', FillAll, handle_fill_all)
    rospy.Service('~empty_all', EmptyAll, handle_empty_all)
    rospy.Service('~quantity_available', QuantityAvailable, handle_quantity_available)
    rospy.Service('~content', Content, handle_content)

    rospy.spin()
示例#17
0
    def create_trigger(cls):
        """ There's a constraint in earlier versions of MySQL where only one
        timestamp column can have a CURRENT_TIMESTAMP default value.

        These triggers get around that problem.

        Returns:
            True if a trigger was created, or False if the trigger already
            exists.

        """
        if cls.trigger_name in Warehouse.trigger_names:
            log.info('%s already exists - skipping.' % cls.trigger_name)
            return False

        trigger = """\
        CREATE TRIGGER %s
        BEFORE INSERT ON %s
        FOR EACH ROW BEGIN
            IF NEW.created = '0000-00-00 00:00:00' THEN
                SET NEW.created = NOW();
            END IF;
        END
        """ % (cls.trigger_name, cls.__tablename__)

        connection = Warehouse.get()
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute(trigger)
            except Exception as exception:
                classify_error(exception)
                raise exception
            else:
                log.info('%s created.' % cls.trigger_name)
                return True
    def __init__(self,
                 rows,
                 cols,
                 edge_base_cost=1.,
                 occupancy_cost=0.,
                 n_agents=10,
                 n_tasks=100,
                 lam=1.,
                 seed=0):
        set_seed(s=seed)

        self._w = Warehouse(rows,
                            cols,
                            node_capacity=-1,
                            edge_base_cost=edge_base_cost,
                            occupancy_cost=occupancy_cost)
        self._w_manager = WarehouseManager(self._w, n_agents)
        nodes = self._w_manager.nodes()

        num_tasks_per_iteration = create_tasks_arrivals(n_tasks, lam)
        self._task_arrivals = []
        for x in num_tasks_per_iteration:
            self._task_arrivals.append([sample_nodes(nodes)] * x)

        self._processed_ticks = 0
        self._only_wip_ticks = 0
示例#19
0
    def select(cls, for_class, since=None):
        extra = {"table": for_class.__tablename__}

        log.debug("Fetching rows from staging table", extra=extra)

        events = list(getattr(cls, "events"))
        sql = """\
        SELECT id, event_name, value_map FROM staging
        WHERE event_name IN (%s)
        ORDER BY created, id
        """ % ",".join(map(dump, events))
        log.debug(sql)

        connection = Warehouse.get()
        with closing(connection.cursor(raw=False)) as cursor:
            cursor.execute(sql)
            results = cursor.fetchall()

        for id_, event_name, value_map in results:
            try:
                data = {"__event__": event_name}
                data.update(json.loads(unicode(value_map)))
                cls._apply_expansions(data)
                inst = hydrated(for_class, data)
            except Exception as error:
                log.error("Unable to hydrate %s record (%s: %s) -- %s",
                          for_class.__name__, error.__class__.__name__, error,
                          value_map, extra=extra)
            else:
                yield inst
            finally:
                # We'll recycle the row regardless of whether or
                # not we've been able to hydrate and yield it. If
                # broken, it gets logged anyway.
                cls.__recycling.add(id_)
示例#20
0
    def create_table(cls):
        """ Create this table in the current data warehouse.

        Returns:
            True if the table was created, or False if the table already
            exists.

        """
        if cls.table_exists:
            log.info('%s already exists - skipping.' % cls.__tablename__)
            return False

        verb = "CREATE TABLE"
        columns = ",\n  ".join(col.expression for col in cls.__columns__)
        sql = "%s %s (\n  %s\n)" % (verb, cls.__tablename__, columns)
        for key, value in cls.__tableargs__.items():
            sql += " %s=%s" % (key, value)

        connection = Warehouse.get()
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute(sql)
            except Exception as exception:
                classify_error(exception)
                raise exception
            else:
                return True
示例#21
0
    def __init__(self, path):
        self.path = path
        input_data = self._get_input(path)
        self.deadline = input_data["deadline"]
        self.rows = input_data["rows"]
        self.columns = input_data["columns"]

        self.num_products = input_data["num_products"]
        self.num_drones = input_data["num_drones"]
        self.num_orders = input_data["num_orders"]
        self.num_warehouses = input_data["num_warehouses"]
        self.max_load = input_data["max_load"]

        self.products = [
            Product(weight) for weight in input_data["product_weights"]
        ]
        self.warehouses = [
            Warehouse(wh["row"], wh["column"], wh["stock"])
            for wh in input_data["warehouses"]
        ]
        self.drones = [
            Drone(i, self.warehouses, input_data["max_load"])
            for i in range(input_data["num_drones"])
        ]
        self.orders = [
            Order(i, order["row"], order["column"], order["product_ids"])
            for i, order in enumerate(input_data["orders"])
        ]
示例#22
0
    def create_table(cls):
        """ Create this table in the current data warehouse.

        Returns:
            True if the table was created, or False if the table already
            exists.

        """
        if cls.table_exists:
            log.info('%s already exists - skipping.' % cls.__tablename__)
            return False

        verb = "CREATE TABLE"
        columns = ",\n  ".join(col.expression for col in cls.__columns__)
        sql = "%s %s (\n  %s\n)" % (verb, cls.__tablename__, columns)
        for key, value in cls.__tableargs__.items():
            sql += " %s=%s" % (key, value)

        connection = Warehouse.get()
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute(sql)
            except Exception as exception:
                classify_error(exception)
                raise exception
            else:
                return True
示例#23
0
    def create_trigger(cls):
        """ There's a constraint in earlier versions of MySQL where only one
        timestamp column can have a CURRENT_TIMESTAMP default value.

        These triggers get around that problem.

        Returns:
            True if a trigger was created, or False if the trigger already
            exists.

        """
        if cls.trigger_name in Warehouse.trigger_names:
            log.info('%s already exists - skipping.' % cls.trigger_name)
            return False

        trigger = """\
        CREATE TRIGGER %s
        BEFORE INSERT ON %s
        FOR EACH ROW BEGIN
            IF NEW.created = '0000-00-00 00:00:00' THEN
                SET NEW.created = NOW();
            END IF;
        END
        """ % (cls.trigger_name, cls.__tablename__)

        connection = Warehouse.get()
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute(trigger)
            except Exception as exception:
                classify_error(exception)
                raise exception
            else:
                log.info('%s created.' % cls.trigger_name)
                return True
示例#24
0
    def __init__(self, configuration):
        self._ressources = Ressources(configuration)

        # build a dict with all keys
        # contains all units available
        self._units = Warehouse("units", configuration)

        #contains all defenses available
        self._defenses = Warehouse("defenses", configuration)

        # define tech available
        self._tech = Warehouse("tech", configuration)

        # mail box
        # @TODO
        self._mail_box = []
示例#25
0
 def __init__(self, pickle=False):
     if pickle == False:
         warehouse_zips = db.getDataFromString('exec dbo.facility')[:100]
         zip_data_class = ZipCodesData()
         self.distribution_centers(zip_data_class)
         self.warehouses = []
         self.warehouses.extend(self.dcs)
         self.ranking = Ranking()
         for i in warehouse_zips:
             self.warehouses.append(
                 Warehouse(i[0], i[1], i[2], i[3], i[4], i[5]))
         zips = db.getDataFromString('exec dbo.zipcode')
         self.zips = {}
         dc_cords = []
         for i in self.dcs:
             dc_cords.append(i.get_cordinates())
         for i in self.warehouses:
             dc_cords.append(i.get_cordinates())
         for i in zips:
             try:
                 int(i[0][:5])
                 zip = ('00000' + str(i[0][:5]))[-5:]
             except:
                 zip = i[0]
             cords = zip_data_class.get_cordinates(zip)
             state = zip_data_class.get_state(zip)
             self.zips[zip] = ZipCode(zip, cords, state)
             self.zips[zip].get_serviceable_array(dc_cords)
     else:
         self.pickle_load()
示例#26
0
 def distribution_centers(self, zipcodes):
     """created self.dcs object"""
     dcs = [['Sainte-Croix', 'G0S 2H0'], ['Coaticook', 'J1A 1Z5'], ['Juarez', '31000']\
     , ['Nashville', '37011'], ['Salt Lake', '84044']]
     self.dcs = []
     for i in dcs:
         cords = zipcodes.get_cordinates(i[1])
         self.dcs.append(Warehouse(i[0], i[1], 2, 4, cords[0], cords[1]))
示例#27
0
def main():
    #Initial grid
    width = 10
    height = 10
    grid = Grid(width, height)

    #Initial warehouse
    robots_path = r'../warehouse/robots.json'
    goods_path = r'../warehouse/goods.json'
    requests_path = r'../requests/requests.json'
    goals = set([(0, 0), (0, 3), (0, 6), (0, 9)])
    warehouse = Warehouse(grid, goals)
    warehouse.load_robots(robots_path)
    warehouse.load_goods(goods_path)
    warehouse.load_requests(requests_path)

    warehouse.maintain()
示例#28
0
def load_data():
    ipt_file = open(input_file + ".in", "r")
    lines = ipt_file.read().split("\n")
    init_info = lines[0].split(" ")

    rows = int(init_info[0])
    cols = int(init_info[1])
    n_drones = int(init_info[2])
    turns = int(init_info[3])
    max_weight = int(init_info[4])
    
    #Init drones
    drones = [0]*n_drones
    for i in range(n_drones):
        drones[i] = Drone(i)

    #Items
    #n_items = int(lines[1])
    _items = lines[2].split(" ")
    items = [0]*len(_items)
    for i in range(len(_items)):
        items[i] = int(_items[i])

    #Warehouses    
    n_wh = int(lines[3])
    warehouses = [0]*n_wh
    for i in range(n_wh):
        wh_pos = lines[4 + i*2].split(" ")
        wh_items = lines[5 + i*2].split(" ")
        warehouses[i] = Warehouse(i, int(wh_pos[0]), int(wh_pos[1]))
        warehouses[i].items = [0]*len(wh_items)
        for j in range(len(wh_items)):
            warehouses[i].items[j] = int(wh_items[j])
        
    #Orders
    init_idx = 4 + n_wh*2
    n_orders = int(lines[init_idx])
    orders = [0]*n_orders
    for i in range(n_orders):
        orders_pos = lines[init_idx+1 + i*3].split(" ")
        orders_items = lines[init_idx+1 + (i*3)+2].split(" ")
        orders[i] = Order(orders_pos[0], orders_pos[1])
        orders[i].items = [0]*len(orders_items)
        for j in range(len(orders_items)): #convertim a int
            orders[i].items[j] = int(orders_items[j])
    def test_warehouse_create(self):
        self.assertEqual(test_1.name, "test 1")
        self.assertEqual(test_1.inventory, {"apples": 5})

        self.assertEqual(test_2.name, "test 2")
        self.assertEqual(test_2.inventory, {
            "banana": 5,
            "apples": 10,
            "pears": 7
        })

        self.assertEqual(test_3.name, "test 3")
        self.assertEqual(test_3.inventory, {})

        with self.assertRaises(TypeError):
            Warehouse("invalid warehouse", 5)
        with self.assertRaises(TypeError):
            Warehouse("invalid warehouse", "string")
示例#30
0
def load():
	"""
        opens a load dialogue window to load a file and creates a WHreader and a Warehouse object
    """
	filename = filedialog.askopenfilename(parent=win)
	global read_setting
	read_setting = WHreader(filename)	#read in the content of the file
	global whouse_object # create an actual warehouse object with the content of the file
	whouse_object = Warehouse(WHreader(filename).stock, WHreader(filename).psus)
示例#31
0
 def test_check_available_area(self):
     warehouse = Warehouse(True)
     test_list = [123, 'apples', 1, 6, 6]
     warehouse.add_item(test_list)
     test_list_2 = [456, 'oranges', 2, 2, 2]
     warehouse.add_item(test_list_2)
     test_true = warehouse.check_available_area(warehouse.new_item_list, 44)
     test_false = warehouse.check_available_area(warehouse.new_item_list,
                                                 10)
     self.assertEqual(True, test_true, 'Passed')
     self.assertEqual(False, test_false, 'Passed')
示例#32
0
class WarehouseTests(unittest.TestCase):
    def setUp(self):
        self.warehouse = Warehouse()
        self.warehouse.add('Glenlivit', 10)

    def test_warehouse_shows_new_inventory(self):
        self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 10)

    def test_warehouse_shows_added_inventory(self):
        self.warehouse.add('Glenlivit', 15)
        self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 25)

    def test_warehouse_shows_removed_inventory(self):
        self.warehouse.remove('Glenlivit', 10)
        self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 0)
示例#33
0
class CarFactory(object):
    def __init__(self):
        self.warehouse = Warehouse() #magazyn
        self.list_orders = []


    def take_order(self, order):
        self.list_orders.append(order)
        print("I added car order to list_orders")

    def get_car(self):
        print(f"We've in list_orders {len(self.list_orders)} car/s. Build car in progres..")
        order = self.list_orders[0]
        car_body = self.warehouse.get_car_body()
        engine = self.warehouse.get_engine(order)
        drive = self.warehouse.get_drive(order)
        car = Car(car_body, engine, drive)
        car_body.paint(order.colour)
        return car
示例#34
0
def parse(inFileName):

    with open(inFileName, "r") as inFile:

        header = inFile.readline()
        rows, columns, nr_drones, nr_turns, max_payload = list(
            map(int,
                header.strip().split(" ")))

        # read product types
        nr_products = int(inFile.readline())
        products = list(map(int, inFile.readline().strip().split(" ")))
        assert len(products) == nr_products

        # read warehouses
        nr_warehouses = int(inFile.readline())
        warehouses = []
        for i in range(nr_warehouses):
            pos = tuple(map(int, inFile.readline().strip().split(" ")))
            items = list(map(int, inFile.readline().strip().split(" ")))
            assert len(items) == nr_products
            warehouses.append(Warehouse(i, pos, items))

        assert len(warehouses) == nr_warehouses

        # read orders
        nr_orders = int(inFile.readline())
        orders = []
        lines = inFile.readlines()
        for i, (pos, nr_items,
                items) in enumerate(zip(lines[::3], lines[1::3], lines[2::3])):
            pos = tuple(map(int, pos.split(" ")))
            items = list(map(int, items.strip().split(" ")))
            assert int(nr_items) == len(items)
            orders.append(Order(id=i, pos=pos, items=items))

        assert len(orders) == nr_orders

        # init drones to simulate
        drones = []
        first_warehouse = warehouses[0]
        for i in range(nr_drones):
            drone = Drone(pos=first_warehouse.pos,
                          id=i,
                          max_payload=max_payload)
            drones.append(drone)

        return State(rows=rows,
                     columns=columns,
                     nr_turns=nr_turns,
                     max_payload=max_payload,
                     products=products,
                     warehouses=warehouses,
                     orders=orders,
                     drones=drones)
示例#35
0
class WarehouseTests(unittest.TestCase):

    def setUp(self):
        self.warehouse = Warehouse()
        self.warehouse.add('Glenlivit', 10)

    def test_warehouse_shows_new_inventory(self):
       self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 10)

    def test_warehouse_shows_added_inventory(self):
        self.warehouse.add('Glenlivit', 15)
        self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 25)

    def test_warehouse_shows_removed_inventory(self):
        self.warehouse.remove('Glenlivit', 10)
        self.assertEqual(self.warehouse.get_inventory('Glenlivit'), 0)
示例#36
0
 def finish(cls, for_class):
     if cls.__recycling:
         sql = "DELETE FROM staging WHERE id in (%s)" % (",".join(
             map(str, cls.__recycling)))
         connection = Warehouse.get()
         try:
             with closing(connection.cursor()) as cursor:
                 cursor.execute(sql)
         except:
             log.error('Unable to clear staging.')
         cls.__recycling.clear()
示例#37
0
 def finish(cls, for_class):
     if cls.__recycling:
         sql = "DELETE FROM staging WHERE id in (%s)" % (
             ",".join(map(str, cls.__recycling)))
         connection = Warehouse.get()
         try:
             with closing(connection.cursor()) as cursor:
                 cursor.execute(sql)
         except:
             log.error('Unable to clear staging.')
         cls.__recycling.clear()
示例#38
0
    def insert(cls, *instances):
        """ Insert one or more instances into the table as records.
        """
        if instances:
            columns = [
                column for column in cls.__columns__
                if not isinstance(column, AutoColumn)
            ]

            sql = "%s INTO %s (\n  %s\n)\n" % (
                cls.INSERT, escaped(cls.__tablename__), ",\n  ".join(
                    escaped(column.name) for column in columns))

            batches = cls.batch(instances)
            for iteration, batch in enumerate(batches, start=1):
                log.debug('Inserting batch %s' % (iteration),
                          extra={"table": cls.__tablename__})

                insert_statement = sql
                link = "VALUES"

                for instance in batch:
                    values = []
                    for column in columns:
                        value = instance[column.name]
                        values.append(dump(value))
                    insert_statement += link + (" (\n  %s\n)" %
                                                ",\n  ".join(values))
                    link = ","

                for i in range(1, 3):
                    connection = Warehouse.get()
                    try:
                        cursor = connection.cursor()
                        cursor.execute(insert_statement)
                        cursor.close()

                    except Exception as e:
                        classify_error(e)
                        if e.__class__ == BrokenPipeError and i == 1:
                            log.info(
                                'Trying once more with a fresh connection',
                                extra={"table": cls.__tablename__})
                            connection.close()
                        else:
                            log.error(e)
                            return
                    else:
                        connection.commit()
                        break

        log.debug('Finished updating %s' % cls.__tablename__,
                  extra={"table": cls.__tablename__})
示例#39
0
    def insert(cls, *instances):
        """ Insert one or more instances into the table as records.
        """
        if instances:
            columns = [column for column in cls.__columns__
                       if not isinstance(column, AutoColumn)]

            sql = "%s INTO %s (\n  %s\n)\n" % (
                cls.INSERT, escaped(cls.__tablename__),
                ",\n  ".join(escaped(column.name) for column in columns))

            batches = cls.batch(instances)
            for iteration, batch in enumerate(batches, start=1):
                log.debug('Inserting batch %s' % (iteration),
                          extra={"table": cls.__tablename__})

                insert_statement = sql
                link = "VALUES"

                for instance in batch:
                    values = []
                    for column in columns:
                        value = instance[column.name]
                        values.append(dump(value))
                    insert_statement += link + (" (\n  %s\n)" % ",\n  ".join(values))
                    link = ","

                for i in range(1, 3):
                    connection = Warehouse.get()
                    try:
                        cursor = connection.cursor()
                        cursor.execute(insert_statement)
                        cursor.close()

                    except Exception as e:
                        classify_error(e)
                        if e.__class__ == BrokenPipeError and i == 1:
                            log.info(
                                'Trying once more with a fresh connection',
                                extra={"table": cls.__tablename__}
                                )
                            connection.close()
                        else:
                            log.error(e)
                            return
                    else:
                        connection.commit()
                        break

        log.debug('Finished updating %s' % cls.__tablename__,
                  extra={"table": cls.__tablename__})
示例#40
0
    def test_warehouse_report(self):
        OPDept.warehouses = []
        Warehouse()
        w2 = Warehouse()
        p = Product()
        p2 = Product()
        p3 = Product()
        w2.products = {
            p.number: '3',
            p2.number: '1',
            p3.number: '5'
        }

        expected_warehouse_report = {
            'zero_stock': 1,
            'total_products': 9
        }

        report = OPDept.report()
        self.assertEqual(
            report['warehouse_report'],
            expected_warehouse_report
        )
示例#41
0
    def insert(cls, *instances):
        """ Insert fact instances (overridden to handle Dimensions correctly)
        """
        if instances:
            columns = [column for column in cls.__columns__
                       if not isinstance(column, AutoColumn)]
            sql = "%s INTO %s (\n  %s\n)\n" % (
                cls.INSERT, escaped(cls.__tablename__),
                ",\n  ".join(escaped(column.name) for column in columns))

            batches = cls.batch(instances)
            for iteration, batch in enumerate(batches, start=1):
                log.debug('Inserting batch %s' % (iteration),
                          extra={"table": cls.__tablename__})

                insert_statement = sql
                link = "VALUES"

                for instance in batch:
                    values = []
                    for column in columns:
                        value = instance[column.name]
                        if isinstance(column, DimensionKey):
                            if not value and column.optional:
                                values.append(dump(value))
                            else:
                                values.append(
                                    "(%s)" % column.dimension.__subquery__(
                                        value,
                                        instance.__dimension_selector__.timestamp(instance) # TODO This is a bit messy - shouldn't have to pass the instance back in.
                                        )
                                    )
                        else:
                            values.append(dump(value))
                    insert_statement += link + (" (\n  %s\n)" % ",\n  ".join(values))
                    link = ","

                connection = Warehouse.get()
                try:
                    with closing(connection.cursor()) as cursor:
                        cursor.execute(insert_statement)
                except Exception as e:
                    classify_error(e)
                    log.error(e)
                    log.error(insert_statement)
                    connection.rollback()
                else:
                    connection.commit()
示例#42
0
    def drop_table(cls, if_exists=False):
        """ Drop this table from the current data warehouse.
        """
        if if_exists:
            verb = "DROP TABLE IF EXISTS"
        else:
            verb = "DROP TABLE"
        sql = "%s %s" % (verb, cls.__tablename__)

        connection = Warehouse.get()
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute(sql)
            except:
                connection.rollback()
            else:
                connection.commit()
示例#43
0
class OrderTests(unittest.TestCase):

    def setUp(self):
        self.warehouse = Warehouse()
        self.warehouse.add(TALISKER, 50)
        self.warehouse.add(HIGHLAND_PARK, 25)

    def test_order_is_filled_if_enough_in_warehouse(self):
        order = Order(TALISKER, 50)
        order.fill(self.warehouse)
        self.assertTrue(order.is_filled())
        self.assertEqual(self.warehouse.get_inventory(TALISKER), 0)

    def test_order_does_not_remove_if_not_enough(self):
        order = Order(TALISKER, 51)
        order.fill(self.warehouse)
        self.assertFalse(order.is_filled())
        self.assertEqual(self.warehouse.get_inventory(TALISKER), 50)
示例#44
0
 def setUp(self):
     self.warehouse = Warehouse()
     self.warehouse.add(TALISKER, 50)
     self.warehouse.add(HIGHLAND_PARK, 25)
示例#45
0
class Player:
    # This class contains all player data.
    # it is just a wrapper around warehouse class.
    def __init__(self, configuration):
        self._ressources = Ressources(configuration)

        # build a dict with all keys
        # contains all units available
        self._units = Warehouse("units", configuration)

        #contains all defenses available
        self._defenses = Warehouse("defenses", configuration)

        # define tech available
        self._tech = Warehouse("tech", configuration)

        # mail box
        # @TODO
        self._mail_box = []

    def check_min_ressources(self, values):
        # from a list a ressource values, return True if ressources are available
        self._ressources.is_available(values)

    def check_min_units(self, units):
        # check a min quantity of units
        return self._units.check_min(units)

    def check_min_tech(self, tech):
        # check a min tech level
        return  self._tech.check_min(tech)

    def get_ressources(self):
        return zip(self._ressources.get_value(), self._ressources.get_delta())

    def get_units(self):
        return self._units.get()

    def get_defenses(self):
        return self._defenses.get()

    def get_tech(self):
        return self._tech.get()

    def add_units(self, units):
        self._units.add(units)

    def add_defenses(self, defenses):
        self._defenses.add(defenses)

    def inc_tech(self, tech_name):
        self._tech.add({tech_name:1})

    def sub_units(self, units):
        self._units.sub(units)

    def sub_defenses(self, defenses):
        self._defenses.sub(defenses)
示例#46
0
'''
nr_drones = int(words[2])
turns = int(words[3])
max_payload = int(words[4])
manager = Manager()
manager.changeDrones(int(words[2]))
manager.changeTurns(int(words[3]))
manager.changePayload(int(words[4]))

manager.changeNumberOfTypes(int(input()))

manager.changeWeigh(input().split())

for e in range(int(input())):
  #creates all warehouses
  w = Warehouse(input().split())
  w.addproducts(input().split())
  manager.addWarehouse(w)

nr_orders = int(input())

orders = []
for e in range(nr_orders):
  order = Order(len(orders), input().split())
  order.addproducts(int(input()), input().split())
  manager.addOrder(order)

manager.organizeWarehouses()

#for e in orders:
#  print(e.products())
示例#47
0
import utils
import math

[rows, columns, noOfDrones, deadline, maxLoad] = [int(num) for num in raw_input().split(" ")]
raw_input() # ignore number of products
utils.productWeights = [int(w) for w in raw_input().split(" ")]

warehouses = []
warehouseByPos = {}
for n in range(int(raw_input())):
    [x, y] = [int(num) for num in raw_input().split(" ")]
    productAmount = [int(w) for w in raw_input().split(" ")]
    products = []
    for i in range(len(productAmount)):
        products += ([i] * productAmount[i])
    w = Warehouse(n, x, y, products)
    warehouses.append(w)
    warehouseByPos[x + y * columns] = w

drones = []
for i in range(noOfDrones):
    drones.append(Drone(i, warehouses[0].x, warehouses[0].y, maxLoad))

orders = []
for c in range(int(raw_input())):
    [x, y] = [int(num) for num in raw_input().split(" ")]
    raw_input()
    products = [int(num) for num in raw_input().split(" ")]
    weight = 0
    for product in products:
        weight += utils.getProductWeight(product)
示例#48
0
 def setUp(self):
     self.warehouse = Warehouse()
     self.warehouse.add('Glenlivit', 10)