def test_Stats(self):
     from stats import Stats
     statistics = Stats(1, 2, 2, 3, 4, 7, 9)
     self.assertAlmostEqual(statistics.mean(), 4.0)
     self.assertEqual(statistics.median(), 3)
     self.assertEqual(statistics.modes(), [2])
     statistics = Stats(1, 2, 2, 3, 4, 7, 9, 7)
     self.assertAlmostEqual(statistics.mean(), 4.375)
     self.assertAlmostEqual(statistics.median(), 3.5)
     self.assertEqual(statistics.modes(), [2, 7])
예제 #2
0
def make_post(event, context):
    posts = []
    paginator = client("dynamodb").get_paginator("scan")
    for page in paginator.paginate(
            TableName="WordpostBotPosts",
            FilterExpression="reactions = :t",
            ExpressionAttributeValues={":t": {
                "BOOL": False
            }}):
        for item in page["Items"]:
            posts.append(item["id"]["S"])

    info_table = resource("dynamodb").Table("WordpostBotInfo")
    credentials = info_table.get_item(Key={"resource": "credentials"})["Item"]
    access_token = credentials["access_token"]
    stats_item = info_table.get_item(Key={"resource": "stats"})["Item"]
    stats = Stats(access_token, posts, stats_item["top_reactors"],
                  stats_item["top_posts"], stats_item["total_posts"],
                  stats_item["total_reactions"])
    session = Session()
    session.params = {"access_token": credentials["access_token"]}
    api_url = "https://graph.facebook.com/v2.10/"
    r = session.post(api_url + credentials["page_id"] + "/feed",
                     data={"message": stats.get_top_reactor_message()})
    r.raise_for_status()
    post_id = r.json()["id"]
    session.post(api_url + post_id + "/comments",
                 data={
                     "message": stats.get_top_post_message()
                 }).raise_for_status()
예제 #3
0
    def __init__(self):
        with open("properties.json") as fp:
            config = json.load(fp)

        # self.q = Queue.Queue()
        # # current completion time of a queue
        policy = config["server"]["allocationPolicy"]
        self.allocation_policy = AllocationPolicy.get_policy(policy)
        self.stat = Stats()

        # TODO : Use this code if we want to use multiple queues
        self.write_server = config["server"]["writeServer"]
        self.read_server = config["server"]["readServer"]
        self.no_of_read_response_required = config["server"][
            "noOfReadResponse"]
        self.no_of_write_response_required = config["server"][
            "noOfWriteResponse"]

        self.server_queues = []
        self.completion_time = []

        for i in range(0, config["server"]["numberOfServers"]):
            self.server_queues.append(Queue.PriorityQueue())
            self.completion_time.append(0)

        self.dist = Distribution.get_distribution(
            config["request"]["distribution"], rate=1)
예제 #4
0
 def reset(self, seed=None):
     self.feq = FutureEventsQueue()
     self.clock = Clock()
     self.stats = Stats()
     if seed is not None:
         random.seed(seed)
     self.initialize()
예제 #5
0
def run_game():
    # initialize game and create screen object
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(settings.screen_res)
    pygame.display.set_caption("Alien Invasion")
    stats = Stats()
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    play_button = Button(settings, screen, 'Play')
    scoreboard = Scoreboard(settings, screen, stats)
    fun.create_fleet(settings, screen, aliens, ship.rect.height, stats)

    # start the main loop for the game
    while True:
        fun.check_events(settings, screen, ship, bullets, stats, aliens, play_button, scoreboard)
        if stats.game_active:
            ship.update()
            bullets.update()
            aliens.update()
            fun.drop_aliens(aliens)
            fun.collide(ship, aliens, bullets, settings, stats)
            fun.delete_bullets(bullets)
        fun.update_screen(screen, settings, ship, bullets, aliens, stats, play_button, scoreboard)
예제 #6
0
 def year_stats(self):
     teams = self.all_info().json()['teams']
     team_to_stats = dict()
     for t in teams:
         stats = Stats(t['valuesByStat'])
         team_to_stats[t['id']] = stats
     return team_to_stats
예제 #7
0
    def send_command(self, command):
        """
        Send a command to the Tello and wait for a response.

        :param command: Command to send.
        :return (str): Response from Tello.

        """
        self.log.append(Stats(command, len(self.log)))
        print(">> send cmd: {}".format(command))
        #self.abort_flag = False
        #timer = threading.Timer(self.command_timeout, self.set_abort_flag)

        self.socket.sendto(command.encode('utf-8'), self.tello_address)
        start = time.time()
        while not self.log[-1].got_response():
            now = time.time()
            diff = now - start
            if diff > self.MAX_TIME_OUT:
                print("Max timeout exceeded... command %s" % command)
                break
            time.sleep(0.01)
            # TODO: is timeout considered failure or next command still get executed
            # now, next one got executed

        print("Command completed: %s to %s" % (command, self.tello_ip))
        return self.log[-1].got_response()
