Ejemplo n.º 1
0
def gauss():
    """
    The driver for the generator based implementation
    """
    from Disk import Disk
    from Gaussian import Gaussian
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(-1,1), (-1,1)]
    B = functools.reduce(operator.mul, ((right-left) for left,right in zip(*box)))#@\label{line:mc:volume}@
    # the point cloud generator
    generator = Mersenne()
    # the region of integration
    disk = Disk(center=(0,0), radius=1)
    # the integrand
    gaussian = Gaussian(mean=(0,0), spread=1/3)

    # the integration algorithm
    # build the point sample
    sample = generator.points(N, box)
    # select the interior points
    interior = disk.interior(sample)
    # compute the integral
    integral = B/N * sum(gaussian.eval(interior))#@\label{line:mc:integral}@

    # print the estimate of the integral
    print("integral: {:.8f}".format(integral))
    return
Ejemplo n.º 2
0
    def add_disk(self, disk_pos_x) -> bool:
        """
        Add new disk to the game board using the horizontal position
        of the mouse click. Then check if that new disk has won the game.

        returns True if the new disk has won the game.
        """
        col = (disk_pos_x // 100)  # the colomn index on the board list
        row = find_row(self.game_board[col]
                       )  #find the first non empty row in the given column

        if row < 6:
            self.curr_disk = Disk(self.win, disk_pos_x, row, col,
                                  self.curr_colour)  #create disk object
            self.game_board[col][
                row] = self.curr_disk  #insert disk in the proper location on the board
            self.curr_disk.set_up_disk(
                self.game_board
            )  #connect the disk to all surrounding disks on the board
            while (self.curr_disk.get_set() != True):
                self.game_view.time_delay()
                self.update_view(False)
            if (self.curr_disk.check_win()
                ):  #check if the disk has won the game
                return True
            return False
        return False
Ejemplo n.º 3
0
def gauss():
    """
    The driver for the generator based implementation
    """
    from Disk import Disk
    from Gaussian import Gaussian
    from Mersenne import Mersenne

    # inputs
    N = 10**7
    box = [(-1, -1), (1, 1)]
    B = functools.reduce(operator.mul,
                         ((right - left) for left, right in zip(*box)))
    # the point cloud generator
    generator = Mersenne()
    # the region of integration
    disk = Disk(center=(0, 0), radius=1)
    # the integrand
    gaussian = Gaussian(mean=(0, 0), spread=1 / 3)

    # the integration algorithm
    # build the point sample
    sample = generator.points(N, box)
    # select the interior points
    interior = disk.interior(sample)
    # compute the integral
    integral = B / N * sum(gaussian.eval(interior))

    # print out the estimate of the integral
    print("integral: {0:.8f}".format(integral))
    return
Ejemplo n.º 4
0
    def __init__(self, num_disks, number=None):
        self.disks = list()
        self.disks_by_name = dict()
        self.disk_names = list()

        disk_names = ["orange", "yellow", "green", "blue", "purple"]

        for idx in range(num_disks):
            disk = Disk()
            disk_name = disk_names[idx]

            self.disks.append(disk)
            self.disks_by_name[disk_names[idx]] = disk
            self.disk_names.append(disk_name)

        if number is not None:
            pos = self.num_disk_positions
            rest = number
            for disk_name in reversed(disk_names):
                disk = self.disks_by_name[disk_name]
                disk_idx = disk_names.index(disk_name)
                pole_idx = rest // pos**disk_idx

                disk.pole = pole_idx
                rest = rest - pole_idx * pos**disk_idx
Ejemplo n.º 5
0
def gauss():
    """
    The driver for the object oriented solution
    """
    from Disk import Disk
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(0,0), (1,1)]
    # the point cloud generator
    cloud = Mersenne()
    # the region of integration
    disk = Disk(center=(0,0), radius=1)

    # the integration algorithm
    total = 0
    interior = 0
    while total < N:
        point = cloud.point(box)
        if disk.interior(point):
            interior += 1
        total += 1

    # print out the estimate of #@$\pi$@
    print("pi: {0:.8f}".format(4*interior/N))
    return
