Python random.html() Examples

The following are 8 code examples of random.html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: distributions.py    From Neuraxle with Apache License 2.0 6 votes vote down vote up
def __init__(self, min_included: float, max_included: float, null_default_value=None):
        """
        Create a random uniform distribution.
        A random float between the two values somehow inclusively will be returned.

        :param min_included: minimum integer, included.
        :type min_included: float
        :param max_included: maximum integer, might be included - for more info, see `examples <https://docs.python.org/2/library/random.html#random.uniform>`__
        :type max_included: float
        :param null_default_value: null default value for distribution. if None, take the min_included
        :type null_default_value: int
        """
        if null_default_value is None:
            HyperparameterDistribution.__init__(self, min_included)
        else:
            HyperparameterDistribution.__init__(self, null_default_value)

        self.min_included: float = min_included
        self.max_included: float = max_included 
Example #2
Source File: token.py    From asymmetric-jwt-auth with ISC License 5 votes vote down vote up
def sign(username, private_key, generate_nonce=None, iat=None, algorithm=DEFAULT_ALGORITHM):
    """
    Create a signed JWT using the given username and RSA private key.

    :param username: Username (string) to authenticate as on the remote system.
    :param private_key: Private key to use to sign the JWT claim.
    :param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
        `random.random <https://docs.python.org/3/library/random.html#random.random>`_.
    :param iat: Optional. Timestamp to include in the JWT claim. Defaults to
        `time.time <https://docs.python.org/3/library/time.html#time.time>`_.
    :param algorithm: Optional. Algorithm to use to sign the JWT claim. Default to ``RS512``.
        See `pyjwt.readthedocs.io <https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_ for other possible algorithms.
    :return: JWT claim as a string.
    """
    iat = iat if iat else time.time()
    if not generate_nonce:
        generate_nonce = lambda username, iat: random.random()  # NOQA

    token_data = {
        'username': username,
        'time': iat,
        'nonce': generate_nonce(username, iat),
    }

    token = jwt.encode(token_data, private_key, algorithm=algorithm)
    return token 
Example #3
Source File: sticklet_un.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def get_font_file(client, channel_id):
    # first get the font messages
    font_file_message_s = await client.get_messages(
        entity=channel_id,
        filter=InputMessagesFilterDocument,
        # this might cause FLOOD WAIT,
        # if used too many times
        limit=None
    )
    # get a random font from the list of fonts
    # https://docs.python.org/3/library/random.html#random.choice
    font_file_message = random.choice(font_file_message_s)
    # download and return the file path
    return await client.download_media(font_file_message) 
Example #4
Source File: secret_key.py    From avos with Apache License 2.0 5 votes vote down vote up
def generate_key(key_length=64):
    """Secret key generator.

    The quality of randomness depends on operating system support,
    see http://docs.python.org/library/random.html#random.SystemRandom.
    """
    if hasattr(random, 'SystemRandom'):
        choice = random.SystemRandom().choice
    else:
        choice = random.choice
    return ''.join(map(lambda x: choice(string.digits + string.ascii_letters),
                   range(key_length))) 
Example #5
Source File: util.py    From core with MIT License 5 votes vote down vote up
def create_nonce():
    x = len(NONCE_CHARS)

    # Class that uses the os.urandom() function for generating random numbers.
    # https://docs.python.org/2/library/random.html#random.SystemRandom
    randrange = random.SystemRandom().randrange

    return ''.join([NONCE_CHARS[randrange(x)] for _ in range(NONCE_LENGTH)]) 
