def change_weights(self, mutate): for weight in self.weights: shape = weight.shape for r in range(shape[0]): for c in range(shape[1]): prob = randfloat(0, 1) change = 0 if prob+mutation_rate >= 1: change = randfloat(-mutate, mutate) weight[r][c] += change
def update(self): delta: vec2 = (self.target_pos - self.pos).normalized() self.direction = delta.normalized() self.update_animation() if (self.target_pos - self.pos).__len__() <= self.finish_dist(): self.target_pos = self.pos self.is_move_finished = True else: self.pos += delta * self.move_speed * GAME_DELTATIME * GAME_TIME_SCALE if not self.is_move_finished: return if self.is_gathering: if self.gather_obj is None: self.wander_at(self.pos) self.update() return if abs(self.pos - self.gather_obj.pos).__len__() < self.finish_dist(): if self.gather_obj.empty(): self.wander_at(self.pos + vec2(randfloat(0.5, 1), randfloat(0.5, 1)) * 50) self.update() return self.inner_counter += 1 if (GAME_DELTATIME * self.inner_counter) >= ( self.gather_period / GAME_TIME_SCALE): self.inner_counter = 0 self.inventory.append( self.gather_obj.take(self.inventory_capacity)) self.target_pos = self.camp_obj.pos elif abs(self.pos - self.camp_obj.pos).__len__() < self.finish_dist(): self.target_pos = self.gather_obj.pos for el in self.inventory: self.camp_obj.res_amounts[el[0]] += el[1] self.inventory.clear() return if self.is_wandering: self.inner_counter += 1 self.is_moving = False if (GAME_DELTATIME * self.inner_counter) >= (randfloat(0.5, 1.5) / GAME_TIME_SCALE): self.inner_counter = 0 self.target_pos = ( self.wandering_pos + vec2(randfloat(-0.5, 0.5), randfloat(-0.5, 0.5)) * self.wandering_radius) self.is_moving = True self.is_move_finished = False
def UpdateNetwork(self): TweakLowerBound = -1 TweakUpperBound = 1 for i in self.InputLayer: i.Threshold += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.InputToHidden1Links: i.Multiplier += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.HiddenLayer1: i.Threshold += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.Hidden1ToHidden2Links: i.Multiplier += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.HiddenLayer2: i.Threshold += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.Hidden2ToHidden3Links: i.Multiplier += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.HiddenLayer3: i.Threshold += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.Hidden3ToOutputLinks: i.Multiplier += Decimal(randfloat(TweakLowerBound, TweakUpperBound)) for i in self.OutputLayer: i.Threshold += Decimal(randfloat(TweakLowerBound, TweakUpperBound))
def generate_weights(mother_w, father_w, shape): child_w = [] for i in range(len(mother_w)): mf = randint(0, 1) mutation = randfloat(0, 1) change = 0 if mutation_rate + mutation >= 1: change = randfloat(-1, 1) if mf == 0: child_w.append(mother_w[i] + change) else: child_w.append(father_w[i] + change) return np.asarray(child_w).reshape(shape)
def rouletteWheelSelect(population, SCORES, scorefunc, scoreparams, N): """ Select N unique individuals from the population based on roulette wheel selection. If there are not at least N individuals in the population, ValueError is raised """ if len(population) < N: raise ValueError("Cannot Select %d individuals from a population of %d" %(N, len(population))) # print 'getting wheel' ## wheel = getRouletteWheel(population, SCORES, scorefunc, scoreparams) # print 'got wheel' ## answer = [] selection = set([]) while N: # print 'while', N ## try: # print 'trying' ## r = randfloat(-1,0) slot = (s for s in wheel if s[1]<=r<=s[0]).next() answer.append(wheel[slot]) selection.add(slot) N -= 1 except: # print 'excepting' ## print r for slot in wheel: print slot raise crash() return answer
def randHsv(): return [ randint(0, 360), randint(40, 80), randint(20, 80), randfloat(0, 0.5) ]
def do_work(counter, lock, queue, df): name = multiprocessing.current_process().name new_data = [] # this will store processed data made_by = [] timestamp = [] for data in df["data"]: # not discussing df.applymap() here new_data.append(data ** 3) # we're transforming our input data made_by.append(name) timestamp.append(time.ctime()) # counter update with lock: counter.value += 1 time.sleep(randfloat(0.1, 1)) print("worker:", name, "reports: WORK DONE") new_df = pd.DataFrame({"old_data" : df["data"], "new_data" : new_data, "made_by" : made_by, "timestamp" : timestamp } ) queue.put(new_df)
def random_symbol(weights): ceil = reduce(lambda x, y: x + y, [x[1] for x in weights]); while True: thresh = randfloat(0, ceil); print "thresh = %s"%thresh; s = reduce(lambda x, y: (x[1] + y[1]) if isinstance(x, int) and x < ceil else x, weights); yield s
def generate_obstacle(self): random_pos = int(randfloat(self.size / 2 + Constants.circCenter_x - Constants.circRadius, Constants.screen_width - (self.size / 2 + Constants.circCenter_x - Constants.circRadius))) star = Star(Vector2(random_pos, -self.size), self.size, Material(Color.yellow)) self.game_object_list.append(star)
def selectBestActionProb(actionVector, probChoosingRandom): prob = random.randfloat(0, 1) if prob > probChoosingRandom: randAction = random.randint(0, len(actionVector) - 1) return randAction else: return actionVector.index(max(actionVector))
def sample_one(items): roll = randfloat() curr = 0.0 for (item, prob) in items: #print roll, curr, '\t', prob curr += prob if roll <= curr: return item return item
def mutate(p, mutprob): answer = [] for g in p: if randfloat(0,1) <= mutprob: answer.append((int(g) +1) %2) else: answer.append(g) return ''.join(str(i) for i in answer)
def generate_obstacle(self): random_pos = int(randfloat(self.radius + Constants.circCenter_x - Constants.circRadius, Constants.screen_width - (self.radius + Constants.circCenter_x - Constants.circRadius))) circle = InvencibleCircle(Vector2(random_pos, -2 * self.radius), self.radius, Material(Color.purple)) self.game_object_list.append(circle)
def crossover(p1, p2, crossprob): G = len(p1) crosspoint = randint(0,G-1) if randfloat(0,1) <= crossprob: c1 = p1[:crosspoint] + p2[crosspoint:] c2 = p2[:crosspoint] + p1[crosspoint:] return c1, c2 else: return p1, p2
def test_bo_observation_added(): observations = list() for index, param_config in enumerate(BO.searchspace): observation = randfloat(0.1, 10) observations.append(observation) BO.update_after_evaluation(observation, index, param_config) assert BO.is_valid(observation) assert len(observations) == index + 1 assert len(BO.unvisited_cache) == len(BO.searchspace) - index - 1 assert BO.current_optimum == min(observations)
def expectedgood(self, output, place, abit=False): """ output = np.copy(output[0]) expected = [0]*len(output) output = output.tolist() expected[output.index(max(output))] = 1 """ place = place - 1 expected = np.copy(output[0]) expected = expected.tolist() if abit: expected[place] += randfloat(0.1, 0.2) else: expected[place] += randfloat(0.01, 0.1) #for i in range(len(expected)): # if i != place: # expected[i] = 0 #""" return [expected]
def symbol_gnrt(weights): ceil = reduce(lambda x, y: x + y, [x[1] for x in weights]); while True: thresh = randfloat(0, ceil); #print "tttthresh = %s"%thresh; x = 0; for t in weights: x += t[1]; if (x > thresh): yield t[0] break;
def should_step_get_rejected(self, standardError): """ Given a standard error, return whether to keep or reject new standard error according to the constraint reject probability function. :Parameters: #. standardError (number): Standard error to compare with the Constraint standard error. :Return: #. result (boolean): True to reject step, False to accept. """ previousRatio = 1 - (self.standardError / self.__maximumStandardError) currentRatio = 1 - (standardError / self.__maximumStandardError) if currentRatio >= self.__thresholdRatio: # must be accepted return False elif previousRatio >= self.__thresholdRatio: # it must be rejected return randfloat() < self.rejectProbability elif standardError <= self.standardError: # must be accepted return False else: # must be rejected return randfloat() < self.rejectProbability
def trokut(i): t.pu() ## randomizirano generiranje tocaka a = random(-400, 400), random(-400, 400) b = random(-400, 400), random(-400, 400) c = random(-400, 400), random(-400, 400) ## nasumicno generiranje boje clr = randfloat(), randfloat(), randfloat() t.color(clr) t.width(5) ## provjera je li pravi trokut i crtanje ako je if pravi(a, b, c): lista.append(i) n += 1 t.goto(a) t.pd() t.goto(b) t.goto(c) t.goto(a)
def should_step_get_rejected(self, standardError): """ Given a standardError, return whether to keep or reject new standardError according to the constraint rejectProbability. :Parameters: #. standardError (number): The standardError to compare with the Constraint standardError :Return: #. result (boolean): True to reject step, False to accept """ if self.standardError is None: raise Exception(LOGGER.error("must compute data first")) if standardError<=self.standardError: return False return randfloat() < self.__rejectProbability
def drawOneCircle(x, y, radius, h, s, v, opacity): randOpacity = round(randfloat(0.3, opacity), 3) randOpacity2 = round(randfloat(0.1, (opacity * 0.5)), 3) env = Environment(autoescape=False) if (radius < 3): tpl = env.from_string(""" <circle r="{{ radius }}%" cx="{{ x }}%" cy="{{ y }}%" fill="hsla({{ h }}, {{ s }}%, 90%, {{ randOpacity }})" > </circle> <circle r="{{ radius }}%" cx="{{ x }}%" cy="{{ y }}%" fill="none" stroke="white" stroke-opacity="{{ randOpacity2 }}" > </circle> """) else: tpl = env.from_string(""" <circle r="{{ radius }}%" cx="{{ x }}%" cy="{{ y }}%" fill="hsla({{ h }}, {{ s }}%, 90%, {{ randOpacity2 }})" filter="url(#blur)" > </circle> """) return tpl.render(x=x, y=y, radius=radius, h=h, s=s, v=v, randOpacity=randOpacity, randOpacity2=randOpacity2)
def generate_obstacle(self): random_pos = int(randfloat(self.size / 2 + Constants.circCenter_x - Constants.circRadius, Constants.screen_width - (self.size / 2 + Constants.circCenter_x - Constants.circRadius))) rect = Rectangle(Vector2(random_pos, -self.size), Vector2(self.size, self.size), Material((255, 255, 255))) rect.animation = ObstaclePulsingAnimation(rect) rect.animator = Animator(rect, [rect.animation]) rect.animator.play() direction = randint(0, 1) if direction == 0: direction = -1 rect.vel = direction # Checks if going left or right. Can be 1 for right or -1 for left self.game_object_list.append(rect)
def expectedgood(self, output, val=0.1): """ output = np.copy(output[0]) expected = [0]*len(output) output = output.tolist() expected[output.index(max(output))] = 1 """ expected = np.copy(output[0]) expected = expected.tolist() place = expected.index(max(expected)) expected[place] += randfloat(0.1, 0.2) #for i in range(len(expected)): # if i != place: # expected[i] = 0 #""" return [expected]
def expected(self, output): #""" expected = np.copy(output[0]) expected = expected.tolist() place = expected.index(max(expected)) expected[place] = 0 for i in range(len(expected)): if i != place: expected[i] += randfloat(0.01, 0.1) """ output = np.copy(output[0]) expected = [1] * len(output) output = output.tolist() expected[output.index(max(output))] = 0 """ return [expected]
async def scrutinize_messages(self, message): channel = message.channel user = message.author if hasattr(user, 'bot') and user.bot is True: return if channel.id not in self.flippedTables: self.flippedTables[channel.id] = {} #┬─┬ ┬┬ ┻┻ ┻━┻ ┬───┬ ┻━┻ will leave 3 tables left flipped #count flipped tables for m in re.finditer('┻━*┻|┬─*┬', message.content): t = m.group() if '┻' in t and not (message.author.id == self.bot.user.id and self.settings["BOT_EXEMPT"]): if t in self.flippedTables[channel.id]: self.flippedTables[channel.id][t] += 1 else: self.flippedTables[channel.id][t] = 1 if not self.settings["ALL_TABLES"]: break else: f = t.replace('┬', '┻').replace('─', '━') if f in self.flippedTables[channel.id]: if self.flippedTables[channel.id][f] <= 0: del self.flippedTables[channel.id][f] else: self.flippedTables[channel.id][f] -= 1 #wait random time. some tables may be unflipped by now. await asyncio.sleep(randfloat(0, 1.5)) tables = "" deleteTables = [] #unflip tables in self.flippedTables[channel.id] for t, n in self.flippedTables[channel.id].items(): unflipped = t.replace('┻', '┬').replace('━', '─') + " ノ( ゜-゜ノ)" + "\n" for i in range(0, n): tables += unflipped #in case being processed in parallel self.flippedTables[channel.id][t] -= 1 deleteTables.append(t) for t in deleteTables: del self.flippedTables[channel.id][t] if tables != "": await self.bot.send_message(channel, tables)
def _gen_graph(username: str) -> nx.DiGraph: log = logging.getLogger('_gen_graph') # TODO text = f'partial key #4:' node_indices = tuple(range(0, len(text))) node_data = ((idx, {'key': text[idx]}) for idx in node_indices) edge_data = ((source, target, randfloat()) for source, target in itertools.zip_longest( node_indices[1:], node_indices[:-1])) graph = _create_graph(node_data, edge_data) seed: int = sum(map(ord, username)) log.debug(f'seed for username {username} is {seed}') graph = _obfuscate_graph(graph, seed) return graph
async def scrutinize_messages(self, message): channel = message.channel user = message.author if hasattr(user, 'bot') and user.bot is True: return if channel.id not in self.flippedTables: self.flippedTables[channel.id] = {} #┬─┬ ┬┬ ┻┻ ┻━┻ ┬───┬ ┻━┻ will leave 3 tables left flipped #count flipped tables for m in re.finditer('┻━*┻|┬─*┬', message.content): t = m.group() if '┻' in t and not (message.author.id == self.bot.user.id and self.settings["BOT_EXEMPT"]): if t in self.flippedTables[channel.id]: self.flippedTables[channel.id][t] += 1 else: self.flippedTables[channel.id][t] = 1 if not self.settings["ALL_TABLES"]: break else: f = t.replace('┬','┻').replace('─','━') if f in self.flippedTables[channel.id]: if self.flippedTables[channel.id][f] <= 0: del self.flippedTables[channel.id][f] else: self.flippedTables[channel.id][f] -= 1 #wait random time. some tables may be unflipped by now. await asyncio.sleep(randfloat(0,1.5)) tables = "" deleteTables = [] #unflip tables in self.flippedTables[channel.id] for t, n in self.flippedTables[channel.id].items(): unflipped = t.replace('┻','┬').replace('━','─') + " ノ( ゜-゜ノ)" + "\n" for i in range(0,n): tables += unflipped #in case being processed in parallel self.flippedTables[channel.id][t] -= 1 deleteTables.append(t) for t in deleteTables: del self.flippedTables[channel.id][t] if tables != "": await self.bot.send_message(channel, tables)
def Répondre2(Entrée, Phrases): Dico = {} l = len(Phrases) for i in range(l): Dico[str(Rsb(Phrases[i], Entrée))] = i Progression(i, 0, l) Ressemblances = list(Dico) Ressemblances.sort() Ressemblances.reverse() Proba = [] for i in range(len(Liste)): Proba.append(Ressemblances[i] / 2**i) r = random.randfloat(0, len(sum(Proba))) i = 0 n = 0 while i < r: i += Proba[n] n += 1 Sortie = Phrases[Dico[Ressemblances[i]] + 1] return Sortie
def create_float(self): return randfloat() * randint(1, 100)
import random hidden_number = random.randfloat(0, 1) user_guess = 0 while not user_guess == hidden_number: user_guess = int(input("Guess a number:")) if user_guess > hidden_number: print("Too high!") elif user_guess < hidden_number: print("Too low!") else: print("Thats right!")
def random(cls): return Color(randfloat(), randfloat(), randfloat(), 1.0)
def add_device(self, device): """ Add a device to the managed list and announce it. Multiple hierarchies are not supported and must be handled separately. :param device: UPnP host device :return: (bool) True if added successfully :since: v0.2.00 """ if (self.log_handler is not None): self.log_handler.debug("#echo(__FILEPATH__)# -{0!r}.add_device()- (#echo(__LINE__)#)", self, context = "pas_upnp") _return = True if (isinstance(device, Device) and device.is_managed()): with self.lock: device_identifier = Device.get_identifier(device.get_usn(), self.bootid, self.configid) if (device_identifier is not None and device_identifier['usn'] not in self.usns): if (self.log_handler is not None): self.log_handler.info("pas.upnp.ControlPoint adds UPnP device USN '{0}'", device_identifier['usn'], context = "pas_upnp") if (device_identifier['device'] not in self.rootdevices): self.rootdevices.append(device_identifier['device']) device_identifier['url_desc'] = device.get_desc_url() self.managed_devices[device_identifier['uuid']] = device self.usns[device_identifier['usn']] = device_identifier self._remove_task(device_identifier['usn'], "deliver_event") if (self.configid < 16777216): self.configid += 1 else: self.configid = 0 wait_seconds = randfloat(0.2, 0.4) event = ControlPointEvent(ControlPointEvent.TYPE_DEVICE_ALIVE, control_point = self) event.set_usn(device_identifier['usn']) event.set_location(device_identifier['url_desc']) event.schedule(wait_seconds) Hook.call("dNG.pas.upnp.ControlPoint.onHostDeviceAdded", identifier = device_identifier) embedded_device_uuids = device.get_embedded_device_uuids() for uuid in embedded_device_uuids: embedded_device = device.get_embedded_device(uuid) embedded_device_identifier = Device.get_identifier(embedded_device.get_usn(), self.bootid, self.configid) if (self.log_handler is not None): self.log_handler.info("pas.upnp.ControlPoint adds UPnP device USN '{0}'", embedded_device_identifier['usn'], context = "pas_upnp") embedded_device_identifier['url_desc'] = embedded_device.get_desc_url() self.managed_devices[embedded_device_identifier['uuid']] = embedded_device self.usns[embedded_device_identifier['usn']] = embedded_device_identifier wait_seconds = randfloat(0.4, 0.6) event = ControlPointEvent(ControlPointEvent.TYPE_DEVICE_ALIVE, control_point = self) event.set_usn(embedded_device_identifier['usn']) event.set_location(embedded_device_identifier['url_desc']) event.schedule(wait_seconds) Hook.call("dNG.pas.upnp.ControlPoint.onHostDeviceAdded", identifier = embedded_device_identifier) # if (self.gena is None): self.gena = Gena.get_instance() self.gena.start() # else: _return = False # else: _return = False return _return
def randomNormalizedPrice(): price = 0 while price < 0.0101 or price > 0.9899: price = randfloat() return price
def handle_request(source_data, source_wait_timeout, search_target, additional_data = None): """ Searches for hosted devices matching the given UPnP search target. :param source_data: UPnP client address data :param source_wait_timeout: UPnP MX value :param search_target: UPnP search target :param additional_data: Additional data received :since: v0.2.00 """ condition = None condition_identifier = None if (search_target == "ssdp:all" or search_target == "upnp:rootdevice" or search_target.startswith("uuid:")): condition = search_target elif (search_target.startswith("urn:")): condition = search_target condition_identifier = Device.get_identifier("uuid:00000000-0000-0000-0000-000000000000::{0}".format(search_target), None, None) elif (len(search_target) > 41): condition = search_target condition_identifier = Device.get_identifier(search_target, None, None) # results = [ ] if (condition is not None): control_point = ControlPoint.get_instance() if (condition_identifier is None and condition == "upnp:rootdevice" ): results += SsdpSearch._get_rootdevice_results(condition) else: managed_devices = control_point.get_managed_devices() for uuid in managed_devices: device = managed_devices[uuid] results += SsdpSearch._handle_device_search(condition, condition_identifier, uuid, device ) if (condition == "ssdp:all" or (condition_identifier is not None and condition_identifier['class'] == "service") ): services = device.get_service_ids() for service_id in services: service = device.get_service(service_id) results += SsdpSearch._handle_service_search(condition, condition_identifier, service, device ) # # embedded_devices = device.get_embedded_device_uuids() for embedded_uuid in embedded_devices: embedded_device = device.get_embedded_device(embedded_uuid) results += SsdpSearch._handle_device_search(condition, condition_identifier, embedded_uuid, embedded_device ) if (condition_identifier is not None and condition_identifier['class'] == "service"): services = embedded_device.get_service_ids() for service_id in services: service = embedded_device.get_service(service_id) results += SsdpSearch._handle_service_search(condition, condition_identifier, service, embedded_device ) # # # # # if (len(results) > 0): if (additional_data is not None): if ('USER-AGENT' in additional_data): client_settings = ClientSettings(additional_data['USER-AGENT']) source_wait_timeout = client_settings.get("ssdp_upnp_search_wait_timeout", source_wait_timeout) elif (source_wait_timeout < 4): # Expect broken clients if no user-agent is given and MX is too small source_wait_timeout = 0 # if (source_wait_timeout > 0): wait_seconds = randfloat(0, (source_wait_timeout if (source_wait_timeout < 10) else 10) / len(results) ) else: wait_seconds = 0 for result in results: event = ControlPointEvent(ControlPointEvent.TYPE_SEARCH_RESULT, control_point = control_point) event.set_usn(result['usn']) event.set_location(result['location']) event.set_search_target(result['search_target']) event.set_response_target(("[{0}]".format(source_data[0]) if (":" in source_data[0]) else source_data[0]), source_data[1] ) event.schedule(wait_seconds)
def punish(self, output, pos): expected = output[:] expected[pos - 1] = 0 for i in range(len(expected)): if i != pos - 1: expected[i] += randfloat(0.01, 0.1)
def random_value(self) -> float: """Generate a random value within the range allowed by this quantity.""" return self.minimum + random.randfloat(0, self.variance)
def swing_max(self): return self.self_control + randfloat(-self.unpredictability, self.unpredictability)
resPlace = 0 clock = pygame.time.Clock() while not m_quit: for ev in pygame.event.get(): if ev.type == pygame.QUIT: m_quit = True break if ev.type == pygame.MOUSEBUTTONDOWN: if ev.button == pygame.BUTTON_RIGHT: res = get_resource_copy(resPlace) res.pos = vec2(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]) if resPlace == 1 or resPlace == 0: res.fill(50, refresh_time=60 + 120 * randfloat(0, 1)) else: res.fill(100) mainCamp.register_resource(res) elif ev.button == pygame.BUTTON_WHEELUP: if resPlace < (GAME_RESOURCES.__len__() - 1): resPlace += 1 elif ev.button == pygame.BUTTON_WHEELDOWN: if resPlace >= 1: resPlace -= 1 elif ev.type == pygame.KEYDOWN: if ev.key == pygame.K_ESCAPE: m_quit = True break if ev.key == pygame.K_SPACE: GAME_TIME_SCALE = 5.0