Python random.Random() Examples

The following are code examples for showing how to use random.Random(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: sharedbuffers   Author: jampp   File: mapped_struct.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def gen_values(self, n, reversed = False, shuffled = False, gen_dupes = False):
        if reversed:
            keys = xrange(n-1,-1,-1)
        else:
            keys = xrange(n)
        if shuffled:
            keys = list(keys)
            r = random.Random(1234827)
            r.shuffle(keys)
        if gen_dupes:
            return itertools.chain(
                itertools.izip(keys, xrange(0, 2*n, 2)),
                itertools.islice(itertools.izip(keys, xrange(0, 2*n, 2)), 10, None),
            )
        else:
            return itertools.izip(keys, xrange(0, 2*n, 2)) 
Example 2
Project: CyberScan   Author: medbenali   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 3
Project: hostapd-mana   Author: adde88   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 4
Project: jarvis   Author: anqxyr   File: scp.py    (license) View Source Project 6 votes vote down vote up
def show_page(page, rating=True):
    attribution = page.build_attribution_string(
        templates=dict(
            author='written {hdate} by {user}',
            rewrite='rewritten {hdate} by {user}',
            translator='translated {hdate} by {user}',
            maintainer='maintained {hdate} by {user}'),
        group_templates=dict(
            author='co-written {hdate} by {users} and {last_user}',
            rewrite='rewritten {hdate} by {users} and {last_user}',
            translator='translated {hdate} by {users} and {last_user}',
            maintainer='maintained {hdate} by {users} and {last_user}'))
    out = lex.page_lookup.summary if rating else lex.page_lookup.nr_summary
    if page.name == 'scp-1848':
        r = rand.Random(int(arrow.now().format('YYYYMMDDHH')))
        rating = r.randrange(-160, -140)
    else:
        rating = page.rating
    return out(page=page, rating=rating, attribution=attribution) 
Example 5
Project: GAMADV-XTD   Author: taers232c   File: utils.py    (license) View Source Project 6 votes vote down vote up
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
    """
    decorator run test method w/ multiple fixed seeds.
    """
    def builder(func):
        @wraps(func)
        def wrapper(*args, **kwds):
            rng = random.Random(master_seed)
            for _ in irange(count):
                kwds['seed'] = rng.getrandbits(32)
                func(*args, **kwds)
        return wrapper
    return builder

#=============================================================================
# custom test harness
#============================================================================= 
Example 6
Project: GAMADV-XTD   Author: taers232c   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def getrandbytes(rng, count):
    """return byte-string containing *count* number of randomly generated bytes, using specified rng"""
    # NOTE: would be nice if this was present in stdlib Random class

    ###just in case rng provides this...
    ##meth = getattr(rng, "getrandbytes", None)
    ##if meth:
    ##    return meth(count)

    if not count:
        return _BEMPTY
    def helper():
        # XXX: break into chunks for large number of bits?
        value = rng.getrandbits(count<<3)
        i = 0
        while i < count:
            yield value & 0xff
            value >>= 3
            i += 1
    return join_byte_values(helper()) 
Example 7
Project: jack   Author: uclmr   File: batch.py    (license) View Source Project 6 votes vote down vote up
def shuffle_and_batch(items: List[T], batch_size: int,
                      rng: Optional[random.Random] = None) \
        -> Iterator[List[T]]:
    """Optionally shuffles and batches items in a list.

    Args:
        - items: List of items to shuffle & batch.
        - batch_size: size of batches.
        - rng: random number generator if items should be shuffles, else None.

    Returns: Batch iterator
    """

    todo = list(range(len(items)))
    if rng is not None:
        rng.shuffle(todo)
    while todo:
        indices = todo[:batch_size]
        todo = todo[batch_size:]
        items_batch = [items[i] for i in indices]
        yield items_batch 
Example 8
Project: CVE-2016-6366   Author: RiskSense-Ops   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 9
Project: deep_stack   Author: lyn716   File: utils.py    (license) View Source Project 6 votes vote down vote up
def random_str(randomlength=8,
               just_number=False):
    """????????????

    :param      randomlength: ?????????
    :param      just_number: ?????
    :return:
    """

    string = ""

    if just_number:
        chars = '0123456789'
    else:
        chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'

    length = len(chars) - 1
    random = Random()

    for i in range(randomlength):
        string += chars[random.randint(0, length)]

    return string 
Example 10
Project: NLP   Author: Deamon5550   File: generate_test_splits.py    (license) View Source Project 6 votes vote down vote up
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids])) 
Example 11
Project: SFBIStats   Author: royludo   File: lexical_analysis.py    (license) View Source Project 6 votes vote down vote up
def my_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    """
    custom colors for wordcloud, derived from wordcloud source

    Parameters
    ----------
    word
    font_size
    position
    orientation
    font_path
    random_state

    Returns
    -------

    """

    if random_state is None:
        random_state = Random()
    return "hsl(%d, 70%%, 40%%)" % random_state.randint(0, 255) 