Example #6
Source File: config_transform_standalone.py    From OpenBookQA with Apache License 2.0 4 votes vote down vote up
def get_random_value(config: Dict[Any, Any]):
    """
    Executes function from https://docs.python.org/3/library/random.html
    :param config: Config that contains type "get_random_value" with 'func' and 'args'
    :return:
    """
    config_dict = config
    if config_dict["type"] != "random":
        raise ValueError("Config with type {0} is not valid for this function".format(config_dict["type"]))

    func_str = config_dict["func"]
    func_args = dict(config_dict["args"])

    return_first = False
    if func_str.endswith("[0]"):
        return_first = True
        func_str = func_str[:-3]

    allowed_funcs = {
        "random.randint": random.randint,
        "randint": random.randint,
        "random.uniform": random.uniform,
        "uniform": random.uniform,
        "random.randrange": random.randrange,
        "randrange": random.randrange,
        "random.shuffle": random.shuffle,
        "shuffle": random.shuffle,
        "random.choice": random.choice,
        "choice": random.choice,
        "random.choices": random.choices,
        "choices": random.choices,
    }

    if not func_str in allowed_funcs:
        raise ValueError("Wrong function type {0}. The following types are allowed: {1}".format(func_str, ", ".join(sorted(allowed_funcs.keys()))))

    func = allowed_funcs[func_str]

    result_value = func(**func_args)
    if return_first:
        result_value = result_value[0]

    return result_value 
Example #7
Source File: sticklet_un.py    From BotHub with Apache License 2.0 4 votes vote down vote up
def sticklet(event):
    R = random.randint(0,256)
    G = random.randint(0,256)
    B = random.randint(0,256)

    # get the input text
    # the text on which we would like to do the magic on
    sticktext = event.pattern_match.group(1)

    # delete the userbot command,
    # i don't know why this is required
    await event.delete()

    # https://docs.python.org/3/library/textwrap.html#textwrap.wrap
    sticktext = textwrap.wrap(sticktext, width=10)
    # converts back the list to a string
    sticktext = '\n'.join(sticktext)

    image = Image.new("RGBA", (512, 512), (255, 255, 255, 0))
    draw = ImageDraw.Draw(image)
    fontsize = 230

    FONT_FILE = await get_font_file(event.client, "@FontRes")

    font = ImageFont.truetype(FONT_FILE, size=fontsize)

    while draw.multiline_textsize(sticktext, font=font) > (512, 512):
        fontsize -= 3
        font = ImageFont.truetype(FONT_FILE, size=fontsize)

    width, height = draw.multiline_textsize(sticktext, font=font)
    draw.multiline_text(((512-width)/2,(512-height)/2), sticktext, font=font, fill=(R, G, B))

    image_stream = io.BytesIO()
    image_stream.name = "@UniBorg.webp"
    image.save(image_stream, "WebP")
    image_stream.seek(0)

    # finally, reply the sticker
    #await event.reply( file=image_stream, reply_to=event.message.reply_to_msg_id)
    #replacing upper line with this to get reply tags

    await event.client.send_file(event.chat_id, image_stream, reply_to=event.message.reply_to_msg_id)
    # cleanup
    try:
        os.remove(FONT_FILE)
    except:
        pass 
Example #8
Source File: util.py    From core with MIT License 4 votes vote down vote up
def parse_range_header(range_header_val, valid_units=('bytes',)):
    """
    Range header parser according to RFC7233

    https://tools.ietf.org/html/rfc7233
    """

    split_range_header_val = range_header_val.split('=')
    if not len(split_range_header_val) == 2:
        raise RangeHeaderParseError('Invalid range header syntax')

    unit, ranges_str = split_range_header_val

    if unit not in valid_units:
        raise RangeHeaderParseError('Invalid unit specified')

    split_ranges_str = ranges_str.split(', ')

    ranges = []

    for range_str in split_ranges_str:
        re_match = BYTE_RANGE_RE.match(range_str)
        first, last = None, None

        if re_match:
            first, last = re_match.groups()
        else:
            re_match = SUFFIX_BYTE_RANGE_RE.match(range_str)
            if re_match:
                first = re_match.group('first')
            else:
                raise RangeHeaderParseError('Invalid range format')

        if first is not None:
            first = int(first)


        if last is not None:
            last = int(last)

        if last is not None and first > last:
            raise RangeHeaderParseError('Invalid range, first %s can\'t be greater than the last %s' % (unit, unit))

        ranges.append((first, last))

    return ranges