예제 #8
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    screen = pygame.display.set_mode((630, 800))
    pygame.display.set_caption("PACMAN")

    # Draw maze
    mazefile = 'maze.txt'
    maze = Maze(screen, mazefile)

    # Pacman
    pm = PM(screen, maze)

    # Stats
    stats = Stats()

    # Ghosts
    red = Red(screen, maze)
    blue = Blue(screen, maze)
    pink = Pink(screen, maze)
    orange = Orange(screen, maze)
    cherry = Cherry(screen)

    display = Display(screen, pm)

    while True:
        if stats.game_active:
            gf.check_events(screen, pm, maze, red, blue, pink, orange, stats,
                            display)

            gf.update_screen(screen, pm, maze, red, blue, pink, orange, cherry,
                             stats, display)

            pygame.display.flip()
예제 #9
0
def anvill_decomp_main(args, source_path, dest_path):

    sources_decompile = list(source_path.rglob("*.json"))
    if sources_decompile:
        workdir_decompile = str(dest_path.joinpath("work"))
        log.debug(f"Making work dir [{workdir_decompile}]")
        os.makedirs(workdir_decompile, exist_ok=True)
    log.info(f"Found {len(sources_decompile)} JSON specs")

    num_cpus = os.cpu_count()
    anvill_stats = Stats()

    if args.test_options:
        with open(args.test_options, "r") as rf:
            anvill_stats.load_rules(rf)

    anvill_stats.set_stat("start_time", str(datetime.now()))

    max_items_decompile = len(sources_decompile)

    apply_anvill_decomp = partial(run_anvill_decompile, args.anvill_decompile, dest_path, args.only_fails, source_path_decompile, anvill_stats)

    with ThreadPool(num_cpus) as p:
        with tqdm(total=max_items_decompile) as pbar:
            for _ in p.imap_unordered(apply_anvill_decomp, enumerate(sources_decompile)):
                pbar.update()

    anvill_stats.set_stat("end_time", str(datetime.now()))

    if args.dump_stats:
        outpath = dest_path.joinpath("stats.json")
        anvill_stats.save_json(outpath)

    if args.slack_notify:
        dump_via_slack(args, anvill_stats)
예제 #10
0
def anvill_python_main(args, source_path, dest_path):
    num_cpus = os.cpu_count()
    anvill_stats = Stats()

    if args.test_options:
        with open(args.test_options, "r") as rf:
            anvill_stats.load_rules(rf)

    # get all the bitcode
    log.info(f"Listing files in {str(source_path)}")
    sources = list(source_path.rglob("*.elf"))
    log.info(f"Found {len(sources)} ELF files")

    # load test to ignore
    anvill_stats.set_stat("start_time", str(datetime.now()))

    max_items_python = len(sources)

    # workspace for anvill-python
    apply_anvill_python = partial(run_anvill_python, args.anvill_python, dest_path, args.only_fails, source_path, anvill_stats)

    with ThreadPool(num_cpus) as p:
        with tqdm(total=max_items_python) as pbar:
            for _ in p.imap_unordered(apply_anvill_python, enumerate(sources)):
                pbar.update()

    anvill_stats.set_stat("end_time", str(datetime.now()))

    if args.dump_stats:
        outpath = dest_path.joinpath("stats.json")
        anvill_stats.save_json(outpath)

    if args.slack_notify:
        dump_via_slack(args, anvill_stats)
예제 #11
0
파일: aco.py 프로젝트: bernardoabreu/CN
    def run(self):
        self.distances = self.__build_distance_matrix(self.points)
        self.heur_values = self.__density()
        self.stats = Stats(np.sum(self.distances))

        self.__build_pheromone_vector()

        sol_dist = np.empty(self.num_ants)
        sol_medians = np.empty((self.num_ants, self.num_medians), dtype=int)

        for i in range(self.iterations):
            for j in range(self.num_ants):
                solution_matrix, medians = self.build_solution()
                sol_dist[j] = self.eval(solution_matrix)
                sol_medians[j] = medians

            self.stats.add_solution(sol_dist, sol_medians)

            local_best = self.stats.get_local_best()
            local_worst = self.stats.get_local_worst()
            global_best = self.stats.get_global_best()
            self.update_pheromone(local_best, local_worst, global_best)

            print('Iteration ' + str(i + 1))
            self.stats.print_stats()
            self.stats.record_data()

        if self.outfile:
            self.stats.dump_to_file(self.outfile)

        return global_best[0]
예제 #12
0
 def get_stats(self, itr=0):
     self.stats = Stats()  # Clean stats
     self.set_iteration(itr)
     self.read_meminfo()
     self.read_slabinfo()
     self.read_cpuinfo()
     return self.stats
