Example #1
0
    def test_generate_robot(self):
        grid = Grid(3, 3)

        grid.generate_robot(0, 0, 'N')

        assert len(grid.robots) > 0
        assert grid.robots[0].pos() == (0, 0, 'N')
Example #2
0
    def test_should_not_generate_robot_at_invalid_coordinate(self):
        grid = Grid(3, 3)

        with pytest.raises(CustomExceptions.CoordinateDoesntExistError) as exc:
            grid.generate_robot(4, 1, 'E')

        assert str(exc.value) == str((4, 1, 'E'))
Example #3
0
def grid_create(username: str):
    # if not request.json:
    #     return jsonify({"error": "Data not specified"}), 409
    # if not request.json.get("name"):
    #     return jsonify({"error": "Name not specified"}), 409
    # if not request.json.get("description"):
    #     return jsonify({"error": "Description not specified"}), 409
    # if not request.json.get("num_Days"):
    #     return jsonify({"error": "numDays not specified"}), 409

    schema = Schema({
        "name":
        And(str, len, error="Namr not specified"),
        "description":
        And(str, len, error="description not specified"),
        "num_Days":
        And(Use(int), error="Number of Days not specified"),
        "is_public":
        And(str, len, error="publicity not specified"),
    })
    form = {
        "name": request.form.get("name"),
        "description": request.form.get("description"),
        "num_Days": request.form.get("num_Days"),
        "is_public": request.form.get("is_public")
    }
    validated = schema.validate(form)

    #subvue_permalink = validated["grid"]
    #subvue = Subvue.objects(permalink__iexact=subvue_permalink).first()
    #if not subvue:
    #    return jsonify({"error": f"Subvue '{subvue_permalink}' not found"}), 404

    user = User.objects(username=username).first()

    grid = Grid(
        # user=user,
        # id = counter
        # name= validated["title"],
        # description="",
        # days = numDays,
        # repeat = [],
        # self.start_Date = [timer.strftime("%m"), timer.strftime("%d")], #A list with the month in mm format and day in the dd format
        # self.start_Day = int(timer.day()),
        # self.curr_Day = int(timer.day()),
        # endDate = []
        user=user,
        name=validated["name"],
        description=validated["description"],
        num_Days=validated["num_Days"],
        repeat=[],
        start_Date=datetime.now(),
        string_start=datetime.strftime(
            datetime.now(), "%B %m, %Y"
        ),  #A list with the month in mm format and day in the dd format
        curr_Date=datetime.now(),
        end_Date=datetime.now() + timedelta(days=int(validated["num_Days"])),
        is_public=validated["is_public"]).save()
    return jsonify(grid.to_public_json())
Example #4
0
	def test_in_bounds_method(self):
		board = Grid(5)
		self.assertTrue(board.in_bounds(0, 4))
		self.assertTrue(board.in_bounds(4, 4))
		self.assertTrue(board.in_bounds(2, 1))
		self.assertFalse(board.in_bounds(1, 5))
		self.assertFalse(board.in_bounds(3, -1))
		self.assertFalse(board.in_bounds(-2, 0))
Example #5
0
    def test_last_positions(self, robots, expected):
        grid = Grid(5, 5)
        for robot in robots:
            grid.generate_robot(*robot)

        final = grid.last_positions()

        assert len(final) == len(expected)
        assert final == expected
Example #6
0
	def test_change_cell_at_method(self):
		board = Grid(5)
		board.change_cell_at(0, 1)

		for cell in board:
			if cell.coords == (0, 1):
				self.assertEqual(cell.is_alive(), True)
			else:
				self.assertEqual(cell.is_alive(), False)
Example #7
0
def add_grid():
    data = request.get_json(force=True)
    form = NewGridForm(MultiDict(mapping=data))
    if form.validate():
        configuration = data.get('configuration')
        grid = Grid(configuration=configuration, date=datetime.utcnow())
        db.session.add(grid)
        db.session.commit()
        socketio.emit('new_grid', str(grid.to_json()))
        return jsonify({'success': 'true'}), 201
    return jsonify({"form_errors": form.errors}), 400