Ejemplo n.º 6
0
 def load_components(self):
     ''' Loads all essentials components'''
     # print("Loading components")
     self.table_of_pages = TableOfPages(self.mem_vir_size, self.page_size,
                                        self.num_prog)
     self.ram = Ram(self.mem_fis_size, self.page_size, self.subtitution, self.num_prog)
     self.tlb = Tlb(self.num_line, self.subs, self.corr, self.num_prog)
     self.disk = Disk(self.num_prog)
Ejemplo n.º 7
0
def testDisk():
    from Disk import Disk
    disk = Disk(center=(0, 0), radius=1)

    points = [(0, 0), (.5, .5), (1, 1)]

    print(count(disk.contains(points)))

    return
Ejemplo n.º 8
0
 def __init__(self, screen_rect, window):
     self.score = {'Red': 0, 'Blue': 0}
     self.players = []
     self.players_threads = []
     self.game_objects = []
     self.screen_rect = screen_rect
     self.window = window
     self.player_size = (pygame.image.load('images/player1_1.png')).get_rect()
     self.center_field = {'x': WINDOW_WIDTH / 2, 'y': WINDOW_HEIGHT / 2}
     self.disk = Disk(self)
Ejemplo n.º 9
0
class DeviceManager:
    def __init__(self):
        self.memory = Memory()
        self.disk = Disk()

    def save_program(self, program):
        self.disk.add_program(program)

    def get_program(self, programs_name):
        return self.disk.get_program(programs_name)

    def load_program(self, program):
        return self.memory.load(program)
Ejemplo n.º 10
0
    def run(self):
        notify_email = properties["notify_email"]
        cpu = Cpu(properties["cpu_monitor_rate"],
                  properties["cpu_over_max_count"], notify_email)

        disk = Disk(properties["all_disk_max_capacity"],
                    properties["single_file_max_capacity"],
                    properties["all_disk_warn_capacity"],
                    properties["direct_remove_file_suffix"],
                    properties["mem_warn_capacity"], log, notify_email)
        ytj = YTJService(log)

        second = int(properties["check_interval"])

        while 1:
            try:
                # cpu.monitor()
                log.info("cpu health")
            except Exception as e:
                log.error("cpu检测脚本出错%s", e.with_traceback(sys.exc_info()[2]))
            try:
                # disk.cpu_system_info()
                log.info("disk health")
            except Exception as e:
                log.error("磁盘检测脚本出错%s", e.with_traceback(sys.exc_info()[2]))

            try:
                ytj.check()
                log.info("ytj health")
            except Exception as e:
                log.error("磁盘ytj脚本出错%s", e.with_traceback(sys.exc_info()[2]))

                time.sleep(second)
Ejemplo n.º 11
0
    def getDisks(self):
        """
        Enumerate all the disks present on the system, updating the cmdb object accordingly

        Create a disk instance for each disk on the system, populate the attributes and add it to the cmdb's hardDisks collection
        @return: cmdb.hardDisks
        """
        disks = j.cloud.cmdtools.inventoryScan.getDisks()
        currentAvailableDisks = list()
        for name, value in disks.iteritems():
            size = int(float(value['size']) *
                       1024) if value['unit'] == 'GB' else int(
                           float(value['size']))
            partitions = value['partitions']
            currentAvailableDisks.append(name)
            if name in self.cmdb.disks.keys():
                self.cmdb.disks[name].name = name
                self.cmdb.disks[name].size = size
            else:
                disk = Disk()
                disk.name = name
                disk.size = size
                self.cmdb.disks[name] = disk
            if partitions:
                disk = self.cmdb.disks[name]
                disk.partitions = list()
                for part in partitions:
                    partition = Partition(
                        part['Type'], part['number'], part['start'],
                        part['end'], int(float(part['size'][0:-3])),
                        part['mountpoint'] if 'mountpoint' in part else '',
                        part['used'] if 'used' in part else 0.0,
                        part['name'] if 'name' in part else '',
                        part['flag'] if 'flag' in part else '')
                    if 'devices' in part:
                        partition.raid = PartitionRaid(
                            part['level'], part['state'], part['devices'],
                            part['activeDevices'], part['failedDevices'],
                            part['totalDevices'], part['raidDevices'],
                            part['spareDevices'], part['backendsize'])
                    disk.partitions.append(partition)

        for disk in self.cmdb.disks.keys():
            if disk not in currentAvailableDisks:
                del self.cmdb.disks[disk]
        self.cmdb.dirtyProperties.add('disks')
        return disks
