Example #1
0
def mock_playoffGame():

    # Gera uma string com letras e numeros de tamanho 10
    winner = "".join(random_choices(ascii_uppercase + digits, k=10))
    loser = "".join(random_choices(ascii_uppercase + digits, k=10))
    score_winner = randint(100, 999)
    score_loser = randint(1, 99)
    date = datetime.now()
    game_number = randint(1, 7)
    return PlayoffGame(winner, loser, score_winner, score_loser, date,
                       game_number)
Example #2
0
    def generate_random_password(
        self,
        length=16,
        alphabet_lower=True,
        alphabet_upper=True,
        number=True,
        symbol=True,
    ):
        if alphabet_lower is alphabet_upper is number is symbol is False:
            print(alphabet_lower)
            print(alphabet_upper)
            print(number)
            print(symbol)
            raise Exception("One of the password options must not be false")

        allowed_characters = []
        if alphabet_lower:
            allowed_characters.extend(
                self.allowed_characters.get("alphabets_lower"))
        if alphabet_upper:
            allowed_characters.extend(
                self.allowed_characters.get("alphabets_upper"))
        if number:
            allowed_characters.extend(self.allowed_characters.get("numbers"))
        if symbol:
            allowed_characters.extend(self.allowed_characters.get("symbols"))

        return "".join(random_choices(population=allowed_characters, k=length))
Example #3
0
 async def handle_several_ranges(
     self,
     send_header_only: bool,
     file_size: int,
     scope: Scope,
     send: Send,
     ranges: Sequence[Tuple[int, int]],
 ) -> None:
     boundary = "".join(
         random_choices("abcdefghijklmnopqrstuvwxyz0123456789", k=13))
     self.headers[
         "content-type"] = f"multipart/byteranges; boundary={boundary}"
     content_length, generate_headers = self.generate_multipart(
         ranges, boundary, file_size, self.content_type)
     self.headers["content-length"] = str(content_length)
     await send_http_start(send, 206, self.list_headers(as_bytes=True))
     if send_header_only:
         return await send_http_body(send)
     sendfile = self.create_send_or_zerocopy(scope, send)
     file_descriptor = await open_for_sendfile(self.filepath)
     try:
         for start, end in ranges:
             await send_http_body(send,
                                  generate_headers(start, end),
                                  more_body=True)
             await sendfile(file_descriptor, start, end - start, True)
             await send_http_body(send, b"\n", more_body=True)
         return await send_http_body(send,
                                     f"--{boundary}--\n".encode("ascii"))
     finally:
         await run_in_threadpool(os.close, file_descriptor)
Example #4
0
    def handle_several_ranges(
        self,
        send_header_only: bool,
        file_size: int,
        start_response: StartResponse,
        ranges: Sequence[Tuple[int, int]],
    ) -> Generator[bytes, None, None]:
        boundary = "".join(
            random_choices("abcdefghijklmnopqrstuvwxyz0123456789", k=13))
        self.headers[
            "content-type"] = f"multipart/byteranges; boundary={boundary}"
        content_length, generate_headers = self.generate_multipart(
            ranges, boundary, file_size, self.content_type)
        self.headers["content-length"] = str(content_length)

        start_response(StatusStringMapping[206],
                       self.list_headers(as_bytes=False))
        if send_header_only:
            yield b""
            return

        with open(self.filepath, "rb") as file:
            for start, end in ranges:
                file.seek(start)
                yield generate_headers(start, end)
                for here in range(start, end, self.chunk_size):
                    yield file.read(min(self.chunk_size, end - here))
                yield b"\n"
            yield f"--{boundary}--\n".encode("ascii")
Example #5
0
def mock_series():
    games = []
    for i in range(1, 6):
        games.append(mock_playoffGame())

    def fix_names(game, winner, loser):
        game.winner = winner
        game.loser = loser
        return game

    # Set the name of all the teams equal for all games
    list(
        map(
            fix_names,
            games,
            [games[0].winner] * len(games),
            [games[0].loser] * len(games),
        ))
    # Invert the winner of the first game
    list(map(fix_names, games, [games[0].loser], [games[0].winner]))

    series_name = "".join(random_choices(ascii_uppercase + digits, k=10))
    return PlayoffSeries(
        series_name,
        winner=games[-1].winner,
        loser=games[-1].loser,
        games=games,
        best_of_series=7,
    )
