Пример #1
0
 def flip_tiles(self, x, y, is_black):
     """Flip tile colors in all eight directions.
     INT, INT -> BOOLEAN"""
     d = Disk(x, y, self.cell)
     position = (d.row, d.column)
     self._flip_tiles_one_dir(self._move_right(position), self._move_right,
                              is_black)
     self._flip_tiles_one_dir(self._move_left(position), self._move_left,
                              is_black)
     self._flip_tiles_one_dir(self._move_up(position), self._move_up,
                              is_black)
     self._flip_tiles_one_dir(self._move_down(position), self._move_down,
                              is_black)
     self._flip_tiles_one_dir(self._move_left_up(position),
                              self._move_left_up, is_black)
     self._flip_tiles_one_dir(self._move_left_down(position),
                              self._move_left_down, is_black)
     self._flip_tiles_one_dir(self._move_right_up(position),
                              self._move_right_up, is_black)
     self._flip_tiles_one_dir(self._move_right_down(position),
                              self._move_right_down, is_black)
     d.draw_black = is_black
     d.display()
     self.table[d.row][d.column] = d
     self.total_count += 1
     self.check_legal(self.gr.player_turn)
Пример #2
0
 def __init__(self, WIDTH, HEIGHT, CELL, gr):
     self.WIDTH = WIDTH
     self.HEIGHT = HEIGHT
     self.cell = CELL
     num_start_disks = 2
     self.black_score = num_start_disks
     self.white_score = num_start_disks
     self.total_count = num_start_disks * 2
     self.gr = gr
     self.total_col = self.WIDTH // self.cell
     self.total_row = self.HEIGHT // self.cell
     self.table = [[0] * self.total_col for i in range(self.total_row)]
     half_cell = self.cell / 2
     self.disk1 = (Disk(self.WIDTH // 2 + half_cell,
                        self.HEIGHT // 2 - half_cell, self.cell))
     self.disk2 = (Disk(self.WIDTH // 2 - half_cell,
                        self.HEIGHT // 2 + half_cell, self.cell))
     self.disk3 = (Disk(self.WIDTH // 2 - half_cell,
                        self.HEIGHT // 2 - half_cell, self.cell))
     self.disk4 = (Disk(self.WIDTH // 2 + half_cell,
                        self.HEIGHT // 2 + half_cell, self.cell))
     self.table[self.disk1.row][self.disk1.column] = self.disk1
     self.table[self.disk2.row][self.disk2.column] = self.disk2
     self.table[self.disk3.row][self.disk3.column] = self.disk3
     self.table[self.disk4.row][self.disk4.column] = self.disk4
     self.disk3.draw_black = False
     self.disk4.draw_black = False
     self.legal_table = set()
Пример #3
0
    def run(self):
        if self.listProcess == []:
            reply = QMessageBox.information(self, 'SEM PROCESSOS',
                                            "Insira processos para rodar",
                                            QMessageBox.Ok)
            return
        self.file_open(True)

        self.quantum = self.quantum_sp.value()
        self.override = self.override_sp.value()
        self.type = self.comboCPU.currentText()
        self.typeMMU = self.comboMem.currentText()
        escalonator = Escalonator(self.type.upper(), self.override)
        self.processes = self.listProcess
        disk = Disk()
        vm = VirtualMemory(100, disk)
        mmu = MMU(vm, self.typeMMU.upper(), disk)
        io = IO(mmu, disk)
        io.escalonator = escalonator
        cpu = CPU(escalonator, mmu, io, self.quantum, disk=disk)
        escalonator.cpu = cpu
        n = len(self.processes)
        for i in self.processes:
            i.io = io
            escalonator.insertProcess(i)
            disk.insertProcess(i.id, i.numpages)

        escalonator.not_arrived.sort(key=lambda x: x.start)
        escalonator.queue()
        self.hide()
        self.gantt = Window_Gantt(n, cpu, escalonator, io, self.processes,
                                  self)
Пример #4
0
def test_check_win_horizontal():
    # initiate disk objects
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")

    # test horizontal by placing the disks
    cw.matrix[3][5] = dk1
    cw.matrix[4][5] = dk2
    cw.matrix[5][5] = dk3
    cw.matrix[6][5] = dk4

    # get result
    re = cw.check_win()
    assert len(cw.matrix) == 7 and \
        len(cw.matrix[5]) == 6 and \
        len(cw.matrix[6]) == 6 and \
        cw.matrix[3][5] != 0 and \
        matrix[4][5] != 0 and \
        matrix[5][5] != 0 and \
        matrix[6][5] != 0 and \
        matrix[3][5].color == "test" and \
        matrix[4][5].color == "test" and \
        matrix[5][5].color == "test" and \
        matrix[6][5].color == "test" and \
        re == "test"
def test_check_all_positions():
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    # Tests case where board is filled by all black
    # manually insert a white disk at point table[0][0]
    # game ends and method returns expected tuple
    for y in range(len(bd.table)):
        for x in range(len(bd.table)):
            bd.table[y][x] = Disk(y, x, 0)
    bd.table[0][0] = Disk(0, 0, 255)
    assert bd.check_all_positions() == (15, 1)

    # Tests case where board is not filled but
    # there are no more possible valid moves for
    # both sides and game ends. Test returns expected tuple
    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[1][1] = 0
    bd1.table[1][2] = 0
    bd1.table[2][1] = 0
    bd1.table[2][2] = 0
    bd1.table[0][0] = Disk(0, 0, 0)
    bd1.table[0][1] = Disk(0, 1, 255)
    bd1.makevalidmove(250, 0)
    assert bd1.check_all_positions() == (3, 0)
Пример #6
0
 def release_AI(self):
     '''release disk in the AI side'''
     # create AI side disk object
     self.disk_ball = Disk("Y")
     # randomly generate the column for dropping AI side disk
     # check if the column can drop AI side disk
     can_drop = True
     while can_drop:
         # column minus one as it's a closed range
         col = random.randint(0, (COLUMN - ONE))
         if not self.is_row_full(col):
             drop_height_index = self.matrix_update(col)
             # total disks in the matrix add 1
             self.total_disk += 1
             # end the while when can drop
             can_drop = False
         else:
             continue
     # pass x and y coordinates for AI side disk
     draw_x = col * ONE_HUDR + HALF_HUDR
     draw_y = HALF_HUDR
     self.disk_ball.draw_me(draw_x, draw_y)
     # calculate the targeted dropped height
     drop_height = MAX_DROP_HEIGHT - drop_height_index * ONE_HUDR
     # drop the disk
     self.disk_ball.down(drop_height)
     # trigger human side
     print("It's your turn:")
     self.countdown = COUNTDOWN
     self.ai_side = False
Пример #7
0
def test_save_name_in_file():
    """Test save_name_in_file method"""
    # Lisa play the game and get her score, store her score in the file
    gc = GameController(800, 100)
    gc.save_name_in_file("Lisa", "test_save_name.txt")

    # Lee play the game and get his score, store his score in the file, it
    # shoule be on the top, because his score is higher than lisa's score
    for i in range(len(gc.grid)):
        for j in range(len(gc.grid)):
            gc.grid[i][j] = Disk(i, j, 0)
    gc.save_name_in_file("Lee", "test_save_name.txt")

    # Chris play the game and get his score, store his score in the file, it
    # shoule be on the bottom, because his score is lower than lee's score
    gc = GameController(800, 100)
    for i in range(len(gc.grid)):
        for j in range(len(gc.grid)):
            if i == 0:
                gc.grid[i][j] = Disk(i, j, 0)
    gc.save_name_in_file("Chris", "test_save_name.txt")

    # Check the first person and the last person in the file
    with open("test_save_name.txt") as file:
        assert file.readline().strip() == "Lee 64"
        assert file.readlines()[-1].strip() == "Chris 10"
Пример #8
0
def test_check_win_increasing_diaganol():
    # initiate the disk objects
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")
    # test increasing diaganol by placing the disks
    cw.matrix[2][2] = dk1
    cw.matrix[5][5] = dk2
    cw.matrix[4][4] = dk3
    cw.matrix[3][3] = dk4
    # get result
    re = cw.check_win()
    assert len(cw.matrix) == 7 and \
        len(cw.matrix[5]) == 6 and \
        len(cw.matrix[6]) == 6 and \
        cw.matrix[2][2] != 0 and \
        matrix[5][5] != 0 and \
        matrix[4][4] != 0 and \
        matrix[3][3] != 0 and \
        matrix[2][2].color == "test" and \
        matrix[5][5].color == "test" and \
        matrix[4][4].color == "test" and \
        matrix[3][3].color == "test" and \
        re == "test"
Пример #9
0
    def read_file(self):
        """Populate the simulation attrubutes"""
        with open(self.filename, encoding='utf-8') as file:
            json_file = json.load(file)

        cache_dict = json_file["Cache"]
        cache_params = get_param_list(cache_dict, CACHE_PARAMS)
        self.cache = Cache(*cache_params)

        tlb_dict = json_file["TLB"]
        tlb_params = get_param_list(tlb_dict, TLB_PARAMS)
        self.tlb = TLB(*tlb_params)

        memory_dict = json_file["MemoriaFisica"]
        memory_params = get_param_list(memory_dict, MEM_PARAMS)
        self.memory = Memory(*memory_params)

        disk_write = self.memory.write_speed * 10
        disk_read = self.memory.read_speed * 10
        self.disk = Disk(disk_write, disk_read)

        self.page_table_size = self.memory.frames * 2
        self.virtual_size = self.memory.size * 2
        self.bits_address = int(log(self.virtual_size, 2))
        self.bits_page = int(log(self.page_table_size, 2))

        programs = json_file["Programas"]
        for program_dic in programs:
            program_parameters = get_param_list(program_dic,
                                                ["Nombre", "Secuencia"])
            new_program = Program(*program_parameters, self.page_table_size)
            self.programs.append(new_program)
            self.program_map[new_program.id] = new_program
            self.stats[new_program.id] = ProgramStats()
Пример #10
0
def test_last_resort():
    ai = othelloAI()
    d = Disk(-1000, '345')
    d2 = Disk(1, 1)
    ai.coordinate_extractor(d)
    ai.coordinate_extractor(d2)
    ai.fill_fin_avoid()
    assert ai.last_resort() == [(-1000, '345')]
Пример #11
0
def test_clear_bad_moves():
    ai = othelloAI()
    d = Disk(-1000, '345')
    d2 = Disk(1, 1)
    ai.coordinate_extractor(d)
    ai.coordinate_extractor(d2)
    ai.fill_fin_avoid()
    assert ai.clear_bad_moves() == [(-1000, '345')]
Пример #12
0
	def __init__(self, node: remote.RemoteNode, sourceDir: Path, cacheDir: Path, maxCacheSizeMB=_DEFAULT_CACHE_SIZE,
				 noatime=True):
		super().__init__()
		sourceDir, cacheDir = Path(sourceDir), Path(cacheDir)
		self.disk = Disk(sourceDir, cacheDir, maxCacheSizeMB, noatime)
		self.vfs = VFS(sourceDir, cacheDir)
		self.remote = node

		self.embed_active = False
Пример #13
0
 def computer_to_drop(self):
     aiX = score.ai_play(self.chessboard)
     row, column = self.chessboard.get_row_column(aiX)
     x, y = self.chessboard.row_column_to_xy(row, column)
     ai_disk = Disk(x, 0, x, y, row, column, self.count)
     ai_disk.intact = False
     self.count += 1
     self.disks.append(ai_disk)
     self.chessboard.occupy(row, column, 2)
Пример #14
0
def test_constructor():
    """Test constructor"""
    d = Disk(100, 150, 50)
    assert d.x == 100
    assert d.y == 150
    assert d.CELL == 50
    d.draw_black = False
    assert d.draw_black is False
    assert d.column == 2
    assert d.row == 3
Пример #15
0
    def prepare_to_drop(self, cur_x, cur_y):
        """draw a disk at the column corresponding to x,y coordinate"""
        # get column index to drop a disk:
        col_idx = int(math.floor(cur_x / self.diam))

        # if it is player's turn and valid, display a disk at desired location
        if self.isRed and self.valid_to_drop(cur_y, col_idx):
            new_disk = Disk(self.SPACE, self.TOTAL_ROW, col_idx,
                            self.disks_per_col[col_idx], self.isRed, self.diam)
            new_disk.draw_me()
Пример #16
0
 def init_disk(self):
     """Put the initial four disk"""
     self.put(self.SIZE/2-1, self.SIZE/2-1,
              Disk(self.SIZE/2-1, self.SIZE/2-1, 255, self, self.DISKSIZE))
     self.put(self.SIZE/2-1, self.SIZE/2,
              Disk(self.SIZE/2-1, self.SIZE/2, 0, self, self.DISKSIZE))
     self.put(self.SIZE/2, self.SIZE/2-1,
              Disk(self.SIZE/2, self.SIZE/2-1, 0, self, self.DISKSIZE))
     self.put(self.SIZE/2, self.SIZE/2,
              Disk(self.SIZE/2, self.SIZE/2, 255, self, self.DISKSIZE))
def test_makevalidmove():
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    # Actual coordinates on grid
    # If we try to place a disk object in the table
    # index that already has a disk object, will end function
    # and return None
    assert bd.makevalidmove(100, 100) == None
    # If we try to click on a spot that does not have an object
    # but is not valid, will return empty list, because no tiles
    # were flipped
    assert bd.makevalidmove(50, 50) == []

    # If we successfully add a disk in a spot, color flag
    # will change and it will be the other color's turn, in this
    # case, True flag (Black) switches to False (White)
    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[0][0] = Disk(0, 0, 255)
    bd1.table[0][1] = Disk(0, 1, 255)
    bd1.table[0][2] = Disk(0, 2, 255)
    bd1.table[1][0] = Disk(1, 0, 255)
    bd1.table[1][1] = Disk(1, 1, 255)
    bd1.table[1][2] = Disk(1, 2, 0)
    bd1.table[2][0] = Disk(2, 0, 255)
    bd1.table[2][1] = Disk(2, 1, 0)
    bd1.table[2][2] = Disk(2, 2, 0)
    assert bd1.color_flag
    bd1.makevalidmove(350, 350)
    assert not bd1.color_flag
Пример #18
0
 def initial_disk(self):
     """Initialize the first four disks"""
     middle = self.dimension // 200
     DIFF = 1
     self.grid[middle - DIFF][middle - DIFF] \
         = Disk(middle - DIFF, middle - DIFF, self.white_color)
     self.grid[middle - DIFF][middle] \
         = Disk(middle - DIFF, middle, self.black_color)
     self.grid[middle][middle - DIFF] \
         = Disk(middle, middle - DIFF, self.black_color)
     self.grid[middle][middle] = Disk(middle, middle, self.white_color)
Пример #19
0
    def add_disk(self, table_index_y, table_index_x):
        """Method to add a black or white disk to the board, checks if
        position that we want to add in already has a disk"""

        # If element in the linked list is already an object, end function
        if self.table[table_index_y][table_index_x]:
            return

        # Determines what color to put down based on flag.
        # Always starts with black, which is when color_flag is True
        if self.color_flag:
            self.table[table_index_y][table_index_x] = \
                Disk(table_index_y, table_index_x, 0)
            # Self Display method mentioned in pytest comments
            # For pytest to work, comment out self.display()
            # Functions will still work as normal, just without delay
            self.display()
            self.color_flag = False  # After put down disk, make flag False

        # If color_flag is False, means white disk is going to be put down
        elif not self.color_flag:
            self.table[table_index_y][table_index_x] = \
                Disk(table_index_y, table_index_x, 255)
            self.color_flag = True  # After put down disk, make flag True

        # The method isvalid() is called with this method - isvalid()
        # isvalid() checks all the valid moves at that turn for a specific
        # color and returns a set of tuples, which are (row, column) indexes
        # for that color

        self.isvalid()

        # If the first isvalid() check returns an empty set, which
        # is False, we change the color_flag to the opposite color and
        # print the statements accordingly.
        if not self.isvalid():
            if self.color_flag:
                self.color_flag = False
                print("No more moves for player. Computer's turn")

            elif not self.color_flag:
                self.color_flag = True
                print("No more moves for computer. Player's turn")

        # We check one more time after the color_flag has changed
        self.isvalid()

        # If the set is empty once again, it will empty this if statement
        if not self.isvalid():
            self.no_more_valid_moves = True
            print("No more valid moves. Game Over")
Пример #20
0
def test_halo_run():
    d = Disk(10, 10)
    d.node_dict[0] = Disk(122, 33)
    d.color, d.node_dict[0].display_on = True, True
    d.node_dict[0].node_dict[0] = Disk(85, 64)
    d.halo_run(0, True)
    assert d.node_dict[0].node_dict[0].halo_tag is True
Пример #21
0
def test_run():
    d = Disk(10, 10)
    d.node_dict[0] = Disk(122, 33)
    d.color, d.node_dict[0].display_on = True, True
    d.node_dict[0].node_dict[0] = Disk(85, 64)
    d.run(0, True)
    assert d.node_dict[0].color is False
def test_isvalid():
    # Test to make sure isvalid() method functions
    # properly - returns the expected set with the valid
    # moves for the color at that turn
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    assert bd.isvalid() == {(0, 1), (1, 0), (2, 3), (3, 2)}

    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[0][1] = Disk(0, 1, 0)
    bd1.table[1][1] = Disk(1, 1, 0)
    bd1.color_flag = False
    assert bd1.isvalid() == {(0, 0), (2, 0), (0, 2)}
Пример #23
0
def test_get_board():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]]
    assert gc.get_board() == board

    col_idx = 0
    disk = Disk(gc.SPACE, gc.TOTAL_ROW, col_idx, gc.disks_per_col[col_idx],
                gc.isRed, gc.diam)
    disk.isRed = 1 - disk.isRed
    gc.board[5][3] = disk
    board[5][3] = 0
    assert gc.get_board() == board
Пример #24
0
    def __create_instances(self, dep_id, common_section, config_sections):
        emailid = common_section.emailid
        instance_user_name = common_section.instance_user_name
        # Launch instances
        for section in config_sections:
            section_name = section.section_name
            count = int(section.count)
            tag = section.tag
            machinetype = section.machinetype
            disk1image = section.disk1image
            disk2image = section.disk2image
            disk1type = section.disk1type
            disk2type = section.disk2type
            disk1size = section.disk1size
            disk2size = section.disk2size

            for num in range(count):
                instance_name = emailid + "-" + dep_id + "-" + section_name + "-" + tag + "-" + str(
                    num)
                disk1 = Disk(instance_name + "-d1", disk1image, disk1size,
                             disk1type)
                disk2 = Disk(instance_name + "-d2", disk2image, disk2size,
                             disk2type)
                disk1.create()
                disk2.create()

                disk_list = [disk1, disk2]
                instance = Instance(instance_name, disk_list, machinetype,
                                    instance_user_name)
                instance.create(common_section)
                if section_name == "master":
                    self.master_instances.append(instance)
                else:
                    self.slave_instances.append(instance)
                self.instances.append(instance)
def init_disk_stack(current_state, screen, setting):
    """初始化柱子栈,默认在第一个柱子"""
    while len(current_state.pillars_stack['one']) < setting.disk_number:
        # gap为盘子宽度差
        gap = len(current_state.pillars_stack['one']) * setting.disk_width_gap
        disk = Disk(screen, setting, gap)
        disk.init_pos('one', current_state)
        # 圆盘的底部等于柱子的顶部
        disk.rect.bottom = current_state.pillars_top['one']
        # 更新状态类的第一个柱子最顶端的像素
        current_state.pillars_top['one'] -= setting.disk_height
        # 给盘子编号
        disk.order_number = setting.disk_number - len(current_state.pillars_stack['one'])
        current_state.pillars_stack['one'].append(disk)
Пример #26
0
def test_update():
    # call check function
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")
    # test horizontal
    cw.matrix[3][5] = dk1
    cw.matrix[4][5] = dk2
    cw.matrix[5][5] = dk3
    cw.matrix[6][5] = dk4
    # check the returned result
    result = cw.check_win()
    assert result == "test"
Пример #27
0
def generate_disks(n, rand_cv, static_cv, even_cv):
    ''' Populate disk list '''
    disks = []
    for i in range(n):
        if rand_cv:
            # Generate random cv and ensure it is even
            disks.append(Disk(random.randint(1, rand_cv), 0))
        elif static_cv:
            disks.append(Disk(static_cv, 0))
        elif even_cv:
            disks.append(Disk(random.randint(1, floor(even_cv / 2)) * 2, 0))
        else:
            disks.append(Disk(1, 0))

    return disks
Пример #28
0
	def restore_file(self, handle, target_file, source_path, restore_cover=False, restore_time=9999999999):
		Disk.mkdir(source_path)
		target_list = handle.show(target_file)[1]
		#备份目录无文件则不恢复
		source_name = os.path.split(target_file)[1]
		for file_name in target_list:
			clock, md5, size = os.path.split(file_name)[1].split('#')
			if restore_time >= time.mktime(time.strptime(clock, '%Y-%m-%d@%H-%M-%S')):
				break
		else: return
		if os.path.exists('%s/%s' % (source_path, source_name)):
			if not restore_cover:
				return
		#print (file_name, source_name), source_path

		handle.download((file_name, source_name), source_path)
Пример #29
0
def init_disks(DISK_num, Latency_range):
    disk_id = 0
    disks = list()
    _min = Latency_range.get("min")
    _max = Latency_range.get("max")
    print("  min = " + str(_min) + ", max = " + str(_max))
    aver = (_min + _max) / 2
    sigma = (aver - _min) / 2  # 95% 的面积

    xli = list()
    yli = list()
    while disk_id < DISK_num:
        latency = int(round(random.gauss(aver, sigma)))
        if latency > 0 and latency < DISK_num:
            xli.append(disk_id)
            yli.append(latency)
            disk = Disk(disk_id, latency)
            disks.append(disk)
            disk_id = disk_id + 1

    # plt.figure()
    # plt.xticks(fontsize=14)
    # plt.yticks(fontsize=14)
    # plt.xlabel("disk", fontsize=14)
    # plt.ylabel("latency", fontsize=14)
    # plt.step(xli, yli, label="DISK-LATANCY", where="post")
    # plt.show()
    # print(len(disks))
    return disks
Пример #30
0
def construct_disk_list(file_name):
    disk_list = []
    with open(file_name, 'r') as file:
        for line in file:
            values = line.split()
            disk_list.append(Disk(values[0], values[1], values[2]))
    return disk_list
Пример #31
0
def test_constructor():
    d = Disk(0, 0, 0, 200, 20)
    assert d.row == 0
    assert d.col == 0
    assert d.color == 0
    assert d.CELL_WIDTH == 200
    assert d.EDGE == 20
Пример #32
0
    def __create_instances(self, dep_id, common_section, config_sections):
        emailid = common_section.emailid
        instance_user_name = common_section.instance_user_name
        # Launch instances
        for section in config_sections:
            section_name = section.section_name
            count = int(section.count)
            tag = section.tag
            machinetype = section.machinetype
            disk1image = section.disk1image
            disk2image = section.disk2image
            disk1type = section.disk1type
            disk2type = section.disk2type
            disk1size = section.disk1size
            disk2size = section.disk2size

            for num in range(count):
                instance_name = emailid + "-" + dep_id + "-" + section_name + "-" + tag + "-" + str(num)
                disk1 = Disk(instance_name + "-d1", disk1image, disk1size, disk1type)
                disk2 = Disk(instance_name + "-d2", disk2image, disk2size, disk2type)
                disk1.create()
                disk2.create()

                disk_list = [disk1, disk2]
                instance = Instance(instance_name, disk_list, machinetype, instance_user_name)
                instance.create(common_section)
                if section_name == "master":
                    self.master_instances.append(instance)
                else:
                    self.slave_instances.append(instance)
                self.instances.append(instance)
Пример #33
0
	def backup_dir(self, handle, source_path, target_path):
		#遍历目录
		for source_list in Disk.walk(source_path):
			#遍历目录下文件
			for source_file in source_list[2]:
				#跳过忽略的文件
				source_child = source_list[0][len(source_path) + 1:] #子目录
				if source_child:
					source_name = '%s/%s' % (source_child, source_file)
				else:
					source_name = source_file
				if search(self.config.get('backup', source_path, 'ignore'), source_name):
					continue
				self.backup_file(handle, source_file, '%s/%s' % (target_path, source_child))
Пример #34
0
def run_loop(my, filename):
    disk = Disk(SECTOR_SIZE, filename)
    total = int((disk.size() + SECTOR_SIZE - 1) / SECTOR_SIZE)
    mycallback = DiskCallback(disk)
    if total == 0:
        total = g_disksize

    view = HexScrollView(my.view, total, mycallback)
    controller = my.controller

    input_mode = False
    goto = ""
    while True:
        key = controller.getch()
        if key == ord('g'):
            input_mode = True
            my.view.add_string(1, 85, "goto: ")
        elif key >= ord('0') and key <= ord('9') and input_mode:
            goto += chr(key)
            my.view.add_string(1, 85, "goto: " + goto)
        elif (key == curses.KEY_ENTER or key == 10) and input_mode:
            input_mode = False
            igoto = int(goto)
            goto = ""
            view.init(igoto)
            view.update(0)
        elif key == 27:
            break
        elif key == curses.KEY_UP:
            view.update(-1)
        elif key == curses.KEY_DOWN:
            view.update(1)
        elif key == 127 and input_mode:
            if len(goto) > 0:
                view.update(0)
                goto = goto[0:-1]
                my.view.add_string(1, 85, "goto: " + goto)
Пример #35
0
pygame.display.set_caption("Circle Test")

white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)

paused = True
throwing = False
throwing_start = None
throwing_disk = None
dragging_disk = None
dragging_offset = None
panning = False
panning_start = None
d1 = Disk(Point(20, 20), 2, 1, Vector(0, 0))
d1.visuals.color = white
d1.visuals.trail = Trail(1, 100)
d2 = Disk(Point(10, 10), 5, 5.97219e+14, Vector(0, 0))
d2.visuals.color = white

world = World()
world.disks = [d1, d2]
camera = Camera(bottomleft=Point(0, 0), topright=Point(39, 29))
renderer = Renderer(world, camera, window_surface)

timestep = 33
dt = 0

while True:
    window_surface.fill(blue)
Пример #36
0
""" Reinsertion script for 46 Okunen Monogatari: The Shinka Ron."""

from utils import SRC_ROM_PATH, DEST_ROM_PATH
from cheats import change_starting_map

from disk import Disk, EXEFile, DATFile

#FILES_TO_TRANSLATE = ['ST2.EXE', 'ST3.EXE', 'ST4.EXE']

FILES_TO_TRANSLATE = [ 'ST1.EXE', 'ST2.EXE', 'ST3.EXE', 'ST4.EXE', 'ST5.EXE', 'ST5S1.EXE',
                      'ST5S2.EXE', 'ST5S3.EXE', 'ST6.EXE', 'OPENING.EXE', 'SINKA.DAT',
                      'OPENING.EXE', 'ENDING.EXE', '46.EXE', 'SEND.DAT', 'GEAGRDRV.EXE']


if __name__ == '__main__':
    DiskA = Disk(SRC_ROM_PATH, DEST_ROM_PATH, FILES_TO_TRANSLATE)
    DiskA.translate()
    #DiskA.typeset(FILES_TO_TYPESET)

    #change_starting_map('ST1.EXE', 101)
    #change_starting_map('ST5.EXE', 600)
Пример #37
0
 def add_disk(self, source_file, device):
     if device == "cdrom":
         self.disks.append(Disk.cdrom_init(source_file))
     elif device == "disk":
         self.disks.append(Disk.disk_init(source_file))
Пример #38
0
class TestDisk(unittest.TestCase):
    def setUp(self):
        self.disk1 = Disk(Point(100, 100), 20, 1, WHITE)
        self.disk2 = Disk(Point(130, 140), 30, 1, WHITE)
        self.disk3 = Disk(Point(120, 130), 30, 1, WHITE)
        self.disk4 = Disk(Point(150, 150), 30, 1, WHITE)

    def test_invalid_center(self):
        with self.assertRaises(TypeError):
            d = Disk((10, 10), 20, 1, WHITE)

    def test_invalid_velocity(self):
        with self.assertRaises(TypeError):
            d = Disk(Point(10, 10), 20, 1, WHITE, (1, 1))

    def test_contact_with_touching_disk(self):
        self.assertTrue(self.disk1.isInContact(self.disk2))

    def test_contact_with_overlapping_disk(self):
        self.assertTrue(self.disk1.isInContact(self.disk3))

    def test_contact_with_non_touching_disk(self):
        self.assertFalse(self.disk1.isInContact(self.disk4))

    def test_collision_with_touching_object_moving_against(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk2.velocity = Vector(-1, -1)
        self.assertTrue(self.disk1.isInCollision(self.disk2))

    def test_collision_with_touching_object_at_rest(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk2.velocity = Vector(0, 0)
        self.assertTrue(self.disk1.isInCollision(self.disk2))

    def test_collision_with_touching_object_moving_alongside(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk2.velocity = Vector(1, 1)
        self.assertFalse(self.disk1.isInCollision(self.disk2))

    def test_collision_with_overlapping_object_moving_against(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk3.velocity = Vector(-1, -1)
        self.assertTrue(self.disk1.isInCollision(self.disk3))

    def test_collision_with_overlapping_object_at_rest(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk3.velocity = Vector(0, 0)
        self.assertTrue(self.disk1.isInCollision(self.disk3))

    def test_collision_with_overlapping_object_moving_alongside(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk3.velocity = Vector(1, 1)
        self.assertFalse(self.disk1.isInCollision(self.disk3))

    def test_collision_with_non_touching_object_moving_against(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk4.velocity = Vector(-1, -1)
        self.assertFalse(self.disk1.isInCollision(self.disk4))

    def test_collision_with_non_touching_object_at_rest(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk4.velocity = Vector(0, 0)
        self.assertFalse(self.disk1.isInCollision(self.disk4))

    def test_collision_with_non_touching_object_moving_alongside(self):
        self.disk1.velocity = Vector(1, 1)
        self.disk4.velocity = Vector(1, 1)
        self.assertFalse(self.disk1.isInCollision(self.disk4))

    def test_surface(self):
        self.assertAlmostEqual(
            self.disk1.surface,
            pi * self.disk1.radius ** 2)

    def test_total_force(self):
        pass

    def test_update_velocity(self):
        pass

    def test_update_position(self):
        self.disk1.velocity = Vector(2, 3)

        dt = 0.1
        pos = self.disk1.center
        destination = pos[0] + 2 * dt, pos[1] + 3 * dt
        self.disk1.updatePosition(dt)
        self.assertAlmostEqual(destination[0], self.disk1.center[0])
        self.assertAlmostEqual(destination[1], self.disk1.center[1])
Пример #39
0
class DiskBuilder(object):
    """
        Disk image builder
    """
    def __init__(self, xml_state, target_dir, root_dir):
        self.root_dir = root_dir
        self.target_dir = target_dir
        self.xml_state = xml_state
        self.custom_filesystem_args = None
        self.build_type_name = xml_state.get_build_type_name()
        self.image_format = xml_state.build_type.get_format()
        self.install_iso = xml_state.build_type.get_installiso()
        self.install_stick = xml_state.build_type.get_installstick()
        self.install_pxe = xml_state.build_type.get_installpxe()
        self.blocksize = xml_state.build_type.get_target_blocksize()
        self.volume_manager_name = xml_state.get_volume_management()
        self.volumes = xml_state.get_volumes()
        self.volume_group_name = xml_state.get_volume_group_name()
        self.mdraid = xml_state.build_type.get_mdraid()
        self.luks = xml_state.build_type.get_luks()
        self.luks_os = xml_state.build_type.get_luksOS()
        self.machine = xml_state.get_build_type_machine_section()
        self.requested_filesystem = xml_state.build_type.get_filesystem()
        self.requested_boot_filesystem = \
            xml_state.build_type.get_bootfilesystem()
        self.bootloader = xml_state.build_type.get_bootloader()
        self.disk_setup = DiskSetup(
            xml_state, root_dir
        )
        self.boot_image_task = BootImageTask(
            'kiwi', xml_state, target_dir
        )
        self.firmware = FirmWare(
            xml_state
        )
        self.system_setup = SystemSetup(
            xml_state=xml_state, description_dir=None, root_dir=self.root_dir
        )
        self.diskname = ''.join(
            [
                target_dir, '/',
                xml_state.xml_data.get_name(),
                '.' + platform.machine(),
                '-' + xml_state.get_image_version(),
                '.raw'
            ]
        )
        self.install_media = self.__install_image_requested()
        self.install_image = InstallImageBuilder(
            xml_state, target_dir, self.boot_image_task
        )
        # an instance of a class with the sync_data capability
        # representing the entire image system except for the boot/ area
        # which could live on another part of the disk
        self.system = None

        # an instance of a class with the sync_data capability
        # representing the boot/ area of the disk if not part of
        # self.system
        self.system_boot = None

        # an instance of a class with the sync_data capability
        # representing the boot/efi area of the disk
        self.system_efi = None

        # result store
        self.result = Result()

    def create(self):
        if self.install_media and self.build_type_name != 'oem':
            raise KiwiInstallMediaError(
                'Install media requires oem type setup, got %s' %
                self.build_type_name
            )

        # setup recovery archive, cleanup and create archive if requested
        self.system_setup.create_recovery_archive()

        # prepare boot(initrd) root system
        log.info('Preparing boot system')
        self.boot_image_task.prepare()

        # precalculate needed disk size
        disksize_mbytes = self.disk_setup.get_disksize_mbytes()

        # create the disk
        log.info('Creating raw disk image %s', self.diskname)
        loop_provider = LoopDevice(
            self.diskname, disksize_mbytes, self.blocksize
        )
        loop_provider.create()

        self.disk = Disk(
            self.firmware.get_partition_table_type(), loop_provider
        )

        # create the bootloader instance
        self.bootloader_config = BootLoaderConfig(
            self.bootloader, self.xml_state, self.root_dir,
            {'targetbase': loop_provider.get_device()}
        )

        # create disk partitions and instance device map
        device_map = self.__build_and_map_disk_partitions()

        # create raid on current root device if requested
        if self.mdraid:
            self.raid_root = RaidDevice(device_map['root'])
            self.raid_root.create_degraded_raid(raid_level=self.mdraid)
            device_map['root'] = self.raid_root.get_device()

        # create luks on current root device if requested
        if self.luks:
            self.luks_root = LuksDevice(device_map['root'])
            self.luks_root.create_crypto_luks(
                passphrase=self.luks, os=self.luks_os
            )
            device_map['root'] = self.luks_root.get_device()

        # create filesystems on boot partition(s) if any
        self.__build_boot_filesystems(device_map)

        # create volumes and filesystems for root system
        if self.volume_manager_name:
            volume_manager_custom_parameters = {
                'root_filesystem_args':
                    self.custom_filesystem_args,
                'root_label':
                    self.disk_setup.get_root_label(),
                'root_is_snapshot':
                    self.xml_state.build_type.get_btrfs_root_is_snapshot()
            }
            volume_manager = VolumeManager(
                self.volume_manager_name, device_map['root'],
                self.root_dir + '/',
                self.volumes, volume_manager_custom_parameters
            )
            volume_manager.setup(
                self.volume_group_name
            )
            volume_manager.create_volumes(
                self.requested_filesystem
            )
            volume_manager.mount_volumes()
            self.system = volume_manager
            device_map['root'] = volume_manager.get_device()['root']
        else:
            log.info(
                'Creating root(%s) filesystem on %s',
                self.requested_filesystem, device_map['root'].get_device()
            )
            filesystem = FileSystem(
                self.requested_filesystem, device_map['root'],
                self.root_dir + '/',
                self.custom_filesystem_args
            )
            filesystem.create_on_device(
                label=self.disk_setup.get_root_label()
            )
            self.system = filesystem

        # create a random image identifier
        self.mbrid = ImageIdentifier()
        self.mbrid.calculate_id()

        # create first stage metadata to boot image
        self.__write_partition_id_config_to_boot_image()

        self.__write_recovery_metadata_to_boot_image()

        self.__write_raid_config_to_boot_image()

        self.system_setup.export_modprobe_setup(
            self.boot_image_task.boot_root_directory
        )

        # create first stage metadata to system image
        self.__write_image_identifier_to_system_image()

        self.__write_crypttab_to_system_image()

        # create initrd cpio archive
        self.boot_image_task.create_initrd(self.mbrid)

        # create second stage metadata to boot
        self.__copy_first_boot_files_to_system_image()

        self.__write_bootloader_config_to_system_image(device_map)

        self.mbrid.write_to_disk(
            self.disk.storage_provider
        )

        # syncing system data to disk image
        log.info('Syncing system to image')
        if self.system_efi:
            log.info('--> Syncing EFI boot data to EFI partition')
            self.system_efi.sync_data()

        if self.system_boot:
            log.info('--> Syncing boot data at extra partition')
            self.system_boot.sync_data(
                self.__get_exclude_list_for_boot_data_sync()
            )

        log.info('--> Syncing root filesystem data')
        self.system.sync_data(
            self.__get_exclude_list_for_root_data_sync(device_map)
        )

        # install boot loader
        self.__install_bootloader(device_map)

        self.result.add(
            'disk_image', self.diskname
        )

        # create install media if requested
        if self.install_media:
            if self.image_format:
                log.warning('Install image requested, ignoring disk format')
            if self.install_iso or self.install_stick:
                log.info('Creating hybrid ISO installation image')
                self.install_image.create_install_iso()
                self.result.add(
                    'installation_image', self.install_image.isoname
                )

            if self.install_pxe:
                log.info('Creating PXE installation archive')
                self.install_image.create_install_pxe_archive()
                self.result.add(
                    'installation_pxe_archive', self.install_image.pxename
                )

        # create disk image format if requested
        elif self.image_format:
            log.info('Creating %s Disk Format', self.image_format)
            disk_format = DiskFormat(
                self.image_format, self.xml_state,
                self.root_dir, self.target_dir
            )
            disk_format.create_image_format()
            self.result.add(
                'disk_format_image',
                self.target_dir + '/' + disk_format.get_target_name_for_format(
                    self.image_format
                )
            )

        return self.result

    def __install_image_requested(self):
        if self.install_iso or self.install_stick or self.install_pxe:
            return True

    def __get_exclude_list_for_root_data_sync(self, device_map):
        exclude_list = [
            'image', '.profile', '.kconfig', 'var/cache/kiwi'
        ]
        if 'boot' in device_map and self.bootloader == 'grub2_s390x_emu':
            exclude_list.append('boot/zipl/*')
            exclude_list.append('boot/zipl/.*')
        elif 'boot' in device_map:
            exclude_list.append('boot/*')
            exclude_list.append('boot/.*')
        return exclude_list

    def __get_exclude_list_for_boot_data_sync(self):
        return ['efi/*']

    def __build_boot_filesystems(self, device_map):
        if 'efi' in device_map:
            log.info(
                'Creating EFI(fat16) filesystem on %s',
                device_map['efi'].get_device()
            )
            filesystem = FileSystem(
                'fat16', device_map['efi'], self.root_dir + '/boot/efi/'
            )
            filesystem.create_on_device(
                label=self.disk_setup.get_efi_label()
            )
            self.system_efi = filesystem

        if 'boot' in device_map:
            boot_filesystem = self.requested_boot_filesystem
            if not boot_filesystem:
                boot_filesystem = self.requested_filesystem
            boot_directory = self.root_dir + '/boot/'
            if self.bootloader == 'grub2_s390x_emu':
                boot_directory = self.root_dir + '/boot/zipl/'
                boot_filesystem = 'ext2'
            log.info(
                'Creating boot(%s) filesystem on %s',
                boot_filesystem, device_map['boot'].get_device()
            )
            filesystem = FileSystem(
                boot_filesystem, device_map['boot'], boot_directory
            )
            filesystem.create_on_device(
                label=self.disk_setup.get_boot_label()
            )
            self.system_boot = filesystem

    def __build_and_map_disk_partitions(self):
        self.disk.wipe()
        if self.firmware.legacy_bios_mode():
            log.info('--> creating EFI CSM(legacy bios) partition')
            self.disk.create_efi_csm_partition(
                self.firmware.get_legacy_bios_partition_size()
            )

        if self.firmware.efi_mode():
            log.info('--> creating EFI partition')
            self.disk.create_efi_partition(
                self.firmware.get_efi_partition_size()
            )

        if self.disk_setup.need_boot_partition():
            log.info('--> creating boot partition')
            self.disk.create_boot_partition(
                self.disk_setup.boot_partition_size()
            )

        if self.volume_manager_name and self.volume_manager_name == 'lvm':
            log.info('--> creating LVM root partition')
            self.disk.create_root_lvm_partition('all_free')

        elif self.mdraid:
            log.info('--> creating mdraid root partition')
            self.disk.create_root_raid_partition('all_free')

        else:
            log.info('--> creating root partition')
            self.disk.create_root_partition('all_free')

        if self.firmware.bios_mode():
            log.info('--> setting active flag to primary boot partition')
            self.disk.activate_boot_partition()

        self.disk.map_partitions()
        return self.disk.get_device()

    def __write_partition_id_config_to_boot_image(self):
        log.info('Creating config.partids in boot system')
        filename = self.boot_image_task.boot_root_directory + '/config.partids'
        partition_id_map = self.disk.get_partition_id_map()
        with open(filename, 'w') as partids:
            for id_name, id_value in partition_id_map.iteritems():
                partids.write('%s="%s"\n' % (id_name, id_value))

    def __write_raid_config_to_boot_image(self):
        if self.mdraid:
            log.info('Creating etc/mdadm.conf in boot system')
            self.raid_root.create_raid_config(
                self.boot_image_task.boot_root_directory + '/etc/mdadm.conf'
            )

    def __write_crypttab_to_system_image(self):
        if self.luks:
            log.info('Creating etc/crypttab')
            self.luks_root.create_crypttab(
                self.root_dir + '/etc/crypttab'
            )

    def __write_image_identifier_to_system_image(self):
        log.info('Creating image identifier: %s', self.mbrid.get_id())
        self.mbrid.write(
            self.root_dir + '/boot/mbrid'
        )

    def __write_recovery_metadata_to_boot_image(self):
        if os.path.exists(self.root_dir + '/recovery.partition.size'):
            log.info('Copying recovery metadata to boot image')
            Command.run(
                [
                    'cp', self.root_dir + '/recovery.partition.size',
                    self.boot_image_task.boot_root_directory
                ]
            )

    def __write_bootloader_config_to_system_image(self, device_map):
        log.info('Creating %s bootloader configuration', self.bootloader)
        boot_device = device_map['root']
        if 'boot' in device_map:
            boot_device = device_map['boot']

        partition_id_map = self.disk.get_partition_id_map()
        boot_partition_id = partition_id_map['kiwi_RootPart']
        if 'kiwi_BootPart' in partition_id_map:
            boot_partition_id = partition_id_map['kiwi_BootPart']

        boot_uuid = self.disk.get_uuid(
            boot_device.get_device()
        )
        self.bootloader_config.setup_disk_boot_images(boot_uuid)
        self.bootloader_config.setup_disk_image_config(boot_uuid)
        self.bootloader_config.write()

        self.system_setup.call_edit_boot_config_script(
            self.requested_filesystem, boot_partition_id
        )

    def __install_bootloader(self, device_map):
        boot_device = device_map['root']
        custom_install_arguments = {}
        if 'boot' in device_map:
            boot_device = device_map['boot']
            custom_install_arguments['boot_device'] = boot_device.get_device()

        bootloader = BootLoaderInstall(
            self.bootloader, self.root_dir, self.disk.storage_provider,
            custom_install_arguments
        )
        bootloader.install()

        self.system_setup.call_edit_boot_install_script(
            self.diskname, boot_device.get_device()
        )

    def __copy_first_boot_files_to_system_image(self):
        log.info('Copy boot files to system image')
        kernel = Kernel(self.boot_image_task.boot_root_directory)
        if kernel.get_kernel():
            log.info('--> boot image kernel as first boot linux.vmx')
            kernel.copy_kernel(
                self.root_dir, '/boot/linux.vmx'
            )
        else:
            raise KiwiDiskBootImageError(
                'No kernel in boot image tree %s found' %
                self.boot_image_task.boot_root_directory
            )
        if self.machine and self.machine.get_domain() == 'dom0':
            if kernel.get_xen_hypervisor():
                log.info('--> boot image Xen hypervisor as xen.gz')
                kernel.copy_xen_hypervisor(
                    self.root_dir, '/boot/xen.gz'
                )
            else:
                raise KiwiDiskBootImageError(
                    'No hypervisor in boot image tree %s found' %
                    self.boot_image_task.boot_root_directory
                )
        log.info('--> initrd archive as first boot initrd.vmx')
        Command.run(
            [
                'mv', self.boot_image_task.initrd_filename,
                self.root_dir + '/boot/initrd.vmx'
            ]
        )
Пример #40
0
    def create(self):
        if self.install_media and self.build_type_name != 'oem':
            raise KiwiInstallMediaError(
                'Install media requires oem type setup, got %s' %
                self.build_type_name
            )

        # setup recovery archive, cleanup and create archive if requested
        self.system_setup.create_recovery_archive()

        # prepare boot(initrd) root system
        log.info('Preparing boot system')
        self.boot_image_task.prepare()

        # precalculate needed disk size
        disksize_mbytes = self.disk_setup.get_disksize_mbytes()

        # create the disk
        log.info('Creating raw disk image %s', self.diskname)
        loop_provider = LoopDevice(
            self.diskname, disksize_mbytes, self.blocksize
        )
        loop_provider.create()

        self.disk = Disk(
            self.firmware.get_partition_table_type(), loop_provider
        )

        # create the bootloader instance
        self.bootloader_config = BootLoaderConfig(
            self.bootloader, self.xml_state, self.root_dir,
            {'targetbase': loop_provider.get_device()}
        )

        # create disk partitions and instance device map
        device_map = self.__build_and_map_disk_partitions()

        # create raid on current root device if requested
        if self.mdraid:
            self.raid_root = RaidDevice(device_map['root'])
            self.raid_root.create_degraded_raid(raid_level=self.mdraid)
            device_map['root'] = self.raid_root.get_device()

        # create luks on current root device if requested
        if self.luks:
            self.luks_root = LuksDevice(device_map['root'])
            self.luks_root.create_crypto_luks(
                passphrase=self.luks, os=self.luks_os
            )
            device_map['root'] = self.luks_root.get_device()

        # create filesystems on boot partition(s) if any
        self.__build_boot_filesystems(device_map)

        # create volumes and filesystems for root system
        if self.volume_manager_name:
            volume_manager_custom_parameters = {
                'root_filesystem_args':
                    self.custom_filesystem_args,
                'root_label':
                    self.disk_setup.get_root_label(),
                'root_is_snapshot':
                    self.xml_state.build_type.get_btrfs_root_is_snapshot()
            }
            volume_manager = VolumeManager(
                self.volume_manager_name, device_map['root'],
                self.root_dir + '/',
                self.volumes, volume_manager_custom_parameters
            )
            volume_manager.setup(
                self.volume_group_name
            )
            volume_manager.create_volumes(
                self.requested_filesystem
            )
            volume_manager.mount_volumes()
            self.system = volume_manager
            device_map['root'] = volume_manager.get_device()['root']
        else:
            log.info(
                'Creating root(%s) filesystem on %s',
                self.requested_filesystem, device_map['root'].get_device()
            )
            filesystem = FileSystem(
                self.requested_filesystem, device_map['root'],
                self.root_dir + '/',
                self.custom_filesystem_args
            )
            filesystem.create_on_device(
                label=self.disk_setup.get_root_label()
            )
            self.system = filesystem

        # create a random image identifier
        self.mbrid = ImageIdentifier()
        self.mbrid.calculate_id()

        # create first stage metadata to boot image
        self.__write_partition_id_config_to_boot_image()

        self.__write_recovery_metadata_to_boot_image()

        self.__write_raid_config_to_boot_image()

        self.system_setup.export_modprobe_setup(
            self.boot_image_task.boot_root_directory
        )

        # create first stage metadata to system image
        self.__write_image_identifier_to_system_image()

        self.__write_crypttab_to_system_image()

        # create initrd cpio archive
        self.boot_image_task.create_initrd(self.mbrid)

        # create second stage metadata to boot
        self.__copy_first_boot_files_to_system_image()

        self.__write_bootloader_config_to_system_image(device_map)

        self.mbrid.write_to_disk(
            self.disk.storage_provider
        )

        # syncing system data to disk image
        log.info('Syncing system to image')
        if self.system_efi:
            log.info('--> Syncing EFI boot data to EFI partition')
            self.system_efi.sync_data()

        if self.system_boot:
            log.info('--> Syncing boot data at extra partition')
            self.system_boot.sync_data(
                self.__get_exclude_list_for_boot_data_sync()
            )

        log.info('--> Syncing root filesystem data')
        self.system.sync_data(
            self.__get_exclude_list_for_root_data_sync(device_map)
        )

        # install boot loader
        self.__install_bootloader(device_map)

        self.result.add(
            'disk_image', self.diskname
        )

        # create install media if requested
        if self.install_media:
            if self.image_format:
                log.warning('Install image requested, ignoring disk format')
            if self.install_iso or self.install_stick:
                log.info('Creating hybrid ISO installation image')
                self.install_image.create_install_iso()
                self.result.add(
                    'installation_image', self.install_image.isoname
                )

            if self.install_pxe:
                log.info('Creating PXE installation archive')
                self.install_image.create_install_pxe_archive()
                self.result.add(
                    'installation_pxe_archive', self.install_image.pxename
                )

        # create disk image format if requested
        elif self.image_format:
            log.info('Creating %s Disk Format', self.image_format)
            disk_format = DiskFormat(
                self.image_format, self.xml_state,
                self.root_dir, self.target_dir
            )
            disk_format.create_image_format()
            self.result.add(
                'disk_format_image',
                self.target_dir + '/' + disk_format.get_target_name_for_format(
                    self.image_format
                )
            )

        return self.result
Пример #41
0
 def setUp(self):
     self.disk1 = Disk(Point(100, 100), 20, 1, WHITE)
     self.disk2 = Disk(Point(130, 140), 30, 1, WHITE)
     self.disk3 = Disk(Point(120, 130), 30, 1, WHITE)
     self.disk4 = Disk(Point(150, 150), 30, 1, WHITE)
Пример #42
0
    def c2s(self, cluster):
        return ((cluster-2) * self.sectors_per_cluster) + self.first_data_sector


def usage():
    print "%s filename sector"%(sys.argv[0])
    sys.exit(0)


def show_part_info(sector):
    return FAT(sector)


def get_fat_table(fat, disk):
    s = fat.reserved_sector_count
    print s
    tables = disk.read(s, fat.fatsize)
    return FATable(tables, fat.fstype)


if __name__ == '__main__':
    filename = sys.argv[1]
    sector = int(sys.argv[2])
    disk = Disk(512, filename)

    raw = disk.read(sector, 512)
    fat = show_part_info(raw)
    print fat.fstype, fat.first_data_sector, fat.reserved_sector_count, fat.fatsize, fat.root_dir_sectors
    fat_table = get_fat_table(fat, disk)
    print fat.c2s(2)
Пример #43
0
	def backup(self, handle, source, target):
		if Disk.isdir(source):
			target_path = '%s/%s' % (target, os.path.split(source)[1])
			self.backup_dir(handle, source, target_path)
		else:
			self.backup_file(handle, source, target)
Пример #44
0
def _disk_exists(username):
    """ Check whether disk exists or not """
    disk = Disk(username)
    return disk.exists()
Пример #45
0
def main(script, command):
    d = Disk()
    if command == 'upload':
        d.upload()
    elif command == 'download':
        d.download()
Пример #46
0
def disk_test():

    timeout = 500

    # Set up a disk model, disk, and some files for testing purposes
    test_disk = DiskModel(
        2.5,    # spin up time
        30,     # spin up energy
        10,     # spin down energy
        3,      # idle power
        7,      # read power
        8,      # write power
        300*units.MiB,  # speed
        0.003,  # seek time
        500*units.GiB)  # capacity
    disk = Disk(test_disk, timeout)

    file1 = FileInfo("file1", "/", FileType.TEXT, 1*units.GiB)
    file1_compressed_size = 300*units.MiB
    file2 = FileInfo("file2", "/", FileType.BINARY, 40*units.MiB)
    file2_compressed_size = 35*units.MiB

    # Tests
    passed = True

    # Write when the disk is on
    current_time = timeout / 2
    disk.update_time(current_time)
    time = disk.write(file1, file1_compressed_size)
    energy = disk.get_energy_usage()

    expected_time = test_disk.seek_time + (file1_compressed_size /
                                           test_disk.speed)
    expected_energy = (timeout / 2) * test_disk.idle_power + \
                      expected_time * test_disk.write_power;
    if not floateq(time, expected_time):
        passed = False
        print "Failed write test 1 for time"
    if not floateq(energy, expected_energy):
        passed = False
        print "Failed write test 1 for energy"

    # Write when the disk is off
    current_time += timeout * 2
    disk.update_time(current_time)
    time = disk.write(file2, file2_compressed_size)
    energy = disk.get_energy_usage()

    expected_time = test_disk.spin_up_time + \
                    test_disk.seek_time + \
                    (file2_compressed_size / test_disk.speed)
    expected_energy += timeout * test_disk.idle_power + \
                       test_disk.spin_down_energy + \
                       test_disk.spin_up_energy + \
                       (expected_time - test_disk.spin_up_time) * \
                       test_disk.write_power;
    if not floateq(time, expected_time):
        passed = False
        print "Failed write test 2 for time"
    if not floateq(energy, expected_energy):
        passed = False
        print "Failed write test 2 for energy"

    # Read when the disk is on
    current_time += timeout / 2
    disk.update_time(current_time)
    time = disk.read(file1)
    energy = disk.get_energy_usage()

    expected_time = test_disk.seek_time + (file1_compressed_size /
                                           test_disk.speed)
    expected_energy += (timeout / 2) * test_disk.idle_power + \
                       expected_time * test_disk.read_power;
    if not floateq(time, expected_time):
        passed = False
        print "Failed read test 1 for time"
    if not floateq(energy, expected_energy):
        passed = False
        print "Failed read test 1 for energy"
        

    # Read when the disk is off
    current_time += timeout * 5
    disk.update_time(current_time)
    time = disk.read(file2)
    energy = disk.get_energy_usage()

    expected_time = test_disk.spin_up_time + \
                    test_disk.seek_time + \
                    (file2_compressed_size / test_disk.speed)
    expected_energy += timeout * test_disk.idle_power + \
                       test_disk.spin_down_energy + \
                       test_disk.spin_up_energy + \
                       (expected_time - test_disk.spin_up_time) * \
                       test_disk.read_power;
    if not floateq(time, expected_time):
        passed = False
        print "Failed read test 2 for time"
    if not floateq(energy, expected_energy):
        passed = False
        print "Failed read test 2 for energy"


    # Try to read something that doesn't exist
    file3 = FileInfo("file1", "/newpath/", FileType.TEXT, 1*units.GiB)
    exception_occurred = False
    try:
        disk.read(file3)
    except:
        exception_occurred = True
    if not exception_occurred:
        passed = False
        print "Failed read test for non-existant file"

    if passed:
        print "All disk tests passed"
    else:
        print "Disk tests FAILED"
Пример #47
0
"""

from utils import SRC_ROM_PATH, DEST_ROM_PATH, TYPESET_ROM_PATH, onscreen_length
from rominfo import DAT_MAX_LENGTH

from disk import Disk, EXEFile, DATFile, Pointer


#FILES_TO_TYPESET =  ['ST1.EXE', 'ST2.EXE',]
FILES_TO_TYPESET = ['ST1.EXE', 'ST2.EXE', 'ST3.EXE', 'ST4.EXE', 'ST5.EXE', 'ST5S1.EXE', 'ST5S2.EXE', 'ST6.EXE']

PATCHED_ROM_PATH = DEST_ROM_PATH
TYPESET_ROM_PATH = TYPESET_ROM_PATH

if __name__ == '__main__':
    DiskA = Disk(DEST_ROM_PATH, TYPESET_ROM_PATH, FILES_TO_TYPESET)
    for gamefile in DiskA.gamefiles:
        gamefile.refresh_pointers()
        for b in gamefile.blocks:
            if b in (gamefile.spare_block, gamefile.other_spare_block, gamefile.creature_block):
                continue
            for p_int in b.get_pointers():
                first_pointer = gamefile.pointers[p_int][0]
                if len(first_pointer.translations) > 0:
                    if first_pointer.translations[0].english == 'Cancel':
                        continue
                    try:
                        original_text = str(first_pointer.text())
                        first_pointer.typeset()
                    except TypeError:
                        pass