Ejemplo n.º 12
0
    def reconstruct_disk(self, disk_num):
        print("Reconstructing Disk")
        if (self.num_disks - len(self.disks)) > 1:
            raise DiskReconstructException(
                "Cannot reconstruct disk: too many disks missing")

        new_disk = Disk(disk_num, self.disk_cap)
        for i in range(len(self.disks[0])):
            block = []
            for j in range(len(self.disks)):
                block.append(self.disks[j].read(i))
            self.validate_parity(
                block + [format(self.calculate_parity(block), bin_format)])

            new_disk.write(format(self.calculate_parity(block), bin_format))
        self.disks.insert(disk_num, new_disk)
        self.validate_disks()
Ejemplo n.º 13
0
    def getDisks(self):
        """
        Enumerate all the disks present on the system, updating the cmdb object accordingly

        Create a disk instance for each disk on the system, populate the attributes and add it to the cmdb's hardDisks collection
        @return: cmdb.hardDisks
        """
        disks = j.cloud.cmdtools.inventoryScan.getDisks()
        currentAvailableDisks = list()
        for name, value in disks.iteritems():
            size = int(float(value['size']) * 1024) if value['unit'] == 'GB' else int(float(value['size']))
            partitions = value['partitions']
            currentAvailableDisks.append(name)
            if name in self.cmdb.disks.keys():
                self.cmdb.disks[name].name = name
                self.cmdb.disks[name].size = size
            else:
                disk = Disk()
                disk.name = name
                disk.size = size
                self.cmdb.disks[name] = disk
            if partitions:
                disk = self.cmdb.disks[name]
                disk.partitions = list()
                for part in partitions:
                    partition = Partition(part['Type'],
                                          part['number'],
                                          part['start'],
                                          part['end'],
                                          int(float(part['size'][0:-3])),
                                          part['mountpoint'] if 'mountpoint' in part else '',
                                          part['used'] if 'used' in part else 0.0,
                                          part['name'] if 'name' in part else '',
                                          part['flag'] if 'flag' in part else '')
                    if 'devices' in part:
                        partition.raid = PartitionRaid(part['level'], part['state'], part['devices'], part['activeDevices'],
                                                       part['failedDevices'], part['totalDevices'], part['raidDevices'],
                                                       part['spareDevices'], part['backendsize'])
                    disk.partitions.append(partition)

        for disk in self.cmdb.disks.keys():
            if disk not in currentAvailableDisks:
                del self.cmdb.disks[disk]
        self.cmdb.dirtyProperties.add('disks')
        return disks
Ejemplo n.º 14
0
 def get_all_disks(self):
     for disk in self.allDisks.split():
         self.disksList.update({
             disk:
             Disk(
                 Utils.produce_command(
                     "sudo fdisk -l | grep /dev/sda: |awk '{print $3$4}'"),
                 Utils.produce_command("cat /sys/block/sd?/device/vendor"))
         })
Ejemplo n.º 15
0
    def reset_disks(self):
        self.disks.clear()
        self.clear_towers()
        self.moves = 0
        for index in range(self.numDisks, 0, -1):
            disk = Disk(index, self.towerS)
            # print(self.towerS.get_min_disk_index())
            self.towerS.add_disk(disk)

            self.disks.append(disk)
Ejemplo n.º 16
0
 def __init__(self, n=3, start="A", workspace="B", destination="C"):
     self.startp = Pole(start, 0, 0)
     self.workspacep = Pole(workspace, 150, 0)
     self.destinationp = Pole(destination, 300, 0)
     self.startp.showpole()
     self.workspacep.showpole()
     self.destinationp.showpole()
     for i in range(n):
         self.startp.pushdisk(
             Disk("d" + str(i), 0, i * 150, 20, (n - i) * 30))
Ejemplo n.º 17
0
 def test_Disk_10_InitialSync(self):
     test_Disk.disk = Disk({
         'login': '******',
         'auth': self.token,
         'path': '~/yd',
         'start': True,
         'ro': False,
         'ow': False,
         'exclude': ['excluded_folder']
     })
     sleep(50)
     self.assertTrue(self.disk.status == 'idle')