Example 12
Project: sidekick   Author: fabiommendes   File: test_lib_sequences.py    (license) View Source Project 6 votes vote down vote up
def test_random_sample(self):
        alist = list(range(100))

        assert list(
            random_sample(1, alist, random_state=2016)) == alist

        mk_rsample = lambda rs=1: \
            list(random_sample(0.1, alist, random_state=rs))
        rsample1 = mk_rsample()
        assert rsample1 == mk_rsample()

        rsample2 = mk_rsample(1984)
        randobj = Random(1984)
        assert rsample2 == mk_rsample(randobj)

        assert rsample1 != rsample2

        assert mk_rsample(object) == mk_rsample(object)
        assert mk_rsample(object) != mk_rsample(object())
        assert mk_rsample(b"a") == mk_rsample(u"a")

        assert raises(TypeError, lambda: mk_rsample([])) 
Example 13
Project: hakkuframework   Author: 4shadoww   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)//2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 14
Project: hnmt   Author: robertostling   File: largetext.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, f, block_size=0x40000, max_blocks=512,
                 encoding='utf-8', seed=123):
        assert 'b' in f.mode
        self.random = Random(seed)
        self.block_size = block_size
        self.max_blocks = max_blocks
        self.lines = None
        self.f = f
        self.encoding = encoding

        f.seek(0, 2)
        file_size = f.tell()
        f.seek(0, 0)

        if file_size <= block_size*max_blocks:
            # For sufficiently small files, read the whole one into RAM
            self.lines = [str(line.rstrip(b'\n'), encoding) for line in f]
            shuffle(self.lines, self.random.random)
        else:
            # For large files, only store a list of block offsets
            self.offsets = list(range(0, file_size, block_size)) 
Example 15
Project: fnc-1-baseline   Author: FakeNewsChallenge   File: generate_test_splits.py    (license) View Source Project 6 votes vote down vote up
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids])) 
Example 16
Project: uci-statnlp   Author: sameersingh   File: data.py    (license) View Source Project 6 votes vote down vote up
def file_splitter(filename, seed = 0, train_prop = 0.7, dev_prop = 0.15,
    test_prop = 0.15):
    """Splits the lines of a file into 3 output files."""
    import random
    rnd = random.Random(seed)
    basename = filename[:-4]
    train_file = open(basename + ".train.txt", "w")
    test_file = open(basename + ".test.txt", "w")
    dev_file = open(basename + ".dev.txt", "w")
    with open(filename, 'r') as f:
        for l in f.readlines():
            p = rnd.random()
            if p < train_prop:
                train_file.write(l)
            elif p < train_prop + dev_prop:
                dev_file.write(l)
            else:
                test_file.write(l)
    train_file.close()
    test_file.close()
    dev_file.close() 
Example 17
Project: uci-statnlp   Author: sameersingh   File: data.py    (license) View Source Project 6 votes vote down vote up
def file_splitter(all_file, train_file, dev_file):
    """Splits the labeled data into train and dev, sentence-wise."""
    import random
    all_sents, all_labels = read_file(all_file)
    train_f = open(train_file, "w")
    dev_f = open(dev_file, "w")
    seed = 0
    dev_prop = 0.25
    rnd = random.Random(seed)
    for i in xrange(len(all_sents)):
        if rnd.random() < dev_prop:
            write_sent(dev_f, all_sents[i], all_labels[i])
        else:
            write_sent(train_f, all_sents[i], all_labels[i])
    train_f.close()
    dev_f.close() 
