예제 #1
0
    def __init__(self, m, f, period, kind, lamb):
        self.turns = utils.generateTimes(kind, lamb, period)
        self.top = m + f
        self.people = dict()
        self.newSingles = []

        for _ in range(m):
            p = Person('m', utils.randint(0, 100) * 48)
            self.people[len(self.people) + 1] = p
            if p.age >= 12:
                self.newSingles.append(len(self.people))

        for _ in range(f):
            p = Person('f', utils.randint(0, 100) * 48)
            self.people[len(self.people) + 1] = p
            if p.age >= 12:
                self.newSingles.append(len(self.people))

        self.actual_time = 0
        self.period = period
        self.events = []
        self.couples = []
        self.singlesM = []
        self.singlesF = []
        self.totalDeaths = 0
        self.totalBirths = 0
예제 #2
0
def add_prefix(text):
    add_prefix_rnd = utils.randint(0, 100)
    if add_prefix_rnd < 50:
        return prefix[utils.randint(
            0,
            len(prefix) - 1)] + " " + text[0].lower() + text[1:]
    return text
예제 #3
0
def schedule_all():
    log.info("starting pws module...")
    # schedule the run job
    schedule.add_job(run,
                     'cron',
                     minute="*/" + str(conf["pws"]["publishing_interval"]),
                     second=utils.randint(1, 59),
                     args=[])
예제 #4
0
def schedule_all():
    # for each backup job
    for entry in conf["general"]["backup"]:
        # schedule the execution of the daily and weekly job
        if not entry["enabled"]: return
        log.info("Scheduling backup job " + entry["backup_id"])
        schedule.add_job(run,
                         'cron',
                         hour="0",
                         minute="30",
                         second=utils.randint(1, 59),
                         args=[entry["backup_id"], "daily"])
        schedule.add_job(run,
                         'cron',
                         day_of_week='sun',
                         hour="0",
                         minute="30",
                         second=utils.randint(1, 59),
                         args=[entry["backup_id"], "weekly"])
예제 #5
0
def randomk(x, k, state):
    y = x.flatten()
    low = np.uint64(0)
    high = np.uint64(len(y))
    indices = np.array([randint(low, high, state) for _ in range(k)],
                       dtype=np.uint64)
    vals = y[indices]
    y.fill(0)
    for idx, val in zip(indices, vals):
        y[idx] = val
    return y.reshape(x.shape)
예제 #6
0
def addComma(token, punctChar):
    orginal_length = len(token)
    comma_pointer = 0
    if len(token) > 1:
        while comma_pointer < orginal_length:
            comma_pointer += randint(1, orginal_length - 1)
            if comma_pointer < orginal_length:
                token = token[:comma_pointer] + \
                    punctChar + token[comma_pointer:]
                comma_pointer += 1
    return token
예제 #7
0
def translate_response(action):
    response = {'type': 'text', 'content': ''}
    request = action.split("|")
    what = request.pop(0)
    if what == "text":
        response["content"] = request[utils.randint(0, len(request) - 1)]
    elif what == "rule":
        response["content"] = add_prefix(
            alerter.run(request[0], request[1], notify=False))
    elif what == "chart":
        response["type"] = "chart"
        response["content"] = request[0] + "," + request[1]
    return response
예제 #8
0
def run():
	# schedule module summary report
	for module in conf["modules"]:
		if not module["enabled"]: continue
		if "daily_digest" not in module: continue
		if module["daily_digest"]:
			schedule.add_job(smtp.module_digest,'cron',hour="23",minute="55",second=utils.randint(1,59),args=[module["module_id"]])
			log.info("["+module['module_id']+"] scheduling daily module digest")
	# schedule alert summary report
	if conf["output"]["email"]["alerts_digest"]: 
		log.info("scheduling daily alert digest")
		schedule.add_job(smtp.alerts_digest,'cron',hour="0",minute="55",args=[])
	# run slack bot
	if conf["input"]["slack"]["enabled"]: schedule.add_job(slack.run,'date',run_date=datetime.datetime.now())
	# listen for voice commands
	if conf["input"]["audio"]["enabled"]: schedule.add_job(audio.listen,'date',run_date=datetime.datetime.now())
예제 #9
0
    def victory(self, player, attack_type):
        return super().victory(player)
        print("You have been defeated in combat by the bandit!")

        #randomly decide whether to kill the player or loot their body and leave them unconscious
        choice = utils.randint(1, 7)
        if choice == 1:
            print(
                "The bandit knocks you unconscious. You wake up on the floor where they left you, stripped of your clothes, weapons, and gold."
            )
        elif attack_type == "melee":
            print("The last thing you see is the bandit's " +
                  self.melee_weapon_name +
                  " being brought down on your head. You have been killed.")
        else:
            print("The bandit's " + self.ranged_weapon_name +
                  " delivers death from afar. You have been killed.")