Ejemplo n.º 18
0
 def test_Disk_01_noAccess(self):
     test_Disk.disk = Disk({
         'login': '******',
         'auth': self.token,
         'path': '/root',
         'start': True,
         'ro': False,
         'ow': False,
         'exclude': ['excluded_folder']
     })
     sleep(2)
     self.assertTrue(self.disk.status == 'fault')
     self.assertEqual(self.disk.exit(), 0)
Ejemplo n.º 19
0
 def test_Disk_00_notStarted(self):
     test_Disk.disk = Disk({
         'login': '******',
         'auth': self.token,
         'path': '~/yd',
         'start': False,
         'ro': False,
         'ow': False,
         'exclude': ['excluded_folder']
     })
     sleep(2)
     self.assertTrue(self.disk.status == 'none')
     self.assertEqual(self.disk.exit(), 0)
Ejemplo n.º 20
0
def gauss():
    """
    The driver for the container based implementation
    """
    from Disk import Disk
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(0,1), (0,1)]
    # the point cloud generator
    cloud = Mersenne()
    # the region of integration
    disk = Disk(center=(0,0), radius=1)

    # the integration algorithm
    # build the point sample
    sample = cloud.points(N, box)
    # count the interior points
    interior = len(disk.interior(sample))

    # print the estimate of π
    print("π: {:.8f}".format(4*interior/N))
    return
Ejemplo n.º 21
0
def gauss():
    """
    The driver for the object oriented solution
    """
    from Disk import Disk
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(0,1), (0,1)]
    # the point cloud generator
    cloud = Mersenne()
    # the region of integration
    disk = Disk(center=(0,0), radius=1)

    # the integration algorithm
    interior = 0
    for i in range(N):
        point = cloud.point(box)
        if disk.interior(point):
            interior += 1
    # print the estimate of π
    print("π: {:.8f}".format(4*interior/N))
    return
Ejemplo n.º 22
0
def gauss():
    """
    The driver for the object oriented solution
    """
    from Disk import Disk
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(0, 1), (0, 1)]
    # the point cloud generator
    cloud = Mersenne()
    # the region of integration
    disk = Disk(center=(0, 0), radius=1)

    # the integration algorithm
    interior = 0
    for i in range(N):
        point = cloud.point(box)
        if disk.interior(point):
            interior += 1
    # print the estimate of π
    print("π: {:.8f}".format(4 * interior / N))
    return
Ejemplo n.º 23
0
def gauss():
    """
    The driver for the generator based implementation
    """
    from Disk import Disk
    from Mersenne import Mersenne

    # inputs
    N = 10**5
    box = [(0, 1), (0, 1)]
    # the point cloud
    cloud = Mersenne()
    # the region of integration
    disk = Disk(center=(0, 0), radius=1)

    # the integration algorithm
    # build the point sample
    sample = cloud.points(N, box)
    # count the interior points
    interior = count(disk.interior(sample))

    # print the estimate of π
    print("π: {:.8f}".format(4 * interior / N))
    return
Ejemplo n.º 24
0
 def __generate_disks(self):
     print "\nGenerating Disks by grouping access percentages:   Started"
     if len(self.__values) > 0:
         starting_point = self.__values[0][1]
         name = 1
         disk = Disk(name)
         self.__disks.append(disk)
         for i in range(len(self.__values)):
             if math.fabs(self.__values[i][1] - starting_point) < 0.01:
                 disk.add_data(self.__values[i][0], self.__values[i][1])
             else:
                 starting_point = self.__values[i][1]
                 name += 1
                 disk = Disk(name)
                 self.__disks.append(disk)
                 disk.add_data(self.__values[i][0], self.__values[i][1])
     print "Generating Disks by grouping access percentages:   Finished"
     print "There are %d Disks" % len(self.__disks)