Example 18
Project: DeepLearn   Author: GauravBh1010tt   File: generate_test_splits.py    (license) View Source Project 6 votes vote down vote up
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids])) 
Example 19
Project: zippy   Author: securesystemslab   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in range(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) 
Example 20
Project: DecInt   Author: casevh   File: DecInt.py    (license) View Source Project 6 votes vote down vote up
def Random(self, randlength):
        '''Return a random integer with randlength digits.

        The actual number of digits may be less than randlength because
        leading zeroes are stripped from the result.'''

        result = DecInt()
        result.radix = self.radix
        result.sign = 1
        result.terms = []
        power, base = self.radix

        full, partial = divmod(randlength, power)
        for i in range(full):
            result.terms.append(mp(_rr.randrange(long(Radix2Value(self.radix)))))
        result.terms.append(mp(_rr.randrange(long(Radix2Value((partial, base))))))
        while len(result.terms) > 1 and result.terms[-1] == ZERO:
            result.terms.pop()
        return result 
Example 21
Project: sockeye   Author: awslabs   File: common.py    (license) View Source Project 6 votes vote down vote up
def generate_digits_file(source_path: str,
                         target_path: str,
                         line_count: int = 100,
                         line_length: int = 9,
                         sort_target: bool = False,
                         line_count_empty: int = 0,
                         seed=13):
    assert line_count_empty <= line_count
    random_gen = random.Random(seed)
    with open(source_path, "w") as source_out, open(target_path, "w") as target_out:
        all_digits = []
        for _ in range(line_count - line_count_empty):
            digits = [random_gen.choice(_DIGITS) for _ in range(random_gen.randint(1, line_length))]
            all_digits.append(digits)
        for _ in range(line_count_empty):
            all_digits.append([])
        random_gen.shuffle(all_digits)
        for digits in all_digits:
            print(" ".join(digits), file=source_out)
            if sort_target:
                digits.sort()
            print(" ".join(digits), file=target_out) 
Example 22
Project: trex-http-proxy   Author: alwye   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 23
Project: trex-http-proxy   Author: alwye   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)//2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 24
Project: Price-Comparator   Author: Thejas-1   File: hmm.py    (license) View Source Project 6 votes vote down vote up
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    print()
    print("Baum-Welch demo for market example")
    print()

    model, states, symbols = _market_hmm_example()

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    rng.seed(0)
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model,
                                     max_iterations=1000) 
Example 25
Project: kitty   Author: cisco-sas   File: staged_sequence.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, name, selection_strategy='1', seed=None):
        '''
        :param name: name of the Stage
        :param selection_strategy: strategy for selecting amount of template in each mutation
        :param seed: RNG seed (default: None)
        '''
        super(Stage, self).__init__('Stage[%s]' % name)
        self._templates = []
        self._strategy = selection_strategy
        self._min_sequence = None
        self._max_sequence = None
        self._r = random.Random()
        self._seed = seed
        if seed:
            self._r.seed(seed)
        self._current_sequence_templates = None
        self._default_sequence_templates = None
        self._ready = False
        self._validate_strategy(selection_strategy) 
Example 26
Project: oil   Author: oilshell   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in xrange(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) 
Example 27
Project: oil   Author: oilshell   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected) 
Example 28
Project: python2-tracer   Author: extremecoders-re   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in xrange(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) 
Example 29
Project: python2-tracer   Author: extremecoders-re   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected) 
Example 30
Project: scapy-bpf   Author: guedou   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 31
Project: sslstrip-hsts-openwrt   Author: adde88   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 32
Project: scapy-radio   Author: BastilleResearch   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 33
Project: Callandtext   Author: iaora   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def getrandbytes(rng, count):
    """return byte-string containing *count* number of randomly generated bytes, using specified rng"""
    # NOTE: would be nice if this was present in stdlib Random class

    ###just in case rng provides this...
    ##meth = getattr(rng, "getrandbytes", None)
    ##if meth:
    ##    return meth(count)

    if not count:
        return _BEMPTY
    def helper():
        # XXX: break into chunks for large number of bits?
        value = rng.getrandbits(count<<3)
        i = 0
        while i < count:
            yield value & 0xff
            value >>= 3
            i += 1
    return join_byte_values(helper()) 