Example #8
0
 def __init__(self, master, row, col, fix, **kargs):
     super().__init__(master, **kargs)
     self.flag_flush = False
     self.params = (row, col, 900 // col, 500 // row, 50, 20)
     params = self.params
     self.g = Grid(params[0],
                   params[1],
                   params[2],
                   params[3],
                   params[4],
                   fix=fix)
     self.n_size = params[5]
     self.id = []
     self.drawing()
Example #9
0
def grid_index():
    pubs = []
    grids = Grid.objects().order_by("-start_Date")
    for grid in grids:
        if grid.is_public == "true":
            pubs.append(grid.to_public_json())

    return jsonify(pubs)
Example #10
0
def grids_user(username: str):
    try:
        user = User.objects(username=username).first()
    except ValidationError:
        return jsonify({"error": "User not found"}), 404

    grids = Grid.objects(user=user).order_by("-created")

    return jsonify([grid.to_public_json() for grid in grids])
Example #11
0
def grids_item(id: str):
    try:
        grid = Grid.objects(pk=id).first()

        # If grid has alreay been deleted
        if not grid:
            raise ValidationError
    except ValidationError:
        return jsonify({"error": "grid not found"}), 404

    return jsonify(grid.to_public_json())
Example #12
0
	def test_update_method(self):
		world = WorldBoard(5)
		board = world._board

		board.change_cell_at(0, 0)
		board.change_cell_at(1, 1)
		board.change_cell_at(1, 2)
		board.change_cell_at(0, 3)

		"""
		X..X.       .XX..
		.XX..       .XX..
		.....   =>  ..... 
		.....       .....
		.....       .....
		              """
		next_gen_board = Grid(5)
		next_gen_board.change_cell_at(0, 1)
		next_gen_board.change_cell_at(0, 2)
		next_gen_board.change_cell_at(1, 1)
		next_gen_board.change_cell_at(1, 2)

		board.next_generation()
		for cell in board:
			self.assertEqual(cell.is_alive(), 
				next_gen_board.get_cell_at(cell.x, cell.y).is_alive())
Example #13
0
    def test_should_not_generate_robot_at_same_coordinate(self):
        grid = Grid(3, 3)
        grid.generate_robot(1, 1, 'E')

        with pytest.raises(CustomExceptions.LaunchRobotCrashError) as exc:
            grid.generate_robot(1, 1, 'E')

        assert str(exc.value) == str((1, 1, 'E'))
Example #14
0
    def test_apply_robot_instructions(
        self,
        robot_position,
        instructions,
        final,
    ):
        grid = Grid(5, 5)
        grid.generate_robot(*robot_position)

        grid.apply_robot_instructions(instructions)

        assert grid.robots[0].pos() == final
Example #15
0
def main():
    """
    A program to find the solution to a sudoku.
    """
    g = Grid()
    get_grid_from_file(g, "puzzles/p1.txt")

    print("Input:")
    g.print_grid()

    discover_vals(g)
    print("---\nSolution:")
    g.print_grid()
Example #16
0
def grids_delete(username: str, id: str):
    try:
        grid = Grid.objects(pk=id).first()

        # If grid has alreay been deleted
        if not grid:
            raise ValidationError
    except ValidationError:
        return jsonify({"error": "Grid not found"}), 404

    # Check whether action was called by creator of the grid
    if username != grid.user.username:
        return jsonify({"error": "You are not the creator of the grid"}), 401

    grid_info = grid.to_public_json()

    grid.delete()

    return jsonify(grid_info)
Example #17
0
def main():
	print('*** Welcome to the Mars Robots Guide! ***\n')
	print('Here are the computed outputs:\n')

	with open('robots_guide.in.md') as f:
		lines = f.readlines()

	grid_size = lines[0]

	if not grid_size:
		return

	grid_size = grid_size.split(' ')

	max_x_axis = int(grid_size[0])
	max_y_axis = int(grid_size[1])

	if max_x_axis > 50 or max_y_axis > 50:
		raise CustomExceptions.InvalidGridRangeError(max_x_axis, max_y_axis)

	grid = Grid(
		x=max_x_axis,
		y=max_y_axis,
	)

	updated_lines = lines.pop(0) 		# upper-right coordinates of the rectangular world
	robots_seed_positions = lines[::2]	# Robots initial position
	robots_instructions = lines[1::2]	# Robots instructions

	for position, instruction in zip(robots_seed_positions, robots_instructions):
		robot_initial_pos = position.strip('\n')

		if not robot_initial_pos:
			break

		robot_instruction = instruction

		robot_initial_pos = robot_initial_pos.split(' ')
		grid.generate_robot(
			x=int(robot_initial_pos[0]),
			y=int(robot_initial_pos[1]),
			orientation=robot_initial_pos[2],
		)
		grid.apply_robot_instructions(robot_instruction)
	f.close()
Example #18
0
 def test_invalid_grid_coordinates_y(self):
     with pytest.raises(InvalidGridCoordinates):
         Grid(0, -1)
Example #19
0
 def test_grid_y_str_value_error(self):
     with pytest.raises(ValueError):
         Grid(2, 'foo')
Example #20
0
 def reset(self):
     params = self.params
     self.g = Grid(params[0], params[1], params[2], params[3], params[4])
     self.drawing()
     self.flag_flush = False
Example #21
0
	def test_next_generation(self):
		board = Grid(5)
		board.change_cell_at(0, 0)
		board.change_cell_at(1, 1)
		board.change_cell_at(1, 2)
		board.change_cell_at(0, 3)

		"""
		X..X.       .XX..
		.XX..       .XX..
		.....   =>  ..... 
		.....       .....
		.....       .....
		              """
		next_gen_board = Grid(5)
		next_gen_board.change_cell_at(0, 1)
		next_gen_board.change_cell_at(0, 2)
		next_gen_board.change_cell_at(1, 1)
		next_gen_board.change_cell_at(1, 2)

		board.next_generation()
		for cell in board:
			self.assertEqual(cell.is_alive(), 
				next_gen_board.get_cell_at(cell.x, cell.y).is_alive())
Example #22
0
 def position_1_1(self):
     grid = Grid(5, 5)
     return Position(1, 1, grid)
Example #23
0
 def position_5_5(self):
     grid = Grid(5, 5)
     return Position(5, 5, grid)
Example #24
0
import argparse

from models import Grid, Position, LawnMower
from utils import parse_file

parser = argparse.ArgumentParser(description='Lawn mowers processor.')
parser.add_argument('lm_data_file',
                    metavar='lm-data-file',
                    type=str,
                    help='Lawn mowers data file locations.')
args = parser.parse_args()

if __name__ == '__main__':
    parse_data = parse_file(args.lm_data_file)
    grid = Grid(*parse_data['grid'])
    lm_actions = []
    for lm in parse_data['lawn_mowers']:
        position = Position(*lm['position'], grid=grid)
        orientation = lm['orientation']
        lm_actions.append([LawnMower(position, orientation), lm['actions']])
    for lawn_mower, actions in lm_actions:
        lawn_mower.perform_actions(actions)
        print(lawn_mower.position.x, lawn_mower.position.y,
              lawn_mower.orientation)
Example #25
0
def initialize_grid(line):
    if ':' in line:
        line = line[line.index(':') + 1:]

    width, height = [int(i.strip()) for i in line.split()]
    return Grid(width, height)
Example #26
0
	def test_if_cell_should_change(self):
		board = Grid(5)
		for cell in board:
			self.assertFalse(board.should_change(cell))


		board.change_cell_at(0, 0)
		board.change_cell_at(0, 1)
		board.change_cell_at(0, 2)
		"""
		XXX..
		.....
		.....
		.....
		.....
		"""
		self.assertTrue(board.should_change(board.get_cell_at(0, 0)))
		self.assertFalse(board.should_change(board.get_cell_at(0, 1)))
		self.assertTrue(board.should_change(board.get_cell_at(0, 2)))
Example #27
0
    def test_is_outside_grid(self, robot_position, expected):
        grid = Grid(1, 1)

        value = grid.is_outside_grid(*robot_position)

        assert value == expected
Example #28
0
 def grid(self):
     return Grid(5, 5)
Example #29
0
 def test_grid_x_str_value_error(self):
     with pytest.raises(ValueError):
         Grid('foo', 2)
Example #30
0
def save_bd_record(pdf):
    """
    Данные, собранные о pdf, сохраняются в базу данных
    :param pdf:
    :return:
    """
    contractor_error = error_text(pdf.upload_to_ctpbureau_status, pdf.upload_to_ctpbureau_error)
    preview_error = error_text(pdf.upload_to_press_status, pdf.upload_to_press_error)
    if not pdf.upload_to_ctpbureau_status:
        bg = 'danger'
    elif not pdf.upload_to_press_status:
        bg = 'warning'
    else:
        bg = 'default'

    logger.info('')
    logger.info('――> Save into database:')

    try:
        row = Grid()
        row.order = pdf.order
        row.datetime = pdf.created
        row.pdfname = pdf.ordername
        row.machine = pdf.machines[1]
        row.total_pages = pdf.complects
        row.total_plates = pdf.plates
        row.contractor = pdf.ctpbureau
        row.contractor_error = contractor_error
        row.preview_error = preview_error
        row.colors = dict_to_multiline(pdf.colors)[:500]
        row.inks = inks_to_multiline(pdf.inks)[:500]
        row.bg = bg
        row.proof = pdf.jpeg_proof
        row.thumb = pdf.jpeg_thumb
        # logger.info('row.order', row.order)
        # logger.info('row.datetime', row.datetime)
        # logger.info('row.pdfname', row.pdfname)
        # logger.info('row.machine', row.machine)
        # logger.info('row.total_pages', row.total_pages)
        # logger.info('row.total_plates', row.total_plates)
        # logger.info('row.contractor', row.contractor)
        # logger.info('row.contractor_error', row.contractor_error)
        # logger.info('row.preview_error', row.preview_error)
        # logger.info('row.colors', row.colors)
        # logger.info('row.inks', row.inks)
        # logger.info('row.bg', row.bg)
        # logger.info('row.proof', row.proof)
        # logger.info('row.thumb', row.thumb)
        row.save()
        logger.info('····done')
    except Exception, e:
        logger.error('····FAILED: {}'.format(e))
Example #31
0
 def position_5_0(self):
     grid = Grid(5, 5)
     return Position(5, 0, grid)
Example #32
0
	def test_get_cell_at_method(self):
		board = Grid(3)
		self.assertEqual(board.get_cell_at(0, 0), board._grid[0][0])
Example #33
0
class My_Canvas(tk.Canvas):
    def __init__(self, master, row, col, fix, **kargs):
        super().__init__(master, **kargs)
        self.flag_flush = False
        self.params = (row, col, 900 // col, 500 // row, 50, 20)
        params = self.params
        self.g = Grid(params[0],
                      params[1],
                      params[2],
                      params[3],
                      params[4],
                      fix=fix)
        self.n_size = params[5]
        self.id = []
        self.drawing()

    def reset(self):
        params = self.params
        self.g = Grid(params[0], params[1], params[2], params[3], params[4])
        self.drawing()
        self.flag_flush = False

    def next_phase(self):
        print("Transit to a next state.")
        self.g.next_phase()
        self.drawing()

    def start_sim(self):
        if self.flag_flush == False:
            self.flag_flush = True
            print("Start!")
            self.after(0, self.simulation)

    def simulation(self):
        if self.flag_flush == True:
            self.g.next_phase()
            self.drawing()
            self.after(100, self.simulation)

    def stop_sim(self):
        if self.flag_flush == True:
            print("Stop!")
            self.flag_flush = False

    def drawing(self):
        self.delete("all")

        g = self.g
        n = g.n
        i_j = [(i, j) for i in range(n) for j in range(n)]

        for _ in range(len(self.id)):
            self.delete(self.id[0])
            del self.id[0]

        # weight of each edge
        self.id = [
            self.create_text((g.L[i][0] + g.L[j][0]) / 2,
                             g.L[i][1] - 20,
                             fill="white",
                             font="system 25 bold",
                             text="{0}".format(g.E[i][j])) for i, j in i_j
            if g.E[i][j] > 0 and i - j in {1, -1}
        ]
        self.id += [
            self.create_text(g.L[i][0] - 20, (g.L[i][1] + g.L[j][1]) / 2,
                             fill="white",
                             font="system 25 bold",
                             text="{0}".format(g.E[i][j])) for i, j in i_j
            if g.E[i][j] > 0 and i - j in {g.col, -g.col} and i < j
        ]
        try:
            # distance table
            cand = sorted([(i, d) for i, d in enumerate(g.dist)
                           if d != -1 and g.flug[i] == False],
                          key=lambda x: x[1])[0][0]
            # even id with false flug
            self.id += [
                self.create_text(900,
                                 30 + (i // 2) * 25,
                                 fill="#AAAAAA",
                                 font="system 20 bold",
                                 text="{0}".format(i + 1)) for i in range(n)
                if i % 2 == 0 and i != cand and g.flug[i] == False
            ]
            # even id with true flug
            self.id += [
                self.create_text(900,
                                 30 + (i // 2) * 25,
                                 fill="#0000FF",
                                 font="system 20 bold",
                                 text="{0}".format(i + 1)) for i in range(n)
                if i % 2 == 0 and i != cand and g.flug[i] == True
            ]
            # distance of even id with false flug
            self.id += [
                self.create_text(950,
                                 30 + (i // 2) * 25,
                                 fill="#AAAAAA",
                                 font="system 20 bold",
                                 text="{0}".format(d))
                for i, d in enumerate(g.dist)
                if i % 2 == 0 and d != -1 and g.flug[i] == False
            ]
            # distance of even id with true flug
            self.id += [
                self.create_text(950,
                                 30 + (i // 2) * 25,
                                 fill="#0000FF",
                                 font="system 20 bold",
                                 text="{0}".format(d))
                for i, d in enumerate(g.dist)
                if i % 2 == 0 and d != -1 and g.flug[i] == True
            ]
            # odd id with false flug
            self.id += [
                self.create_text(1000,
                                 30 + (i // 2) * 25,
                                 fill="#AAAAAA",
                                 font="system 20 bold",
                                 text="{0}".format(i + 1)) for i in range(n)
                if i % 2 == 1 and i != cand and g.flug[i] == False
            ]
            # odd id with true flug
            self.id += [
                self.create_text(1000,
                                 30 + (i // 2) * 25,
                                 fill="#0000FF",
                                 font="system 20 bold",
                                 text="{0}".format(i + 1)) for i in range(n)
                if i % 2 == 1 and i != cand and g.flug[i] == True
            ]
            # distance of even id with false flug
            self.id += [
                self.create_text(1050,
                                 30 + (i // 2) * 25,
                                 fill="#AAAAAA",
                                 font="system 20 bold",
                                 text="{0}".format(d))
                for i, d in enumerate(g.dist)
                if i % 2 == 1 and d != -1 and g.flug[i] == False
            ]
            # distance of even id with true flug
            self.id += [
                self.create_text(1050,
                                 30 + (i // 2) * 25,
                                 fill="#0000FF",
                                 font="system 20 bold",
                                 text="{0}".format(d))
                for i, d in enumerate(g.dist)
                if i % 2 == 1 and d != -1 and g.flug[i] == True
            ]
            # id of min distance
            self.id += [
                self.create_text(900 + (cand % 2) * 100,
                                 30 + (cand // 2) * 25,
                                 fill="#00FF00",
                                 font="system 20 bold",
                                 text="{0}".format(cand + 1))
            ]

            def create_bold_line(x1,
                                 y1,
                                 x2,
                                 y2,
                                 fill=None,
                                 boldness=1,
                                 hori=True):
                if hori == True:
                    for t in range(1 - boldness, boldness):
                        self.create_line(x1, y1 + t, x2, y2 + t, fill=fill)
                else:
                    for t in range(1 - boldness, boldness):
                        self.create_line(x1 + t, y1, x2 + t, y2, fill=fill)

            create_bold_line(875,
                             16,
                             875,
                             20 + ((n + 1) // 2) * 25,
                             fill="#AAAAAA",
                             boldness=2,
                             hori=False)
            create_bold_line(925,
                             16,
                             925,
                             20 + ((n + 1) // 2) * 25,
                             fill="#AAAAAA",
                             boldness=1,
                             hori=False)
            create_bold_line(975,
                             16,
                             975,
                             20 + ((n + 1) // 2) * 25,
                             fill="#AAAAAA",
                             boldness=2,
                             hori=False)
            create_bold_line(1025,
                             16,
                             1025,
                             20 + ((n + 1) // 2) * 25,
                             fill="#AAAAAA",
                             boldness=1,
                             hori=False)
            create_bold_line(1075,
                             16,
                             1075,
                             20 + ((n + 1) // 2) * 25,
                             fill="#AAAAAA",
                             boldness=2,
                             hori=False)
            for i in range((n + 1) // 2 + 1):
                create_bold_line(875,
                                 17 + i * 25,
                                 1075,
                                 17 + i * 25,
                                 fill="#AAAAAA",
                                 boldness=2,
                                 hori=True)
        except:
            pass

        #draw edges from i to j
        for i, j in i_j:
            if g.E[i][j] > 0:
                if g.flug_e[i][j] == 0:
                    self.create_line(g.L[i][0],
                                     g.L[i][1],
                                     g.L[j][0],
                                     g.L[j][1],
                                     fill="#AAAAAA")
                elif g.flug_e[i][j] == 1:
                    if i - j in {1, -1}:
                        for t in range(-4, 5):
                            self.create_line(g.L[i][0],
                                             g.L[i][1] + t,
                                             g.L[j][0],
                                             g.L[j][1],
                                             fill="#00AA00")
                    elif i - j in {g.col, -g.col}:
                        for t in range(-4, 5):
                            self.create_line(g.L[i][0] + t,
                                             g.L[i][1],
                                             g.L[j][0],
                                             g.L[j][1],
                                             fill="#00AA00")

        for i in range(n):
            # draw nodes
            if g.flug[i] == False:
                self.create_rectangle(
                    g.L[i][0] - self.n_size / 2,
                    g.L[i][1] - self.n_size / 2,
                    g.L[i][0] + self.n_size / 2,
                    g.L[i][1] + self.n_size / 2,
                    fill="#AAAAAA"
                )  # (x1, y1, x2, y2) x1 and y1 are upper-left, and x2 and y2 are lower-right
            else:
                self.create_rectangle(
                    g.L[i][0] - self.n_size / 2,
                    g.L[i][1] - self.n_size / 2,
                    g.L[i][0] + self.n_size / 2,
                    g.L[i][1] + self.n_size / 2,
                    fill="#00FF00"
                )  # (x1, y1, x2, y2) x1 and y1 are upper-left, and x2 and y2 are lower-right

        if all(g.flug) == True:
            print("#hops of shortest path: {}".format(len(g.path[n - 1])))
            for i in range(len(g.path[n - 1]) - 1):
                for t in range(-6, 7):
                    if g.path[n - 1][i] - g.path[n - 1][i + 1] in {-1, 1}:
                        self.create_line(g.L[g.path[n - 1][i]][0],
                                         g.L[g.path[n - 1][i]][1],
                                         g.L[g.path[n - 1][i + 1]][0],
                                         g.L[g.path[n - 1][i + 1]][1] + t,
                                         fill="#FF0000")
                    elif g.path[n - 1][i] - g.path[n - 1][i + 1] in {
                            -g.col, g.col
                    }:
                        self.create_line(g.L[g.path[n - 1][i]][0],
                                         g.L[g.path[n - 1][i]][1],
                                         g.L[g.path[n - 1][i + 1]][0] + t,
                                         g.L[g.path[n - 1][i + 1]][1],
                                         fill="#FF0000")
            for t in range(-6, 7):
                if n - 1 - g.path[n - 1][-1] in {-1, 1}:
                    self.create_line(g.L[g.path[n - 1][-1]][0],
                                     g.L[g.path[n - 1][-1]][1],
                                     g.L[n - 1][0],
                                     g.L[n - 1][1] + t,
                                     fill="#FF0000")
                elif n - 1 - g.path[n - 1][-1] in {-g.col, g.col}:
                    self.create_line(g.L[g.path[n - 1][-1]][0],
                                     g.L[g.path[n - 1][-1]][1],
                                     g.L[n - 1][0] + t,
                                     g.L[n - 1][1],
                                     fill="#FF0000")
Example #34
0
    def test_apply_robot_instructions_with_empty_grid(self):
        grid = Grid(5, 5)

        grid.apply_robot_instructions('')

        assert not grid.robots