Ejemplo n.º 25
0
class MainGame:
    def __init__(self, screen_rect, window):
        self.score = {'Red': 0, 'Blue': 0}
        self.players = []
        self.players_threads = []
        self.game_objects = []
        self.screen_rect = screen_rect
        self.window = window
        self.player_size = (pygame.image.load('images/player1_1.png')).get_rect()
        self.center_field = {'x': WINDOW_WIDTH / 2, 'y': WINDOW_HEIGHT / 2}
        self.disk = Disk(self)

    def initialize_game(self):
        self.add_players()
        self.repopulate_player_threads()
        self.change_player_threads(True)
        all_game_objects = self.players.copy()
        all_game_objects.append(self.disk)
        self.game_objects = pygame.sprite.RenderPlain(*all_game_objects)

    def draw_board(self, screen, background):
        self.players[0].read()
        self.game_objects.clear(screen, background)
        self.game_objects.draw(screen)

    def add_players(self):
        self.players.append(KeyboardPlayer(0, self))
        # paths = Controller.return_microsoft_paths()
        # for index in range(len(paths)):
        #     self.players.append(ControllerPlayer(index + 1, Controller(paths[index])))

    def repopulate_player_threads(self):
        del self.players_threads[:]
        for player in self.players:
            if type(player) is ControllerPlayer:
                self.players_threads.append(ControllerPlayerThread(player, player.player_num, self))

    def change_player_threads(self, on):
        for player_thread in self.players_threads:
            try:
                if on:
                    player_thread.start()
                else:
                    player_thread.stop()
            except RuntimeError:
                self.repopulate_player_threads()
                self.change_player_threads(on)

    def movement_allowed(self, player_num, pos_dirs):
        """ Returns true if movement is allowed. """
        new_rect = self.players[player_num].rect.move(pos_dirs[0], pos_dirs[1])
        return self.check_in_field(new_rect) and self.check_player_collide(player_num, new_rect)

    def throw_allowed(self, player_num, rect):
        if self.distance_from_center(rect) <= 10:
            self.team_score(player_num)
        return self.screen_rect.contains(rect) and self.check_player_collide(player_num, rect)

    def check_in_field(self, new_rect):
        if self.distance_from_center(new_rect) <= 125:
            return False
        return self.screen_rect.contains(new_rect)

    def check_player_collide(self, player_num, new_rect):
        for player in self.players:
            if player.player_num == player_num:
                continue
            if player.rect.colliderect(new_rect):
                return False
        return True

    def distance_from_center(self, rect):
        return math.hypot(rect.center[0] - self.center_field['x'], rect.center[1] - self.center_field['y'])

    def team_score(self, player_num):
        self.disk.stop_movement()
        if player_num % 2 == 0:
            self.score['Red'] += 1
        else:
            self.score['Blue'] += 1
        self.window.update_score()
        self.disk.force_set_disk(300, 300)