Example 34
Project: isf   Author: w3h   File: volatile.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1
    
        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0 
Example 35
Project: isf   Author: w3h   File: staged_sequence.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, name, selection_strategy='1', seed=None):
        '''
        :param name: name of the Stage
        :param selection_strategy: strategy for selecting amount of template in each mutation
        :param seed: RNG seed (default: None)
        '''
        super(Stage, self).__init__('Stage[%s]' % name)
        self._templates = []
        self._strategy = selection_strategy
        self._min_sequence = None
        self._max_sequence = None
        self._r = random.Random()
        self._seed = seed
        if seed:
            self._r.seed(seed)
        self._current_sequence_templates = None
        self._default_sequence_templates = None
        self._ready = False
        self._validate_strategy(selection_strategy) 
Example 36
Project: isf   Author: w3h   File: usb_hid.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, name=None, fuzzable=True):
        namer = NameGen()
        fields = []
        r = Random()
        for tag in opcodes:
            for i in range(4):
                opcode = tag | i
                current = chr(opcode)
                for j in range(i):
                    current += chr(r.randint(0, 255))
                fields.append(Static(name=namer.gen(opcode), value=current))
        super(RandomHidReport, self).__init__(
            fields=fields,
            min_elements=10,
            max_elements=40,
            fuzzable=fuzzable,
            name=name
        ) 
Example 37
Project: web_ctp   Author: molebot   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in range(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) 
Example 38
Project: web_ctp   Author: molebot   File: test_random.py    (license) View Source Project 6 votes vote down vote up
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                #(g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected) 
Example 39
Project: litevideo   Author: enjoy-digital   File: ycbcr422to444_tb.py    (license) View Source Project 6 votes vote down vote up
def sink_generator(sink, rand_threshold=100):
    prng = random.Random(42)
    for i in range(len(sink_cb_cr)):
        valid = 0
        while True:
            valid = (prng.randrange(100) < rand_threshold)
            if valid:
                yield sink.valid.eq(1)
                yield sink.y.eq(sink_y[i])
                yield sink.cb_cr.eq(sink_cb_cr[i])
                yield
                while not (yield sink.ready):
                    yield
                yield sink.valid.eq(0)
                break
            else:
                yield sink.valid.eq(0)
                yield
    # yield for processing latency
    for i in range(128):
        yield 
Example 40
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: hmm.py    (license) View Source Project 6 votes vote down vote up
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    print()
    print("Baum-Welch demo for market example")
    print()

    model, states, symbols = _market_hmm_example()

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    rng.seed(0)
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model,
                                     max_iterations=1000) 
Example 41
Project: Dumb-Cogs   Author: irdumbs   File: adventure.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, seed=None):
        Data.__init__(self)
        self.output = ''
        self.yesno_callback = False
        self.yesno_casual = False       # whether to insist they answer

        self.clock1 = 30                # counts down from finding last treasure
        self.clock2 = 50                # counts down until cave closes
        self.is_closing = False         # is the cave closing?
        self.panic = False              # they tried to leave during closing?
        self.is_closed = False          # is the cave closed?
        self.is_done = False            # caller can check for "game over"
        self.could_fall_in_pit = False  # could the player fall into a pit?

        self.random_generator = random.Random()
        if seed is not None:
            self.random_generator.seed(seed) 
Example 42
Project: python-   Author: secondtonone1   File: tempfile.py    (license) View Source Project 5 votes vote down vote up
def rng(self):
        cur_pid = _os.getpid()
        if cur_pid != getattr(self, '_rng_pid', None):
            self._rng = _Random()
            self._rng_pid = cur_pid
        return self._rng 