def miller_rabin_primality_testing(n, k):
    # prevent potential infinite loop when d = 0
    if n < 2:
        return False

    # Decompose (n - 1) to write it as (2 ** r) * d
    # While d is even, divide it by 2 and increase the exponent.
    d = n - 1
    r = 0

    while not (d & 1):
        r += 1
        d >>= 1

    # Test k witnesses.
    for _ in range(k):
        # Generate random integer a, where 2 <= a <= (n - 2)
        a = utils.randint(n - 3) + 1

        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue

        for _ in range(r - 1):
            x = pow(x, 2, n)
            if x == 1:
                # n is composite.
                return False
            if x == n - 1:
                # Exit inner loop and continue with next witness.
                break
        else:
            # If loop doesn't break, n is composite.
            return False

    return True
예제 #11
0
 def get_price(self):
     return (self.tier * (5 + utils.randint(0, 10))) + utils.randint(1, 5)
예제 #12
0
 def gen_case():
     vals = types[randint(len(types))]
     return [vals[randint(len(vals))] for _ in range(randint(16) + 4)]
예제 #13
0
def get_wait_message():
    return wait[utils.randint(0, len(wait) - 1)]
예제 #14
0
 def roll(self):
     self.strength_roll = utils.randint(0, 10) + self.strength
     self.dexterity_roll = utils.randint(0, 10) + self.dexterity
     self.intellect_roll = utils.randint(0, 10) + self.intellect
     self.charisma_roll = utils.randint(0, 10) + self.charisma
예제 #15
0
def schedule_all():
    # init plugins
    init_plugins()
    log.info("setting up all the configured sensors")
    # for each module
    for module in conf["modules"]:
        if not module["enabled"]: continue
        # skip group without sensors
        if "sensors" not in module: continue
        for sensor in module["sensors"]:
            # check if the sensor is enabled
            if not sensor["enabled"]: continue
            # initialize the sensor data structure
            sensor = init_sensor(sensor)
            if sensor is None: continue
            # skip sensors without a plugin
            if 'plugin' not in sensor: continue
            # this plugin needs sensors to be registered with it first
            if hasattr(plugins[sensor['plugin']['plugin_name']], 'register'):
                # register the sensor
                log.debug("[" + sensor['module_id'] + "][" +
                          sensor['group_id'] + "][" + sensor['sensor_id'] +
                          "] registering with plugin service " +
                          sensor['plugin']['plugin_name'])
                plugins[sensor['plugin']['plugin_name']].register(sensor)
            # this plugin needs the sensor to be polled
            if "polling_interval" in sensor["plugin"]:
                # schedule polling
                log.debug("[" + sensor['module_id'] + "][" +
                          sensor['group_id'] + "][" + sensor['sensor_id'] +
                          "] scheduling polling every " +
                          str(sensor["plugin"]["polling_interval"]) +
                          " minutes")
                # run it now first
                if conf["sensors"]["poll_at_startup"]:
                    schedule.add_job(
                        run,
                        'date',
                        run_date=datetime.datetime.now() +
                        datetime.timedelta(seconds=utils.randint(1, 59)),
                        args=[
                            sensor['module_id'], sensor['group_id'],
                            sensor['sensor_id'], 'save'
                        ])
                # then schedule it for each refresh interval
                schedule.add_job(run,
                                 'cron',
                                 minute="*/" +
                                 str(sensor["plugin"]["polling_interval"]),
                                 second=utils.randint(1, 59),
                                 args=[
                                     sensor['module_id'], sensor['group_id'],
                                     sensor['sensor_id'], 'save'
                                 ])
            # schedule an expire job every day
            schedule.add_job(run,
                             'cron',
                             hour="1",
                             minute="0",
                             second=utils.randint(1, 59),
                             args=[
                                 sensor['module_id'], sensor['group_id'],
                                 sensor['sensor_id'], 'expire'
                             ])
            # schedule a summarize job every hour and every day if needed
            if "summarize" in sensor:
                log.debug("[" + sensor['module_id'] + "][" +
                          sensor['group_id'] + "][" + sensor['sensor_id'] +
                          "] scheduling summary every hour and day")
                schedule.add_job(run,
                                 'cron',
                                 minute="0",
                                 second=utils.randint(1, 59),
                                 args=[
                                     sensor['module_id'], sensor['group_id'],
                                     sensor['sensor_id'], 'summarize_hour'
                                 ])
                schedule.add_job(run,
                                 'cron',
                                 hour="0",
                                 minute="0",
                                 second=utils.randint(1, 59),
                                 args=[
                                     sensor['module_id'], sensor['group_id'],
                                     sensor['sensor_id'], 'summarize_day'
                                 ])
    # start all the plugin services
    start_plugins()