Ejemplo n.º 26
0
class CPU:

    def __init__(self, MEM_FIS_SIZE, MEM_VIR_SIZE, PAGE_SIZE, SUBSTITUTION,
                 NUM_LINE, CORR, SUBS, NUM_PROG, PROG):
        self.mem_fis_size = MEM_FIS_SIZE
        self.mem_vir_size = MEM_VIR_SIZE
        self.page_size = PAGE_SIZE
        self.subtitution = SUBSTITUTION
        self.num_line = NUM_LINE
        self.corr = CORR
        self.subs = SUBS
        self.num_prog = NUM_PROG
        self.prog = PROG

        if DEBUG_MODE:
            print("*" * 50 + "\n")

        # Stores index of current program running
        self.current_program_index = 0

        # Dict to store last addr for each program
        # {program_index : last_addr_used_index}
        self.last_addr_used_register = {prog: 0 for prog in range(self.num_prog)}

        # Works as a timestamp for FIFO, LFU, LRU stats
        self.iteration = 0

        self.load_components()

    @property
    def is_finished(self):
        ''' Returns true if all programs did everything they had to do.
        Checks if last index of program is equal to the length  - 1 for
        every program'''
        last_address_programs = [len(prog) - 1 for prog in self.prog]
        last_used = self.last_addr_used_register.values()
        comparations = [i == j for i, j in zip(last_address_programs, last_used)]

        return len(set(comparations)) == 1 and comparations[0]

    @property
    def current_program_list(self):
        ''' Returns current program list '''
        return self.prog[self.current_program_index]

    @property
    def current_program_is_finished(self):
        ''' Compares indexes of last addr used and len of program - 1 '''
        last_addr_current_program = len(self.current_program_list) - 1
        last_addr_used = self.last_addr_used_register[self.current_program_index]

        return last_addr_used == last_addr_current_program

    def load_components(self):
        ''' Loads all essentials components'''
        # print("Loading components")
        self.table_of_pages = TableOfPages(self.mem_vir_size, self.page_size,
                                           self.num_prog)
        self.ram = Ram(self.mem_fis_size, self.page_size, self.subtitution, self.num_prog)
        self.tlb = Tlb(self.num_line, self.subs, self.corr, self.num_prog)
        self.disk = Disk(self.num_prog)

    def print_components(self):
        # print(repr(self.table_of_pages))
        print(repr(self.ram))
        print(repr(self.tlb))
        # print(repr(self.disk))

    def run_programs(self):
        ''' Flow control to run programs in correct order '''

        while not self.is_finished:
            # If current program is finished go to next program
            if self.current_program_is_finished:
                # print("Program {} already finished".format(self.current_program_index))
                self.next_program()
                continue

            # If it is not finished, use it
            if DEBUG_MODE:
                print("-" * 25)
                print("Current program {}".format(self.current_program_index))

            # Get last addres used by this program
            last_used_this_program = self.last_addr_used_register[self.current_program_index]

            # If program starts with yield, save info and go to next program
            if last_used_this_program == 0 and self.current_program_list[last_used_this_program] == -1:
                if DEBUG_MODE:
                    print("[YIELD] Programa {} ha ejecutado YIELD".format(self.current_program_index))
                self.tlb.clear()

                # Save last addres used in this program and add one so it does not resumes from
                # index 0 and addres -1
                self.last_addr_used_register[self.current_program_index] = last_used_this_program + 1

                # Go to next program
                self.next_program()

                # Skip iteration
                continue

            # If not, check if it resumes from a -1.
            # Add one to the index if cpu takes this program from a -1
            last_used_this_program = last_used_this_program + 1 if self.current_program_list[last_used_this_program] == -1 else last_used_this_program

            # For every address not used, run it
            for j, addr in enumerate(self.current_program_list):
                # Omit addresses already used
                if j < last_used_this_program:
                    continue

                if DEBUG_MODE:
                    print()
                    print("Iteration: {}".format(self.iteration))
                    print("Addr: {}, program: {}".format(addr, self.current_program_index))
                    print()

                # Save last addres used in this program
                self.last_addr_used_register[self.current_program_index] = j

                # If addr is a yield, clean TLB and go to next program
                if addr < 0:
                    if DEBUG_MODE:
                        print("[YIELD] Programa {} ha ejecutado YIELD".format(self.current_program_index))

                    self.tlb.clear()

                    # Go to next program
                    self.next_program()

                    # Break out of for loop
                    break

                # If it is not a yield, increase iteration counter
                self.iteration += 1

                # Check first digits of addr to get page number
                bin_addr = self.table_of_pages.to_binary(addr)
                bits_to_check = self.table_of_pages.num_of_bits_page
                page_digits = bin_addr[:bits_to_check]
                offset_digits = bin_addr[bits_to_check:]
                page_number = self.table_of_pages.to_decimal(page_digits)
                offset_number = self.table_of_pages.to_decimal(offset_digits)
                if DEBUG_MODE:
                    print("[ACCESO] Memoria virtual {}({}) -> Pagina virtual {}({}) Offset {}({})".format(
                        bin_addr, addr, page_digits, page_number, offset_digits, offset_number))

                # Check page in TLB, if it finds the page updates hit count and returns it
                page = self.tlb.get_page(page_number, self.current_program_index, self.iteration)

                if not page:
                    # If it not found, go to table of pages and add to TLB
                    page = self.table_of_pages.get_page(page_number, self.current_program_index)

                    # self.tlb.add_page(page, bin_address, self.iteration)
                    self.tlb.add_page(page, page_digits, self.iteration)

                # Check if it has a marco in RAM
                if not page.has_marco:
                    if DEBUG_MODE:
                        print("[Pagina SIN ASOCIAR] Memoria full: {}".format(self.ram.is_full))
                        # Page fault
                        print("[PAGE FAULT] Página no tiene marco.")

                    self.table_of_pages.update_page_faults(self.current_program_index)

                    # Assign a marco
                    self.ram.add_page(page, self.iteration, self.disk)
                else:
                    # If it has marco it can be on disk or ram
                    if page.marco_on_disk:
                        if DEBUG_MODE:
                            print("[PAGE FAULT] La pagina se encuentra en un marco del disco")

                        # Page fault
                        self.table_of_pages.update_page_faults(self.current_program_index)

                        # Bring back page to ram, and backup one marco to disk
                        self.ram.swap_in_out(page, self.disk, self.iteration)

                        # It counts as a use for page that came back (LFU, LRU)
                        # self.ram.update_counters(page, self.iteration)
                    else:
                        # It has a marco on ram (LFU, LRU)
                        self.ram.update_counters(page, self.iteration)

                if DEBUG_MODE:
                    print(repr(self.ram))
                    print(repr(self.tlb))
                    print()
                    print("self.ram.swap_out_stats, ", self.ram.swap_out_stats)
                    print("self.ram.swap_in_stats, ", self.ram.swap_in_stats)
                    print("#" * 66)

            if self.current_program_is_finished:
                if DEBUG_MODE:
                    print("*****************PROGRAMA {} HA FINALIZADO!************".format(self.current_program_index))
                self.tlb.clear()

        self.print_statistics()

    def print_statistics(self):
        for p in range(self.num_prog):
            print("PROGRAMA  {}".format(p + 1))
            # Hit TLB
            hit_tlb = self.tlb.hit_stats[p]
            page_fault = self.table_of_pages.page_fault_stats[p]
            swap_in = self.ram.swap_in_stats[p]
            swap_out = self.ram.swap_out_stats[p]
            page_disk = self.disk.get_pages_on_disk(p)
            pages_ram = self.ram.get_pages_on_ram(p)
            page_valid = page_disk + pages_ram
            print("hit TLB: {}".format(hit_tlb))
            print("page fault: {}".format(page_fault))
            print("swap in: {}".format(swap_in))
            print("swap out: {}".format(swap_out))
            print("page valid: {}".format(page_valid))
            print("page disk: {}\n".format(page_disk))

    def next_program(self):
        self.current_program_index += 1
        self.current_program_index = 0 if self.current_program_index == self.num_prog else self.current_program_index