Example 43
Project: picoCTF   Author: picoCTF   File: deploy.py    (MIT License) View Source Project 5 votes vote down vote up
def give_port():
    """
    Returns a random port and registers it.
    """

    global port_random

    context = get_deploy_context()

    # default behavior
    if context["config"] is None:
        return randint(1000, 65000)

    if "banned_ports_parsed" not in context["config"]:
        banned_ports_result = []
        for port_range in context["config"].banned_ports:
            banned_ports_result.extend(list(range(port_range["start"], port_range["end"] + 1)))

        context["config"]["banned_ports_parsed"] = banned_ports_result

    # during real deployment, let's register a port
    if port_random is None:
        port_random = Random(context["config"].deploy_secret)

    # if this instance already has a port, reuse it
    if (context["problem"], context["instance"]) in inv_port_map:
        return inv_port_map[(context["problem"], context["instance"])]

    if len(context["port_map"].items()) + len(context["config"].banned_ports_parsed) == 65536:
        raise Exception("All usable ports are taken. Cannot deploy any more instances.")

    while True:
        port = port_random.randint(0, 65535)
        if port not in context["config"].banned_ports_parsed:
            owner, instance = context["port_map"].get(port, (None, None))
            if owner is None or (owner == context["problem"] and instance == context["instance"]):
                context["port_map"][port] = (context["problem"], context["instance"])
                return port 
Example 44
Project: picoCTF   Author: picoCTF   File: deploy.py    (MIT License) View Source Project 5 votes vote down vote up
def update_problem_class(Class, problem_object, seed, user, instance_directory):
    """
    Changes the metaclass of the given class to introduce necessary fields before
    object instantiation.

    Args:
        Class: The problem class to be updated
        problem_name: The problem name
        seed: The seed for the Random object
        user: The linux username for this challenge instance
        instance_directory: The deployment directory for this instance

    Returns:
        The updated class described above
    """

    random = Random(seed)
    attributes = deepcopy(problem_object)

    # pass configuration options in as class fields
    attributes.update(dict(deploy_config))

    attributes.update({"random": random, "user": user, "directory": instance_directory,
                       "server": deploy_config.hostname})

    return challenge_meta(attributes)(Class.__name__, Class.__bases__, Class.__dict__) 
Example 45
Project: 8-Queens   Author: miguelarauj1o   File: state.py    (MIT License) View Source Project 5 votes vote down vote up
def initial_state(self):
        r = Random()
        return [r.randint(1, 8) for y in range(8)] 
Example 46
Project: 8-Queens   Author: miguelarauj1o   File: state.py    (MIT License) View Source Project 5 votes vote down vote up
def crossover(self, p1, p2):
        r = Random()
        crossover_index = r.randint(0, 8)
        left = p1.state[0:crossover_index]
        right = p2.state[crossover_index:8]
        left.extend(right)
        return left 
Example 47
Project: 8-Queens   Author: miguelarauj1o   File: state.py    (MIT License) View Source Project 5 votes vote down vote up
def mutate(self):
        r = Random()
        for i in range(len(self.state)):
            if random() < self._mutation_rate:
                self.state[i] = r.randint(1,8) 
Example 48
Project: 8-Queens   Author: miguelarauj1o   File: state.py    (MIT License) View Source Project 5 votes vote down vote up
def mutate(self):
        r = Random()
        
        if random() < self._mutation_rate:
            ix1 = r.randint(0,len(self.state)-1)
            ix2 = r.randint(0,len(self.state)-1)
            temp = self.state[ix1]
            self.state[ix1] = self.state[ix2]
            self.state[ix2] = temp 
Example 49
Project: kinect-2-libras   Author: inessadl   File: tempfile.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __init__(self):
        self.mutex = _allocate_lock()
        self.rng = _Random()
        self.normcase = _os.path.normcase 
Example 50
Project: abe-bootstrap   Author: TryCoin-Team   File: datagen.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(gen, rng=1, chain=None, **kwargs):
        if not hasattr(rng, 'randrange'):
            import random
            rng = random.Random(rng)
        if chain is None:
            chain = Abe.Chain.create("Testnet")

        gen._rng = rng
        gen.chain = chain

        for attr, val in kwargs.items():
            setattr(gen, attr, val)