Python random.expovariate() Examples

The following are code examples for showing how to use random.expovariate(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_explicit_from_float(self):
        r = Decimal(0.1)
        self.assertEqual(type(r), Decimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        self.assertTrue(Decimal(float('nan')).is_qnan())
        self.assertTrue(Decimal(float('inf')).is_infinite())
        self.assertTrue(Decimal(float('-inf')).is_infinite())
        self.assertEqual(str(Decimal(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(Decimal(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(Decimal(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertEqual(str(Decimal(float('-0.0'))),
                         str(Decimal('-0')))
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(Decimal(x))) # roundtrip 
Example 2
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_from_float(self):

        class  MyDecimal(Decimal):
            pass

        r = MyDecimal.from_float(0.1)
        self.assertEqual(type(r), MyDecimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        bigint = 12345678901234567890123456789
        self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
        self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
        self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
        self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
        self.assertEqual(str(MyDecimal.from_float(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(MyDecimal.from_float(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_decimal.py    GNU General Public License v3.0 6 votes vote down vote up
def test_explicit_from_float(self):

        Decimal = self.decimal.Decimal

        r = Decimal(0.1)
        self.assertEqual(type(r), Decimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        self.assertTrue(Decimal(float('nan')).is_qnan())
        self.assertTrue(Decimal(float('inf')).is_infinite())
        self.assertTrue(Decimal(float('-inf')).is_infinite())
        self.assertEqual(str(Decimal(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(Decimal(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(Decimal(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertEqual(str(Decimal(float('-0.0'))),
                         str(Decimal('-0')))
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(Decimal(x))) # roundtrip 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_decimal.py    GNU General Public License v3.0 6 votes vote down vote up
def test_explicit_context_create_from_float(self):

        Decimal = self.decimal.Decimal

        nc = self.decimal.Context()
        r = nc.create_decimal(0.1)
        self.assertEqual(type(r), Decimal)
        self.assertEqual(str(r), '0.1000000000000000055511151231')
        self.assertTrue(nc.create_decimal(float('nan')).is_qnan())
        self.assertTrue(nc.create_decimal(float('inf')).is_infinite())
        self.assertTrue(nc.create_decimal(float('-inf')).is_infinite())
        self.assertEqual(str(nc.create_decimal(float('nan'))),
                         str(nc.create_decimal('NaN')))
        self.assertEqual(str(nc.create_decimal(float('inf'))),
                         str(nc.create_decimal('Infinity')))
        self.assertEqual(str(nc.create_decimal(float('-inf'))),
                         str(nc.create_decimal('-Infinity')))
        self.assertEqual(str(nc.create_decimal(float('-0.0'))),
                         str(nc.create_decimal('-0')))
        nc.prec = 100
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(nc.create_decimal(x))) # roundtrip 
Example 5
Project: tomomibot   Author: adzialocha   File: session.py    MIT License 6 votes vote down vote up
def play(self):
        while self.is_running:
            time.sleep(CHECK_WAV_INTERVAL)
            if not self.is_running:
                return

            if len(self._wavs) > 1:
                # Get next wav file to play from queue
                wav = self._wavs[0]

                self.ctx.vlog(
                    '▶ play .wav sample "{}" (queue={}, density={})'.format(
                        os.path.basename(wav),
                        len(self._wavs),
                        self._density))

                # Delay playing the sample a little bit
                rdm = random.expovariate(PLAY_DELAY_EXP) * self._density
                time.sleep(rdm)

                # Play it!
                self._audio.play(wav)

                # Remove the played sample from our queue
                self._wavs = self._wavs[1:] 
Example 6
Project: cbeams   Author: tartley   File: animate.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, color):
        self.color = color # as an integer

        # Center point.
        self.y, self.x = terminal.rand_coord()

        # The max radius we will reach.
        term_size = terminal.get_max_dimension()
        self.size = 2 + min(term_size * 2, random.expovariate(32 / term_size))

        # How close 'outer' gets to its max size before 'inner' starts to grow.
        # From 0 to 1
        self.thickness = random.triangular(0.3, 0.95)

        # Outer and inner radii.
        self.outer = 0.0
        self.inner = 0.0
        # The value of 'inner' on the last frame.
        self.inner_last = self.inner 
Example 7
Project: ironpython2   Author: IronLanguages   File: test_decimal.py    Apache License 2.0 6 votes vote down vote up
def test_explicit_from_float(self):
        r = Decimal(0.1)
        self.assertEqual(type(r), Decimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        self.assertTrue(Decimal(float('nan')).is_qnan())
        self.assertTrue(Decimal(float('inf')).is_infinite())
        self.assertTrue(Decimal(float('-inf')).is_infinite())
        self.assertEqual(str(Decimal(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(Decimal(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(Decimal(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertEqual(str(Decimal(float('-0.0'))),
                         str(Decimal('-0')))
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(Decimal(x))) # roundtrip 
Example 8
Project: ironpython2   Author: IronLanguages   File: test_decimal.py    Apache License 2.0 6 votes vote down vote up
def test_from_float(self):

        class  MyDecimal(Decimal):
            pass

        r = MyDecimal.from_float(0.1)
        self.assertEqual(type(r), MyDecimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        bigint = 12345678901234567890123456789
        self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
        self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
        self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
        self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
        self.assertEqual(str(MyDecimal.from_float(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(MyDecimal.from_float(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 
Example 9
Project: ocs-monkey   Author: JohnStrunk   File: osio.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _action_idle(self, deploy: kube.MANIFEST) -> kube.MANIFEST:
        anno = deploy["metadata"]["annotations"]
        if deploy["spec"]["replicas"] == 0:  # idle -> active
            deploy["spec"]["replicas"] = 1
            active_mean = float(anno["ocs-monkey/osio-active"])
            active_duration = random.expovariate(1/active_mean)
            if WORKAROUND_MIN_RUNTIME:
                active_duration = max(active_duration, self._health_interval_initial)
            idle_time = time.time() + active_duration
            health_time = time.time() + self._health_interval_initial
            LOGGER.info("idle->active: %s/%s", self._namespace, self._name)
            EXECUTOR.submit(_pod_start_watcher, copy.deepcopy(deploy))
        else:  # active -> idle
            deploy["spec"]["replicas"] = 0
            idle_mean = float(anno["ocs-monkey/osio-idle"])
            idle_duration = random.expovariate(1/idle_mean)
            if WORKAROUND_MIN_RUNTIME:
                idle_duration = max(idle_duration, self._health_interval_initial)
            idle_time = time.time() + idle_duration
            health_time = time.time() + self._health_interval
            LOGGER.info("active->idle: %s/%s", self._namespace, self._name)
            EXECUTOR.submit(_pod_stop_watcher, copy.deepcopy(deploy))
        anno["ocs-monkey/osio-idle-at"] = str(idle_time)
        anno["ocs-monkey/osio-health-at"] = str(health_time)
        return deploy 
Example 10
Project: CyberScan   Author: medbenali   File: asn1.py    GNU General Public License v3.0 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 11
Project: oss-ftp   Author: aliyun   File: test_decimal.py    MIT License 6 votes vote down vote up
def test_explicit_from_float(self):
        r = Decimal(0.1)
        self.assertEqual(type(r), Decimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        self.assertTrue(Decimal(float('nan')).is_qnan())
        self.assertTrue(Decimal(float('inf')).is_infinite())
        self.assertTrue(Decimal(float('-inf')).is_infinite())
        self.assertEqual(str(Decimal(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(Decimal(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(Decimal(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertEqual(str(Decimal(float('-0.0'))),
                         str(Decimal('-0')))
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(Decimal(x))) # roundtrip 
Example 12
Project: oss-ftp   Author: aliyun   File: test_decimal.py    MIT License 6 votes vote down vote up
def test_from_float(self):

        class  MyDecimal(Decimal):
            pass

        r = MyDecimal.from_float(0.1)
        self.assertEqual(type(r), MyDecimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        bigint = 12345678901234567890123456789
        self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
        self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
        self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
        self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
        self.assertEqual(str(MyDecimal.from_float(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(MyDecimal.from_float(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 
Example 13
Project: deep-scheduler   Author: mfatihaktas   File: sim_objs.py    MIT License 6 votes vote down vote up
def run_poisson(self):
    while 1:
      yield self.env.timeout(random.expovariate(self.ar) )
      self.nsent += 1
      k = self.k_rv.sample()
      demandmean = self.demandperslot_mean_rv.sample()
      coeff_var = 0.7
      self.out.put(Job(
        _id = self.nsent,
        k = k, n = k,
        demandperslot_rv = TNormal(demandmean, demandmean*coeff_var),
        totaldemand = self.totaldemand_rv.sample() ) )
      
      # if self.nsent >= self.njob:
      #   return

# #########################################  Worker  ############################################# # 
Example 14
Project: dice   Author: code-dice   File: rnd.py    GNU General Public License v2.0 6 votes vote down vote up
def int_exp(min_inc=0, max_inc=None, lambd=0.01):
    """
    A non accurate exponentially distributed integer generator.
    """
    shift = int(random.expovariate(lambd))
    if max_inc is not None:
        if max_inc - min_inc == 0:
            shift = 0
        else:
            shift %= max_inc - min_inc
    if min_inc is not None and min_inc >= 0:
        return min_inc + shift
    else:
        minus = random.random() > 0.5
        if min_inc is not None and minus and shift > - min_inc:
            shift %= - min_inc
        return - shift if minus else shift 
Example 15
Project: dice   Author: code-dice   File: symbol.py    GNU General Public License v2.0 6 votes vote down vote up
def generate(self):
        """
        Generate a random integer.
        """
        scale = 50.0
        maximum = self.maximum
        minimum = self.minimum
        while True:
            sign = 1.0 if random.random() > 0.5 else -1.0
            res = sign * (2.0 ** (random.expovariate(1.0 / scale)) - 1.0)
            if maximum is not None:
                if maximum >= 0 and res > maximum + 1:
                    continue
                if maximum < 0 and res > maximum:
                    continue
            if minimum is not None:
                if minimum >= 0 and res < minimum:
                    continue
                if minimum < 0 and res < minimum - 1:
                    continue
            return int(res) 
Example 16
Project: arkc-server   Author: projectarkc   File: control.py    GNU General Public License v2.0 6 votes vote down vote up
def conn_check(self, conn):
        """Test whether a connection is authenticated, if so,
        Reset the connection after a random time for better performance.
        """
        if conn:
            if conn.authenticated:
                # Reset the connection after a random time, no need if using
                # timeout enforced by GAE
                if self.obfs_level < 3:
                    expire_time = expovariate(1.0 / 60)
                else:
                    expire_time = expovariate(1.0 / 30)
                reactor.callLater(expire_time, self.client_reset, conn)
            else:
                conn.write(self.close_char, "00", "100000")
                conn.close()
                if all((_ is None) or (_ == 1) for _ in self.client_connectors_pool):
                    self.initiator.blacklist_count(
                        self.client_sha1, self.main_pw)
                    self.dispose()
            # TODO: ADD to some black list? 
Example 17
Project: momi2   Author: popgenmethods   File: demo_utils.py    GNU General Public License v3.0 6 votes vote down vote up
def random_tree_demo(num_leaf_pops, lins_per_pop):
    #events_list = []
    sampled_pops = list(range(1, num_leaf_pops + 1))
    model = momi.DemographicModel(1.0, .25)
    for p in sampled_pops:
        model.add_leaf(p, N=random.expovariate(1.0))
    roots = list(sampled_pops)
    #for i in roots:
    #    events_list += [('-en', 0.0, i, random.expovariate(1.0))]
    t = 0.0
    while len(roots) > 1:
        i, j = random.sample(roots, 2)
        t += random.expovariate(1.0)
        #events_list += [('-ej', t, i, j),
        #                ('-en', t, j, random.expovariate(1.0))]
        model.move_lineages(i, j, t, N=random.expovariate(1.0))
        roots.remove(i)
    #return make_demo_hist(events_list, sampled_pops, [lins_per_pop] * num_leaf_pops)
    return model
    # return make_demography(events_list, sampled_pops, [lins_per_pop] *
    # num_leaf_pops) 
Example 18
Project: Dollynator   Author: Tribler   File: test_cloudomate_controller.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_pick_providers(self, mock1):

        self.vps = cloudomate.get_vps_providers
        self.get_gateway = blueAngel.BlueAngelHost.get_gateway
        self.estimate_price = Coinbase.Coinbase.estimate_price
        self.get_price = wallet_util.get_price
        self.get_fee = wallet_util.get_network_fee

        # cloudomate.get_vps_providers = MagicMock(
        #     return_value=CaseInsensitiveDict({'blueangelhost': blueAngel.BlueAngelHost}))
        random.expovariate = MagicMock(return_value=0.55)
        blueAngel.BlueAngelHost.get_gateway = MagicMock()
        Coinbase.Coinbase.estimate_price = MagicMock()
        cloudomate.pick_option = MagicMock(return_value=[1, 2, 3])
        wallet_util.get_price = MagicMock()
        wallet_util.get_network_fee = MagicMock()

        cloudomate.pick_provider(cloudomate.get_vps_providers())
        blueAngel.BlueAngelHost.get_gateway.assert_called_once()

        cloudomate.get_vps_providers = self.vps
        blueAngel.BlueAngelHost.get_gateway = self.get_gateway
        Coinbase.Coinbase.estimate_price = self.estimate_price
        wallet_util.get_price = self.get_price
        wallet_util.get_network_fee = self.get_fee 
Example 19
Project: CVE-2016-6366   Author: RiskSense-Ops   File: asn1.py    MIT License 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 20
Project: scapy   Author: secdev   File: asn1.py    GNU General Public License v2.0 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0, 1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_GENERALIZED_TIME) or issubclass(o, ASN1_UTC_TIME):  # noqa: E501
            z = GeneralizedTime()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05) + 1)
            return o("".join(random.choice(self.chars) for _ in range(z)))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08) + 1)
            return o([self.__class__(objlist=self.objlist)._fix(n + 1)
                      for _ in range(z)])
        return ASN1_INTEGER(int(random.gauss(0, 1000)))


##############
#    ASN1    #
############## 
Example 21
Project: rally   Author: elastic   File: params.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, index_name, type_name, conflicting_ids=None, conflict_probability=None, on_conflict=None,
                 recency=None, rand=random.random, randint=random.randint, randexp=random.expovariate):
        if type_name:
            self.meta_data_index_with_id = '{"index": {"_index": "%s", "_type": "%s", "_id": "%s"}}' % \
                                           (index_name, type_name, "%s")
            self.meta_data_update_with_id = '{"update": {"_index": "%s", "_type": "%s", "_id": "%s"}}' % \
                                            (index_name, type_name, "%s")
            self.meta_data_index_no_id = '{"index": {"_index": "%s", "_type": "%s"}}' % (index_name, type_name)
        else:
            self.meta_data_index_with_id = '{"index": {"_index": "%s", "_id": "%s"}}' % (index_name, "%s")
            self.meta_data_update_with_id = '{"update": {"_index": "%s", "_id": "%s"}}' % (index_name, "%s")
            self.meta_data_index_no_id = '{"index": {"_index": "%s"}}' % index_name

        self.conflicting_ids = conflicting_ids
        self.on_conflict = on_conflict
        # random() produces numbers between 0 and 1 and the user denotes the probability in percentage between 0 and 100
        self.conflict_probability = conflict_probability / 100.0 if conflict_probability is not None else 0
        self.recency = recency if recency is not None else 0

        self.rand = rand
        self.randint = randint
        self.randexp = randexp
        self.id_up_to = 0 
Example 22
Project: Merc-01   Author: Secretmapper   File: levels.py    MIT License 6 votes vote down vote up
def one_mid_two(self):
    points = 1000
    choice = [(get_bouncer, 25, 50),
              (get_tracker, 50, 30),
              (get_evader,  100, 20)]
    to_spawn = get_spawn_list(points, choice)

    rate = 1.0
    while(len(to_spawn) > 0):
        if len(to_spawn) > 0 and random.randint(0, 100) <= random.expovariate(1 / rate):
            x, y = self.get_spawn_pos()
            fn, params = to_spawn.pop()
            if params:
                fn(self, *params)
            else:
                self.enemies.append(fn(self, x, y))
        yield True
    yield two 
Example 23
Project: Merc-01   Author: Secretmapper   File: levels.py    MIT License 6 votes vote down vote up
def three(self):
    for i in xrange(3):
        get_blackhole(self, spawn=True)
        spawn_line(self)
        points = 500
        choice = [(get_bouncer, 25, 50),
                  (get_tracker, 50, 30),
                  (get_evader,  100, 20)]
        to_spawn = get_spawn_list(points, choice)

        rate = 2.0
        while(len(to_spawn) > 0):
            if len(to_spawn) > 0 and random.randint(0, 100) <= random.expovariate(1 / rate):
                x, y = self.get_spawn_pos()
                fn, params = to_spawn.pop()
                if params:
                    fn(self, *params)
                else:
                    self.enemies.append(fn(self, x, y))
            yield True
        yield True
    yield four 
Example 24
Project: instaloader   Author: instaloader   File: instaloadercontext.py    MIT License 5 votes vote down vote up
def do_sleep(self):
        """Sleep a short time if self.sleep is set. Called before each request to instagram.com."""
        if self.sleep:
            time.sleep(min(random.expovariate(0.7), 5.0)) 
Example 25
Project: LaserTOF   Author: kyleuckert   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_decimal.py    GNU General Public License v3.0 5 votes vote down vote up
def test_from_float(self):

        Decimal = self.decimal.Decimal

        class MyDecimal(Decimal):
            def __init__(self, _):
                self.x = 'y'

        self.assertTrue(issubclass(MyDecimal, Decimal))

        r = MyDecimal.from_float(0.1)
        self.assertEqual(type(r), MyDecimal)
        self.assertEqual(str(r),
                '0.1000000000000000055511151231257827021181583404541015625')
        self.assertEqual(r.x, 'y')

        bigint = 12345678901234567890123456789
        self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
        self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
        self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
        self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
        self.assertEqual(str(MyDecimal.from_float(float('nan'))),
                         str(Decimal('NaN')))
        self.assertEqual(str(MyDecimal.from_float(float('inf'))),
                         str(Decimal('Infinity')))
        self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
                         str(Decimal('-Infinity')))
        self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
        for i in range(200):
            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
            self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 
Example 27
Project: LogCausalAnalysis   Author: cpflat   File: randlog.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def poisson_process(top_dt, end_dt, lambd):
    def next_dt(dt):
        return dt + datetime.timedelta(seconds = 1) * int(
                24 * 60 * 60 * random.expovariate(lambd))

    temp_dt = top_dt
    temp_dt = next_dt(temp_dt)
    while temp_dt < end_dt:
        yield temp_dt
        temp_dt = next_dt(temp_dt) 
Example 28
Project: LogCausalAnalysis   Author: cpflat   File: dtutil.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rand_next_exp(dt, lambd):
    return dt + datetime.timedelta(seconds = 1) * int(
            24 * 60 * 60 * random.expovariate(lambd)) 
Example 29
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_matfuncs.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 30
Project: ocs-monkey   Author: JohnStrunk   File: osio.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,  # pylint: disable=too-many-arguments
                 namespace: str,
                 storage_class: str,
                 access_mode: str,
                 interarrival: float,
                 lifetime: float,
                 active: float,
                 idle: float,
                 kernel_slots: int,
                 kernel_untar: float,
                 kernel_rm: float,
                 workload_image: str) -> None:
        """
        Deployments are created and destroyed at some random rate.

        Given some mean interarrival time, a, and lifetime, l, the average
        number of Deployments that would be expected to exist is (l/a) according
        to Little's Law.
        """
        self._namespace = namespace
        self._storage_class = storage_class
        self._access_mode = access_mode
        self._interarrival = interarrival
        self._lifetime = lifetime
        self._active = active
        self._idle = idle
        self._kernel_slots = kernel_slots
        self._kernel_untar = kernel_untar
        self._kernel_rm = kernel_rm
        self._workload_image = workload_image
        super().__init__(when=time.time() +
                         random.expovariate(1/self._interarrival)) 
Example 31
Project: ocs-monkey   Author: JohnStrunk   File: osio.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _action_initialize(self, deploy: kube.MANIFEST) -> kube.MANIFEST:
        anno = deploy["metadata"]["annotations"]
        idle_mean = float(anno["ocs-monkey/osio-idle"])
        idle_duration = random.expovariate(1/idle_mean)
        if WORKAROUND_MIN_RUNTIME:
            idle_duration = max(idle_duration, self._health_interval_initial)
        idle_time = time.time() + idle_duration
        anno["ocs-monkey/osio-idle-at"] = str(idle_time)
        health_time = time.time() + self._health_interval_initial
        anno["ocs-monkey/osio-health-at"] = str(health_time)
        return deploy 
Example 32
Project: botfriend   Author: leonardr   File: euphemism.py    MIT License 5 votes vote down vote up
def choose(self, choices, mean):
        if mean is None:
            return random.choice(choices)
        else:
            mean = len(choices) * mean
            v = None
            while v is None or v >= len(choices):
                v = int(random.expovariate(1.0/mean))
            return choices[v] 
Example 33
Project: botfriend   Author: leonardr   File: entrepreneur.py    MIT License 5 votes vote down vote up
def choose(self, choices, mean):
        if mean is None:
            return random.choice(choices)
        else:
            mean = len(choices) * mean
            v = None
            while v is None or v >= len(choices):
                v = int(random.expovariate(1.0/mean))
            return choices[v] 
Example 34
Project: HyperStream   Author: IRC-SPHERE   File: 2017-06-20_v1.0.0.py    MIT License 5 votes vote down vote up
def _execute(self, sources, alignment_stream, interval):
        if alignment_stream is None:
            raise ToolExecutionError("Alignment stream expected")

        for ti, _ in alignment_stream.window(interval, force_calculation=True):
            yield StreamInstance(ti, random.expovariate(lambd=self.lambd)) 
Example 35
Project: CyberScan   Author: medbenali   File: volatile.py    GNU General Public License v3.0 5 votes vote down vote up
def _fix(self):
        return self.base+int(round(random.expovariate(self.lambd))) 
Example 36
Project: ble5-nrf52-mac   Author: tomasero   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 37
Project: Dallinger   Author: Dallinger   File: bots.py    MIT License 5 votes vote down vote up
def wait_to_send_message(self):
        waiting_time = random.expovariate(1.0 / self.AVG_TIME_BETWEEN_MESSAGES)
        time.sleep(waiting_time) 
Example 38
Project: Dallinger   Author: Dallinger   File: bots.py    MIT License 5 votes vote down vote up
def stochastic_sleep(self):
        delay = max(1.0 / random.expovariate(0.5), 10.0)
        gevent.sleep(delay) 
Example 39
Project: Dallinger   Author: Dallinger   File: db.py    MIT License 5 votes vote down vote up
def serialized(func):
    """Run a function within a db transaction using SERIALIZABLE isolation.

    With this isolation level, committing will fail if this transaction
    read data that was since modified by another transaction. So we need
    to handle that case and retry the transaction.
    """

    @wraps(func)
    def wrapper(*args, **kw):
        attempts = 100
        session.remove()
        while attempts > 0:
            try:
                session.connection(
                    execution_options={"isolation_level": "SERIALIZABLE"}
                )
                result = func(*args, **kw)
                session.commit()
                return result
            except OperationalError as exc:
                session.rollback()
                if isinstance(exc.orig, TransactionRollbackError):
                    if attempts > 0:
                        attempts -= 1
                    else:
                        raise Exception(
                            "Could not commit serialized transaction "
                            "after 100 attempts."
                        )
                else:
                    raise
            finally:
                session.remove()
            time.sleep(random.expovariate(0.5))

    return wrapper


# Reset outbox when session begins 
Example 40
Project: Computable   Author: ktraunmueller   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 41
Project: numerate-language-models   Author: uclnlp   File: download_arxmliv.py    GNU General Public License v3.0 5 votes vote down vote up
def get_delay(self):
        self.n_called += 1
        if self.mode == 'unlimited':
            interval = 0.0
        elif self.mode == 'careful':
            interval = random.expovariate(self.avg_num_requests_per_minute/60.0)
            self.total_time += interval
            if self.total_time > self.reset_every:
                self.total_time = 0
                interval = self.reset_delay
        return interval 
Example 42
Project: poker   Author: surgebiswas   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 43
Project: deep-scheduler   Author: mfatihaktas   File: rvs.py    MIT License 5 votes vote down vote up
def sample(self):
    return self.D + random.expovariate(self.mu) 
Example 44
Project: deep-scheduler   Author: mfatihaktas   File: sim.py    MIT License 5 votes vote down vote up
def run_poisson(self):
    while 1:
      yield self.env.timeout(random.expovariate(self.ar) )
      self.nsent += 1
      self.out.put(Job(self.nsent, self.k_dist.gen_sample(), self.size_dist.gen_sample() ) )
      
      if self.nsent >= self.ntosend:
        return 
Example 45
Project: deep-scheduler   Author: mfatihaktas   File: sim.py    MIT License 5 votes vote down vote up
def run_selfsimilar(self):
    stime = Pareto(1, 1.2)
    arepoch_l = [0]
    for i in range(self.ntosend):
      arepoch_l.append(arepoch_l[-1] + random.expovariate(self.ar) )
    arepoch_l = sorted([e + stime.gen_sample() for e in arepoch_l] )
    
    for i in range(1, self.ntosend+1):
      yield self.env.timeout(arepoch_l[i] - arepoch_l[i-1] )
      self.nsent += 1
      self.out.put(Job(self.nsent, self.k_dist.gen_sample(), self.size_dist.gen_sample() ) )
    return 
Example 46
Project: deep-scheduler   Author: mfatihaktas   File: sim_wqs_objs.py    MIT License 5 votes vote down vote up
def run_poisson(self):
    while 1:
      yield self.env.timeout(random.expovariate(self.ar) )
      self.nsent += 1
      k = self.k_rv.sample()
      demandmean = self.demandperslot_mean_rv.sample()
      coeff_var = 0.7
      self.out.put(Job(
        _id = self.nsent,
        k = k, n = k,
        demandperslot_rv = TNormal(demandmean, demandmean*coeff_var),
        totaldemand = self.totaldemand_rv.sample() ) )
  
# #########################################  Worker  ############################################# # 
Example 47
Project: P3_image_processing   Author: latedude2   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 48
Project: PyQueueSim   Author: tkralphs   File: QueueSim.py    MIT License 5 votes vote down vote up
def process_event(self, event):
        '''
        processes event given and updates sqList and eventTable accordingly
        '''
        if event.eventType == ARRIVE: 
            whichQueue, whichServer = self.which_queue()
            serviceTime = expovariate(1.0/self.ST)
            if whichServer == None:
                self.sqList[whichQueue].enqueue(Customer(self.currentTime, 
                                                         serviceTime, 
                                                         self.customerCounter))
            else:
                self.waitingTime[self.customerCounter] = 0
                self.serviceTime[self.customerCounter] = serviceTime
                self.add_event(DEPART, self.currentTime + serviceTime, 
                               whichServer)
            self.customerCounter += 1
            self.add_event(ARRIVE, self.currentTime+expovariate(1.0/self.IAT))
        elif event.eventType == DEPART:
            if self.queue_num == 1:
                q = self.sqList[0]
            else:
                q = self.sqList[event.serverNumber]
            if not q.isEmpty():
                customer = q.dequeue()
                self.waitingTime[customer.number] = (self.currentTime - 
                                                     customer.entryTime)
                self.serviceTime[customer.number] = customer.serviceTime
                self.add_event(DEPART, self.currentTime + customer.serviceTime,
                               event.serverNumber)
            else:
                self.server[event.serverNumber] = IDLE
        else:
            print "Unknown event type" 
Example 49
Project: webapp-bench   Author: edgedb   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_acting_career(self):
        'A number of movies an actor starred in.'
        return max(1, round(random.expovariate(1 / 9))) 
Example 50
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_matfuncs.py    MIT License 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 51
Project: Simulations   Author: harrymunro   File: depot_model_simpy.py    MIT License 5 votes vote down vote up
def interval(time):
	#result = random.expovariate(1.0 / time) # use for fleet maintenance model
	result = time # use for individual train maintenance model
	return result 
Example 52
Project: Simulations   Author: harrymunro   File: termini_simulation_animation.py    MIT License 5 votes vote down vote up
def arrival_interval(T_INTER):
    t = random.expovariate(1.0/T_INTER) # exponential distribution, not particularly useful for "as fast as possible", more useful if we want to try to reproduce real world arrival times
    return t

# set up the dwell variable 
Example 53
Project: Simulations   Author: harrymunro   File: equipment_availability_sim.py    MIT License 5 votes vote down vote up
def time_to_failure():
    """Return time until next failure for a machine."""
    return random.expovariate(BREAK_MEAN) 
Example 54
Project: Simulations   Author: harrymunro   File: equipment_availability_sim.py    MIT License 5 votes vote down vote up
def REPAIR_TIME():
    """Return time until next failure for a machine."""
    return random.expovariate(MEAN_REPAIR_TIME) + random.expovariate(MEAN_LOGISTICS_TIME) 
Example 55
Project: Dollynator   Author: Tribler   File: test_qtable.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_choose_option(self, mock1, mock2, mock3):
        self.qtable.init_qtable_and_environment(self.providers)
        self.qtable.set_self_state(VPSState("blueangelhost", "Advanced"))
        random.expovariate = MagicMock(return_value=0.55)
        option = self.qtable.choose_option(self.providers)
        assert (option["option_name"] == "Basic Plan")
        assert (option["price"] == 10.0) 
Example 56
Project: Dollynator   Author: Tribler   File: qtable.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def choose_option(self, providers):
        lambd = 1 - 1 / (self.get_no_replications() + 3)
        num = random.expovariate(lambd)
        num = int(math.floor(num))

        if num > len(self.qtable[self.get_ID_from_state()]) - 1:
            num = len(self.qtable[self.get_ID_from_state()]) - 1

        return self.choose_k_option(providers, num) 
Example 57
Project: CVE-2016-6366   Author: RiskSense-Ops   File: volatile.py    MIT License 5 votes vote down vote up
def _fix(self):
        return self.base+int(round(random.expovariate(self.lambd))) 
Example 58
Project: scraper   Author: m-lab   File: run_scraper.py    Apache License 2.0 5 votes vote down vote up
def main(argv):
    """Run scraper.py in an infinite loop."""
    args = parse_cmdline(argv[1:])
    rsync_url, status, destination, storage_service = scraper.init(args)
    prometheus_client.start_http_server(args.metrics_port)
    # First, clear out any existing cache that can be cleared.
    with UPLOAD_RUNS.time():
        # Upload except for the most recent day on disk.
        retry.api.retry_call(scraper.upload_stale_disk,
                             (args, status, destination, storage_service),
                             exceptions=scraper.RecoverableScraperException)
    # Now, download then upload until we run out of num_runs
    while args.num_runs > 0:
        try:
            logging.info('Scraping %s', rsync_url)
            with RSYNC_RUNS.time():
                scraper.download(args, rsync_url, status, destination)
            with UPLOAD_RUNS.time():
                scraper.upload_if_allowed(args, status, destination,
                                          storage_service)
            SCRAPER_SUCCESS.labels(message='success').inc()
        except scraper.RecoverableScraperException as error:
            logging.error('Scrape and upload failed: %s', error.message)
            SCRAPER_SUCCESS.labels(message=str(error.prometheus_label)).inc()
        # In order to prevent a thundering herd of rsync jobs, we spread the
        # jobs around in a memoryless way.  By choosing our inter-job sleep
        # time from an exponential distribution, we ensure that the resulting
        # time distribution of jobs is Poisson, the one and only memoryless
        # distribution.  The denominator of the fraction in the code below is
        # the mean sleep time in seconds.
        #
        # That said, don't sleep for more than an hour.
        sleep_time = min(random.expovariate(1.0 / args.expected_wait_time),
                         3600)
        logging.info('Sleeping for %g seconds', sleep_time)
        with SLEEPS.time():
            time.sleep(sleep_time)
        args.num_runs -= 1 
Example 59
Project: slack-coub   Author: asfdfdfd   File: main.py    MIT License 5 votes vote down vote up
def random_exponential(self, value_max):
        return (random.expovariate(value_max / 10.0) * value_max) % value_max 
Example 60
Project: scapy   Author: secdev   File: volatile.py    GNU General Public License v2.0 5 votes vote down vote up
def _fix(self):
        return self.base + int(round(random.expovariate(self.lambd))) 
Example 61
Project: wot-py   Author: agmangas   File: server.py    MIT License 5 votes vote down vote up
def build_event_burst_handler(exposed_thing):
    """Factory function to build the handler for the action that initiates event bursts."""

    async def start_event_burst(parameters):
        """Emits a series of events where the total count and interval
        between each emission is determined by the given parameters."""

        time_start = time_millis()

        input_dict = parameters["input"] if parameters["input"] else {}

        lambd = input_dict.get("lambd", DEFAULT_BURST_LAMBD)
        total = input_dict.get("total", DEFAULT_BURST_TOTAL)
        burst_id = input_dict.get("id", uuid.uuid4().hex)

        for idx in range(total):
            exposed_thing.emit_event("burstEvent", {
                "id": burst_id,
                "index": idx,
                "timeStart": time_start,
                "timeEmission": time_millis(),
                "burstEnd": idx == total - 1
            })

            await asyncio.sleep(random.expovariate(lambd))

    return start_event_burst 
Example 62
Project: Python-iBeacon-Scan   Author: NikNitro   File: crv_types.py    GNU General Public License v3.0 5 votes vote down vote up
def sample(self):
        return random.expovariate(self.rate) 
Example 63
Project: feupy   Author: up201806185   File: cache.py    MIT License 5 votes vote down vote up
def _random_radioactive_lifetime(half_life = _datetime.timedelta(days=2), cutoff = True):
    """Returns a randomly generated lifetime of a radioactive particle with a half-life of half_life seconds
    (a time_delta is also acceptable).
    If cutoff is True (which is by default), if the lifetime generated is bigger than half_life * 4, the function
    will instead return half_life * 4, which is useful if you wish to avoid ridiculously large lifetimes
    This function is used to disperse the timeouts of the cache values.
    """
    if isinstance(half_life, _datetime.timedelta):
        half_life = half_life.total_seconds()

    lambd = 0.693147 / half_life # ln(2)/half-life
    lifetime = _random.expovariate(lambd)

    return min(lifetime, half_life * 4) if cutoff else lifetime 
Example 64
Project: pypedream   Author: garywu   File: _src.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_text_file(f_name, num_lines, num_chars):
    def _rand_line():
        len_ = int(random.expovariate(1. / num_chars))
        return ''.join(random.choice(string.ascii_letters) for x in range(len_)) + '\n'
        
    if os.path.exists(f_name):
        os.remove(f_name)
    with open(f_name, 'wb') as f:
        for i in range(num_lines):
            f.write(_rand_line()) 
Example 65
Project: pypedream   Author: garywu   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_05(self):
        for i in range(15):
            buf_len = max(10, int(random.expovariate(1. / 60)))   
            stream_len = max(10, int(random.expovariate(1. / 1000)))  
            rand_line = lambda len_: b''.join(
                random.choice(string.ascii_letters).encode('utf-8') for _ in range(len_))
            data = [rand_line(1 + min(int(random.expovariate(1. / 20)), buf_len - 2)) for _ in range(stream_len)]
            open('long_tmp.txt', 'wb').write(b'\n'.join(data))
            source(data) | to_stream('long_tmp1.txt', buf_size = buf_len)
            open('buf_size.txt', 'wb').write(bytes(buf_len))
            data1 = stream_lines('long_tmp1.txt') | to_list()
            stream_lines('long_tmp1.txt') | to_stream('long_tmp2.txt', buf_size = buf_len)
            data2 = stream_lines('long_tmp2.txt') | to_list()
            self.assertEqual(data, data1)
            self.assertEqual(data, data2) 
Example 66
Project: pypedream   Author: garywu   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_32(self):
        for i in range(5):
            chunk_len = max(10, random.expovariate(60))   
            stream_len = max(10, random.expovariate(1000))     
            npc, c = source((i, random.random()) for i in range(stream_len)) | \
                (np.chunk(chunk_len) | np.corr()) + corr()
        self.assertAlmostEqual(npc, c) 
Example 67
Project: gitcha-scripts   Author: yeonghoey   File: generate_dummy_data.py    MIT License 5 votes vote down vote up
def new_item_id():
    sample = int(random.expovariate(1.0) * (MAX_REPO/5))
    return str(min(sample, MAX_REPO)) 
Example 68
Project: Think-Bayes   Author: foamliu   File: kidney.py    Apache License 2.0 5 votes vote down vote up
def GenerateRdt(pc, lam1, lam2):
    """Generate an RDT from a mixture of exponential distributions.

    With prob pc, generate a negative value with param lam2;
    otherwise generate a positive value with param lam1.
    """
    if random.random() < pc:
        return -random.expovariate(lam2)
    else:
        return random.expovariate(lam1) 
Example 69
Project: rally   Author: elastic   File: scheduler.py    Apache License 2.0 5 votes vote down vote up
def next(self, current):
        # no need for calculations when we are not rate limiting
        if self.rate > 0:
            return current + random.expovariate(self.rate)
        else:
            return 0 
Example 70
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_matfuncs.py    Apache License 2.0 5 votes vote down vote up
def test_fuzz(self):
        # try a bunch of crazy inputs
        rfuncs = (
                np.random.uniform,
                np.random.normal,
                np.random.standard_cauchy,
                np.random.exponential)
        ntests = 100
        for i in range(ntests):
            rfunc = random.choice(rfuncs)
            target_norm_1 = random.expovariate(1.0)
            n = random.randrange(2, 16)
            A_original = rfunc(size=(n,n))
            E_original = rfunc(size=(n,n))
            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
            scale = target_norm_1 / A_original_norm_1
            A = scale * A_original
            E = scale * E_original
            M = np.vstack([
                np.hstack([A, E]),
                np.hstack([np.zeros_like(A), A])])
            expected_expm = scipy.linalg.expm(A)
            expected_frechet = scipy.linalg.expm(M)[:n, n:]
            observed_expm, observed_frechet = expm_frechet(A, E)
            assert_allclose(expected_expm, observed_expm)
            assert_allclose(expected_frechet, observed_frechet) 
Example 71
Project: notebooks   Author: fluentpython   File: taxi_sim.py    MIT License 5 votes vote down vote up
def compute_duration(previous_action):
    """Compute action duration using exponential distribution"""
    if previous_action in ['leave garage', 'drop off passenger']:
        # new state is prowling
        interval = SEARCH_DURATION
    elif previous_action == 'pick up passenger':
        # new state is trip
        interval = TRIP_DURATION
    elif previous_action == 'going home':
        interval = 1
    else:
        raise ValueError('Unknown previous_action: %s' % previous_action)
    return int(random.expovariate(1/interval)) + 1 
Example 72
Project: notebooks   Author: fluentpython   File: taxi_sim0.py    MIT License 5 votes vote down vote up
def compute_delay(interval):
    """Compute action delay using exponential distribution"""
    return int(random.expovariate(1/interval)) + 1

# BEGIN TAXI_PROCESS 
Example 73
Project: notebooks   Author: fluentpython   File: taxi_sim_delay.py    MIT License 5 votes vote down vote up
def compute_duration(previous_action):
    """Compute action duration using exponential distribution"""
    if previous_action in ['leave garage', 'drop off passenger']:
        # new state is prowling
        interval = SEARCH_DURATION
    elif previous_action == 'pick up passenger':
        # new state is trip
        interval = TRIP_DURATION
    elif previous_action == 'going home':
        interval = 1
    else:
        raise ValueError('Unknown previous_action: %s' % previous_action)
    return int(random.expovariate(1/interval)) + 1 
Example 74
Project: Merc-01   Author: Secretmapper   File: levels.py    MIT License 5 votes vote down vote up
def one(self):
    spawned = [get_bouncer(self)]
    self.enemies.extend(spawned)
    while(len(spawned) > 0):
        clear_spawn(spawned)
        yield True
    spawned = [get_bouncer(self) for i in xrange(2)]
    self.enemies.extend(spawned)

    points = 100

    # type - points - weight
    choice = [
        (get_bouncer, 25, 50),
        (get_tracker, 50, 30),
        (get_splitter, 50, 30),
        (get_evader,  100, 20),
        (spawn_corner, 400, 10, [1, get_evader]),
    ]
    to_spawn = get_spawn_list(points, choice)

    rate = 1.0
    while(len(to_spawn) > 0):
        if random.randint(0, 100) <= random.expovariate(1 / rate):
            x, y = self.get_spawn_pos()
            fn, params = to_spawn.pop()
            if params:
                fn(self, *params)
            else:
                self.enemies.append(fn(self, x, y))
        yield True
    yield one_mid_two 
Example 75
Project: ocs-monkey   Author: JohnStrunk   File: osio.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def execute(self) -> 'List[Event]':
        """Create a new Deployment & schedule it's destruction."""
        destroy_time = time.time() + random.expovariate(1/self._lifetime)
        manifests = _get_workload(self._namespace, self._storage_class,
                                  self._access_mode, self._kernel_slots,
                                  self._kernel_untar, self._kernel_rm,
                                  self._workload_image)
        pvc = manifests["pvc"]
        deploy = manifests["deployment"]
        # Set necessary accotations on the Deployment
        anno = deploy["metadata"].setdefault("annotations", {})
        anno["ocs-monkey/osio-active"] = str(self._active)
        anno["ocs-monkey/osio-idle"] = str(self._idle)
        anno["ocs-monkey/osio-destroy-at"] = str(destroy_time)
        anno["ocs-monkey/osio-pvc"] = pvc["metadata"]["name"]
        deploy["metadata"]["annotations"] = anno
        LOGGER.info("Create: %s/%s, %s",
                    deploy["metadata"]["namespace"],
                    deploy["metadata"]["name"],
                    pvc["metadata"]["name"])
        core_v1 = k8s.CoreV1Api()
        kube.call(core_v1.create_namespaced_persistent_volume_claim,
                  namespace=pvc["metadata"]["namespace"],
                  body=pvc)
        apps_v1 = k8s.AppsV1Api()
        kube.call(apps_v1.create_namespaced_deployment,
                  namespace=deploy["metadata"]["namespace"],
                  body=deploy)
        EXECUTOR.submit(_pod_start_watcher, deploy)
        return [
            Lifecycle(when=0,  # execute asap
                      namespace=deploy["metadata"]["namespace"],
                      name=deploy["metadata"]["name"],
                      ),
            Creator(self._namespace,
                    self._storage_class,
                    self._access_mode,
                    self._interarrival,
                    self._lifetime,
                    self._active,
                    self._idle,
                    self._kernel_slots,
                    self._kernel_untar,
                    self._kernel_rm,
                    self._workload_image)
        ] 
Example 76
Project: nanopores   Author: mitschabaude   File: run_old.py    MIT License 4 votes vote down vote up
def run(params=params):
    X = np.array([0.])
    Y = np.array([0.])
    Z = np.array([params["z0"]])
    J1 = np.array([])
    T = np.array([])
    avgbind=params["avgbind"]
    P_bind=params["P_bind"]
    ffa = True
    i=0
    while i<maxiter and Z[-1]>=-hpore/2.-2.:
        xi_x=gauss(0.,1.)
        xi_y=gauss(0.,1.)
        xi_z=gauss(0.,1.)
        Force = F
	[[Dxfac, Dyfac, Dzfac],[DDx,DDy,DDz]]=D(X[-1],Y[-1],Z[-1])
#        x_new = X[-1] + coeff*xi_x*math.sqrt(abs(Dxfac)) + C*Force[0]*Dxfac + DDx*tau*Dmol
#        y_new = Y[-1] + coeff*xi_y*math.sqrt(abs(Dyfac)) + C*Force[1]*Dyfac + DDy*tau*Dmol
#        z_new = Z[-1] + coeff*xi_z*math.sqrt(abs(Dzfac)) + C*Force[2]*Dzfac + DDz*tau*Dmol
        x_new = X[-1] + coeff*xi_x + C*Force[0]
        y_new = Y[-1] + coeff*xi_y + C*Force[1]
        z_new = Z[-1] + coeff*xi_z + C*Force[2]
        if dis(argument(x_new,y_new,z_new)) < rMolecule:
            x_new = X[-1]
            y_new = Y[-1]
            z_new = Z[-1]
            if ffa and np.random.binomial(1,P_bind)==1 and Z[-1]<=hpore/2.-h2 and Z[-1]>=-hpore/2.+1.:
                add=expovariate(lambd=1./avgbind)
            else:
                add=0.
            ffa = False
        elif dis(argument(x_new,y_new,z_new)) < rMolecule + beps:
            pass
        else:
            ffa = True
            add=tau
        X = np.append(X,x_new)
        Y = np.append(Y,y_new)
        Z = np.append(Z,z_new)
        if abs(Z[-1])>30.:
            print 'Traceback fehler????????????'
        J1=np.append(J1,J(Z[-1]))
        T =np.append(T,add)
        i+=1
        if not (Z[i]<=H/2. and Z[i]>=-H/2 and X[i] <=R/2 and X[i] >=-R/2 and Y[i] <=R/2 and Y[i] >=-R/2):
            break
    if i>=maxiter:
        print 'randomwalk: more than 1e6 steps!'
    X=[list(X)]
    Y=[list(Y)]
    Z=[list(Z)]
    T=[list(T)]
    J1=[list(J1)]
    print 'savefield'
    fields.save_fields("randomwalk7",params,T=T,J=J1) 
Example 77
Project: ez-segway   Author: thanh-nguyen-dang   File: flow_change_generator.py    Apache License 2.0 4 votes vote down vote up
def generate_traffic_matrix(id_nodes):
        tm = {}
        t_in = {}
        t_out = {}
        total_in = 0
        total_out = 0

        # generate the first N_1 values as random exponential variables
        for i in range(0, len(id_nodes) - 1):
            n = id_nodes[i]
            t_in[n] = random.expovariate(1)
            t_out[n] = random.expovariate(1)
            total_in += t_in[n]
            total_out += t_out[n]

        # adjust the matrix with the last element
        last = id_nodes[len(id_nodes) - 1]
        if total_in > total_out:
            t_in[last] = random.expovariate(1)
            total_in += t_in[last]
            t_out[last] = total_in - total_out
            total_out += t_out[last]
        else:
            t_out[last] = random.expovariate(1)
            total_out += t_out[last]
            t_in[last] = total_out - total_in
            total_in += t_in[last]

        # print "\ninput vector: %s\noutput vector: %s\n
        # total input traffic: %d\ntotal output traffic: %d"
        # %(t_in, t_out, total_in, total_out)

        # compute the traffic matrix according to the gravity model, see equation (1) in
        # "Simplifying the synthesis of Internet Traffic Matrices", M. Roughan, in CCR 2005

        max_vol = 0
        for n in id_nodes:
            tm[n] = {}
            for m in id_nodes:
                traffic_vol = (t_in[n] * t_out[m]) / total_in
                tm[n][m] = traffic_vol
                if max_vol < traffic_vol:
                    max_vol = traffic_vol

        return tm, max_vol 
Example 78
Project: ez-segway   Author: thanh-nguyen-dang   File: mul_flow_change_generator.py    Apache License 2.0 4 votes vote down vote up
def generate_traffic_matrix(self, id_nodes):
        tm = {}
        t_in = {}
        t_out = {}
        total_in = 0
        total_out = 0

        # generate the first N_1 values as random exponential variables
        for i in range(0, len(id_nodes) - 1):
            n = id_nodes[i]
            t_in[n] = random.expovariate(1)
            t_out[n] = random.expovariate(1)
            total_in += t_in[n]
            total_out += t_out[n]

        # adjust the matrix with the last element
        last = id_nodes[len(id_nodes) - 1]
        if total_in > total_out:
            t_in[last] = random.expovariate(1)
            total_in += t_in[last]
            t_out[last] = total_in - total_out
            total_out += t_out[last]
        else:
            t_out[last] = random.expovariate(1)
            total_out += t_out[last]
            t_in[last] = total_out - total_in
            total_in += t_in[last]

        # print "\ninput vector: %s\noutput vector: %s\n
        # total input traffic: %d\ntotal output traffic: %d"
        # %(t_in, t_out, total_in, total_out)

        # compute the traffic matrix according to the gravity model, see equation (1) in
        # "Simplifying the synthesis of Internet Traffic Matrices", M. Roughan, in CCR 2005

        max_vol = 0
        for n in id_nodes:
            tm[n] = {}
            for m in id_nodes:
                traffic_vol = (t_in[n] * t_out[m]) / total_in
                tm[n][m] = traffic_vol
                if max_vol < traffic_vol:
                    max_vol = traffic_vol

        return tm, max_vol 
Example 79
Project: Merc-01   Author: Secretmapper   File: levels.py    MIT License 4 votes vote down vote up
def two(self):
    points = 0
    wave_spawns = []
    c = [[0] * 2 + [1] * 2 + [2]]
    c = random.choice(sum(c, []))
    if c == 0:
        # adds everything to wave_spawns
        def add_to_spawn(horizontal):
            lst = spawn_zipping(self)
            wave_spawns.extend(lst)
            self.state.enemies.extend(lst)

        for x in xrange(3):
            for i in xrange(180):
                yield True
            self.callbacks.append(
                [add_to_spawn, 5, {'horizontal': True if x % 2 == 0 else False}])
        points = 500
    elif c == 1:
        spawn_corner(self)
        for i in xrange(360):
            yield True
        points = 200
    else:
        points = 2000

    def bouncer_bundle(self, x, y):
        x, y = self.get_spawn_pos(50)

        return [get_bouncer(self, x, y) for i in xrange(2)]

    choice = [(bouncer_bundle, 100, 20),
              (get_bouncer, 25, 50),
              (get_tracker, 50, 30),
              (get_evader,  100, 20)]
    to_spawn = get_spawn_list(points, choice)

    rate = 1.0
    while(len(to_spawn) > 0):
        clear_spawn(wave_spawns)
        if len(to_spawn) > 0 and random.randint(0, 100) <= random.expovariate(1 / rate):
            x, y = self.get_spawn_pos()
            fn, params = to_spawn.pop()
            if params:
                fn(self, *params)
            else:
                ret = fn(self, x, y)
                if ret:  # spawn_line hack
                    # incredible hackishness (bundles/list)
                    if hasattr(ret, '__len__'):
                        self.enemies.extend(ret)
                    else:
                        self.enemies.append(ret)
        yield True
    if self.state.target_score >= 7500:
        yield two_mid_three
    else:
        yield two 
Example 80
Project: Merc-01   Author: Secretmapper   File: levels.py    MIT License 4 votes vote down vote up
def five(self):
    points = 3500

    def bouncer_bundle(self, x, y):
        x, y = self.get_spawn_pos(50)

        return [get_bouncer(self, x, y) for i in xrange(10)]

    choice = [
        (bouncer_bundle, 50, 30),
        (get_tracker, 50, 60),
        (spawn_line, 100, 50),
        (get_splitter, 50, 50),
        (get_evader,  100, 40),
        (get_blackhole, 200, 30),
        (self.spawn_sin, 400, 20, ['old']),  # old not working with append
        (spawn_corner, 800, 21, [5, get_evader]),
    ]
    to_spawn = get_spawn_list(points, choice)

    rate = 1.0
    play_time = 0
    while(len(to_spawn) > 0):
        if random.randint(0, 100) <= random.expovariate(1 / rate) and len(self.state.enemies) <= 30:
            x, y = self.get_spawn_pos()
            fn, params = to_spawn.pop()
            if params:
                if params[0] == 'old':  # hack, for old (spawn_sin)
                    fn()
                else:
                    fn(self, *params)
            else:

                ret = fn(self, x, y)
                if ret:  # spawn_line hack
                    # incredible hackishness (bundles/list)
                    if hasattr(ret, '__len__'):
                        self.enemies.extend(ret)
                    else:
                        self.enemies.append(ret)
        play_time += 1
        yield True
    yield six