Ejemplo n.º 27
0
    print(e)

position = Position()
position.fix()

filename = BoatImage().click(position)

voltages = Voltages()
voltages = voltages.read_voltages()

gyro = Gyro()
x_angle = gyro.get_x_degrees()
temperature = gyro.get_temperature()

tide = Tide()
tide_height = tide.current_height()

uploader = Uploader(bucket_name)

uploader.download_json()

disk_usage = Disk.current_usage()

state = State(position, voltages, filename, x_angle, temperature, tide_height,
              disk_usage)
state.save()

uploader.upload_json()
if filename is not None:
    uploader.upload_image(filename)
Ejemplo n.º 28
0
from Disk import Disk
from Loader import Loader

try:
    disk = Disk()
    loader = Loader()
    # for index in disk.memory:
    #     print(index)

except Exception as ex:
    print(ex.args)
Ejemplo n.º 29
0
import sys

from Disk import Disk
from Simple_Filesystem import Simple_Filesystem

disk = Disk(10000)
fs = Simple_Filesystem(disk)

no_args = len(sys.argv)
image_name = sys.argv[1]
command = sys.argv[2]
if command == "mkdisk":
    fs.format()
    disk.save(image_name)
elif command == "mkfile":
    disk.load(image_name)
    fs.create_file(sys.argv[3])
    disk.save(image_name)
elif command == "list":
    disk.load(image_name)
    number_of_files, files = fs.get_files()
    print('%d file(s)' % number_of_files)
    for filename in files.keys():
        print(filename)
elif command in 'remove':
    filename = sys.argv[3]
    disk.load(image_name)
    number_of_files, files = fs.get_files()
    if filename in files:
        fs.delete_file(files[filename])
    else:
Ejemplo n.º 30
0
 def __init__(self):
     self.memory = Memory()
     self.disk = Disk()