def bytes_to_image(data: bytearray) -> Image:
    """Convert a bytes object into a PIL Image with RGB format

    This function takes a bytes object and builds an RGB image by assigning a
    byte to a color band of a single pixel: Every 3 bytes of data form a single
    pixel in the image.

    In order to create a (more or less) compact image, the data is rear-padded
    with bytes sampled from the same data, seamlessly merging with the possible
    created colors. This allows for the image to maintain a squared shape and
    make it easier to visualize. So as to keep track of the padded bytes, a
    certain amount of bytes are added to the beginning of the data. The value
    obtained from these bytes indicate how many bytes were added at the end of
    the input data, making it possible to crop accurately when trying to decode.

    The amount of bytes that contain the number of padded bytes is defined at
    the top of this file.

    :param data: The byte array object to convert.
    :return: A PIL.Image with RGB format.
    """
    # Obtain squared dimensions
    short_side, long_side = get_min_image_size(data)
    # Calculate necessary padding bytes
    pad_count = short_side * long_side * 3 - len(data) - padding_info_bytes

    # N bytes of padding at most
    if pad_count > 2 ** (8 * padding_info_bytes) - 1:
        raise ValueError("Text is too long to be encoded in an image")

    # Create padding bytes from sample
    padding = bytearray()
    for byte in random_choices(data, k=pad_count):
        padding.append(byte)

    # Add padding info in front of padded data
    padding_info = bytearray()
    # Split padding into N bytes
    for i in range(padding_info_bytes):
        padding_info.append(pad_count & 255)
        pad_count = pad_count >> 8
    # Decreasing signifiance
    padding_info.reverse()

    # Merge byte arrays
    data = padding_info + data + padding

    image = Image.frombytes("RGB", (short_side, long_side), bytes(data))
    return image
Example #7
0
    def process(self, time_passed):
        # record time passed for states to use.
        self.time_passed = time_passed

        Character.process(self, time_passed)

        level_up_stats_weighted = [
            ("ranged cooldown", 0.6),
            ("projectile range", 0.1),
            ("heal cooldown", 0.1),
            ("speed", 0.2),
        ]
        if self.can_level_up():
            upgrade_stat = random_choices(
                population=[s[0] for s in level_up_stats_weighted],
                weights=[s[1] for s in level_up_stats_weighted],
                k=1,
            )[0]
            self.level_up(upgrade_stat)
            if upgrade_stat == "projectile range":
                self.min_target_distance = self.projectile_range
Example #8
0
def thermal_chooser(queue,
                    remaining,
                    nbranch=8,
                    temperature=1,
                    rel_temperature=True):
    """A contraction 'chooser' that weights possible contractions using a
    Boltzmann distribution. Explicitly, given costs `c_i` (with `c_0` the
    smallest), the relative weights, `w_i`, are computed as:

        $$w_i = exp( -(c_i - c_0) / temperature)$$

    Additionally, if `rel_temperature` is set, scale `temperature` by
    `abs(c_0)` to account for likely fluctuating cost magnitudes during the
    course of a contraction.

    **Parameters:**

    - **queue** - *(list)* The heapified list of candidate contractions.
    - **remaining** - *(dict[str, int])* Mapping of remaining inputs' indices to the ssa id.
    - **temperature** - *(float, optional)* When choosing a possible contraction, its relative probability will be
        proportional to `exp(-cost / temperature)`. Thus the larger
        `temperature` is, the further random paths will stray from the normal
        'greedy' path. Conversely, if set to zero, only paths with exactly the
        same cost as the best at each step will be explored.
    - **rel_temperature** - *(bool, optional)* Whether to normalize the `temperature` at each step to the scale of
        the best cost. This is generally beneficial as the magnitude of costs
        can vary significantly throughout a contraction.
    - **nbranch** - *(int, optional)* How many potential paths to calculate probability for and choose from at each step.

    **Returns:**

    - **cost**
    - **k1**
    - **k2**
    - **k3**
    """
    n = 0
    choices = []
    while queue and n < nbranch:
        cost, k1, k2, k12 = heapq.heappop(queue)
        if k1 not in remaining or k2 not in remaining:
            continue  # candidate is obsolete
        choices.append((cost, k1, k2, k12))
        n += 1

    if n == 0:
        return None
    if n == 1:
        return choices[0]

    costs = [choice[0][0] for choice in choices]
    cmin = costs[0]

    # adjust by the overall scale to account for fluctuating absolute costs
    if rel_temperature:
        temperature *= max(1, abs(cmin))

    # compute relative probability for each potential contraction
    if temperature == 0.0:
        energies = [1 if c == cmin else 0 for c in costs]
    else:
        # shift by cmin for numerical reasons
        energies = [math.exp(-(c - cmin) / temperature) for c in costs]

    # randomly choose a contraction based on energies
    (chosen, ) = random_choices(range(n), weights=energies)
    cost, k1, k2, k12 = choices.pop(chosen)

    # put the other choice back in the heap
    for other in choices:
        heapq.heappush(queue, other)

    return cost, k1, k2, k12