예제 #13
0
 def __init__(self):
     # initializes game session and builds game resourses
     pygame.init()
     self.settings = Settings()
     # storing game statistics
     self.stats = Stats(self)
     self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
     self.screen_rect = self.screen.get_rect()
     self.settings.screen_width = self.screen.get_rect().width
     self.settings.screen_height = self.screen.get_rect().height
     pygame.display.set_caption("Warplanes")
     self.bg_color = self.settings.bg_colour
     self.hp = self.settings.enemy_hp
     self.junkers = Junkers(self)
     self.shots = pygame.sprite.Group()
     self.enemy_shots = pygame.sprite.Group()
     self.enemies = pygame.sprite.Group()
     # game scoreboard
     self.sb = Scoreboard(self)
     self.play_button = Button(self, "START", (0, -100))
     self.info_button = Button(self, "INFO", (0, 100))
     self.pause_button = Button(self, "Continue")
     self._create_sky()
     self.info = Info(self)
     pygame.mixer.music.load('music.wav')
     self.shot_sound = pygame.mixer.Sound('shot.ogg')
     self.explosion_sound = pygame.mixer.Sound('explosion.ogg')
예제 #14
0
파일: races.py 프로젝트: Merylpa/NachoRPG
class Race(metaclass=utilities.StrMeta):
    starting_stats = Stats(0, 0, 0, 0)

    def __init__(self, str, agi, int, con):
        if not self.starting_stats.validStart():
            raise InvalidStartingStats("Unbalanced starting stats: %d" %
                                       self.starting_stats.sum())
예제 #15
0
    def bundle_func(self, dir_list):
        '''
            Function called in parallel_bundler() which gives it an array containing
            src_path and dest_path
            Generates json object and captures stats of each process

            Arguments:
                dir_list           -- Array containing src_path and dest_path

            Returns:
                bundled_file_data  -- Json object of archive file
                stat               -- Stat object of the process
        '''
        stat = Stats()
        start = time.time()
        proc_name = multiprocessing.current_process().name

        cmd, elapsed_proc_time, tar_path = Bundler.bundle_file_set(dir_list[0], dir_list[1])

        end = time.time()
        elapsed = end - start

        tar_size = Bundler.get_bundle_size(tar_path)

        bundled_file_data = {}

        stat.capture_stats(elapsed_proc_time, tar_size, 0, tar_path, proc_name, cmd, "", end)

        return  bundled_file_data, stat, tar_path
예제 #16
0
파일: main.py 프로젝트: Anonark/kcauto
    def __init__(self, config):
        """Initializes the primary kcauto instance with the passed in
        Config instance; creates the Stats instance and resets scheduled sleep
        timers.

        Args:
            config (Config): kcauto Config instance
        """
        self.kc_region = None
        self.config = config
        self.stats = Stats(self.config)
        self.scheduler = Scheduler(self.config, self.stats)
        self.modules = {
            'resupply': None,
            'pvp': None,
            'combat': None,
            'repair': None,
            'ship_switcher': None,
            'fleet_switcher': None,
            'expedition': None,
            'quest': None
        }
        self.print_stats_check = True
        self.paused = False
        self.regions = {}
        self.active_fleets = {}
        self.combat_fleets = {}
        self.expedition_fleets = {}
        self.combat_cycle = False
예제 #17
0
def start_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))

    pygame.display.set_caption("Alien Attack")

    play_button = Button(settings, screen, "Play")

    stats = Stats(settings)
    sb = ScoreBoard(settings, screen, stats)

    ship = Ship(settings, screen)
    bullets = Group()
    aliens = Group()

    gf.create_fleet(settings, screen, ship, aliens)

    while True:
        gf.check_events(settings, screen, stats, sb, play_button, ship, aliens,
                        bullets)

        if stats.game_active:
            update_elements(settings, screen, stats, sb, ship, aliens, bullets)

        gf.update_screen(settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
예제 #18
0
    def get_stats(self):
        """Retrieves statistics about the queue"""
        href = proc_template(self._conn.stats_href, queue_name=self._name)

        hdrs, body = self._conn._perform_http(href=href, method='GET')

        return Stats(body)
    def _cumulative_stats(self, lineup: Lineup):
        """
        Calculates an approximation of the final statistics of this lineup, assuming
        ideal management (setting lineups daily, etc.)
        :param Lineup lineup: the lineup to examine and use to calculate stats
        :return Stats: the accumulated, year-end total stats
        """
        total_stats = Stats({}, BaseballStat)
        for p in lineup.starters():
            total_stats += self._get_projection(p.name) or Stats({},
                                                                 BaseballStat)
        for p in lineup.benched():
            total_stats += self._get_projection(p.name) or Stats(
                {}, BaseballStat) * self.likelihood(p, lineup)

        return total_stats