Ejemplo n.º 31
0
    confHome = expanduser(path_join('~', '.config', appName))
    config = Config(path_join(confHome, 'client.conf'))
    if not config.loaded:
        makedirs(confHome, exist_ok=True)
        config.changed = True
    config.setdefault('type', 'std')
    config.setdefault('disks', {})
    if config.changed:
        config.save()
    # Setup localization
    translation(appName, '/usr/share/locale', fallback=True).install()

    disks = []
    while True:
        for user in config['disks'].values():
            disks.append(Disk(user))
        if disks:
            break
        else:
            from OAuth import getToken, getLogin
            print(_('No accounts configured'))
            if input(_('Do you want to configure new account (Y/n):')).lower(
            ) not in ('', 'y'):
                appExit(_('Exit.'))
            else:
                while True:
                    path = ''
                    while not pathExists(path):
                        path = input(
                            _('Enter the path to local folder '
                              'which will by synchronized with cloud disk. (Default: ~/YandexDisk):'
Ejemplo n.º 32
0
class Model:
    def __init__(self, win, game_view, game_controller) -> None:

        self.win = win
        self.game_view = game_view
        self.game_controller = game_controller
        self.curr_disk = None
        self.curr_colour = red
        self.game_board = [[None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None]]

    def restart_model(self) -> None:
        """
        Restarts the model to the default
        """
        self.curr_disk = None
        self.curr_colour = red
        self.game_board = [[None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None],[None, None, None, None, None, None],\
                           [None, None, None, None, None, None]]

    def update_view(self, game_over) -> None:
        """
        Send the game view the game board to display.
        """
        self.game_view.display(self.game_board, game_over, self.curr_colour,
                               self.game_controller)

    def get_colour(self):
        return self.curr_colour

    def change_colour(self) -> None:
        """
        Changes the current colour between red and blue to alternate between players.
        Also sets the current disk to None if a switch is made.
        """
        if (self.curr_disk != None and self.curr_disk.get_set()):
            if (self.curr_colour == red):
                self.curr_colour = blue
            else:
                self.curr_colour = red
            self.curr_disk = None

    def add_disk(self, disk_pos_x) -> bool:
        """
        Add new disk to the game board using the horizontal position
        of the mouse click. Then check if that new disk has won the game.

        returns True if the new disk has won the game.
        """
        col = (disk_pos_x // 100)  # the colomn index on the board list
        row = find_row(self.game_board[col]
                       )  #find the first non empty row in the given column

        if row < 6:
            self.curr_disk = Disk(self.win, disk_pos_x, row, col,
                                  self.curr_colour)  #create disk object
            self.game_board[col][
                row] = self.curr_disk  #insert disk in the proper location on the board
            self.curr_disk.set_up_disk(
                self.game_board
            )  #connect the disk to all surrounding disks on the board
            while (self.curr_disk.get_set() != True):
                self.game_view.time_delay()
                self.update_view(False)
            if (self.curr_disk.check_win()
                ):  #check if the disk has won the game
                return True
            return False
        return False
Ejemplo n.º 33
0
        print "\nBroadcast Column view :"
        for i in range(len(broadcast_stack)):
            print "     ", broadcast_stack[i]

if __name__ == "__main__":
    bdisk = BroadCastDisk()
    bdisk.add_data(5, 0.2)
    bdisk.add_data(4, .3)
    bdisk.add_data(6, .2)
    bdisk.add_data(1, .1)
    bdisk.add_data(2, .1)
    bdisk.add_data(3, .05)
    bdisk.add_data(7, .05)

    for i in range(bdisk.get_number_of_data()):
        print "Data: %s, Percentage: %0.6f" % bdisk.get_data_index(i)

    d = Disk(1)
    d.add_data(5, 0.2)
    d.add_data(4, .3)
    d.add_data(6, .2)
    d.add_data(1, .1)
    d.add_data(2, .1)
    d.add_data(3, .05)
    d.add_data(7, .05)
    d.determine_q()
    d.set_frequency(3)
    print "Number of data = %d" % d.get_number_of_data()
    print "Q = %0.6f" % d.get_q()
    print "Frequency = %d" % d.get_frequency()
Ejemplo n.º 34
0
 def __init__(self, num_disks, disk_cap=0):
     self.num_disks = num_disks
     self.disk_cap = disk_cap
     for i in range(num_disks):
         self.disks.append(Disk(i, disk_cap))