def select_parents(rw): rw_co = list(rw) poppp = list() while True: r1 = random.randrange(0, len(rw_co), 1) p1 = rw_co[r1] # print(r, end=" ") r2 = random.randrange(0, len(rw_co), 1) p2 = rw_co[r2] if p1 != p2: poppp.append([p1, p2]) rw_co = list(filter(lambda a: a != p2, rw_co)) rw_co = list(filter(lambda a: a != p1, rw_co)) if len(list(set(rw_co))) == 1: p1 = rw_co[-1] p2 = rw[0] poppp.append([p1, p2]) return poppp # rw_co = list(filter(lambda a: a != p2, rw_co)) # rw_co = list(filter(lambda a: a != p1, rw_co)) if len(list(set(rw_co))) <= 1: return poppp
async def timed_affirmation(self, ctx: Context): """Invoking this script will start a timer. Every few minutes I'll take the channel through a breathing exercise and then finish with a picture of something cute.""" while self.bot.is_ready(): affirmations = self._affirm_list.get_all_records() upper = len(affirmations) call_affirmation_number = random.randrange(2, upper) self._affirm_list.update_cell(1, 8, call_affirmation_number) cell = self._affirm_list.cell(call_affirmation_number, 1).value await ctx.send("Breathe in for four ... ", delete_after=20) await asyncio.sleep(6) await ctx.send("Hold for four ... ", delete_after=20) await asyncio.sleep(6) await ctx.send("Breathe out for six ... ", delete_after=20) await asyncio.sleep(8) await ctx.send("An affirmation I sometimes use is - " + cell, delete_after=20) current_value = int( self._affirm_list.cell(call_affirmation_number, 5).value) self._affirm_list.update_cell(call_affirmation_number, 5, current_value + 1) with open("calm_posts.json", "r") as source: pic_container = json.load(source) pic_list = pic_container["images"] pic_hit = random.randrange(1, len(pic_list)) dict_pic = pic_list[pic_hit] v = dict_pic.get('url') await asyncio.sleep(20) await ctx.channel.purge(limit=4) await asyncio.sleep(20) await ctx.channel.send(v) await ctx.channel.send("Here's some cute, I hope it helps.", delete_after=20) await asyncio.sleep(490)
def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): """Construct a random graph, with the specified nodes, and random links. The nodes are laid out randomly on a (width x height) rectangle. Then each node is connected to the min_links nearest neighbors. Because inverse links are added, some nodes will have more connections. The distance between nodes is the hypotenuse times curvature(), where curvature() defaults to a random number between 1.1 and 1.5.""" g = UndirectedGraph() g.locations = {} # Build the cities for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) # Build roads from each city to at least min_links nearest neighbors. for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return math.inf return distance(g.locations[n], here) neighbor = nodes.index(min(nodes, key=distance_to_node)) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g
def reproductionTime(self): totalChromToGenerate = self.totalChromosomesXCriature - len(self.chrom_list_selected) # ready to cross some chromosomes to reproduce p = [] for i in self.chrom_list_rest: p.append(self.chromosomesToArray(i)) print(p) for i in range(0,totalChromToGenerate): iFather = 0 iMother = 1 # loop until find a random numbers not equal father and mother while iFather !=iMother and len(p)>2: iFather = random.randrange(0,len(p)) iMother = random.randrange(0,len(p)) # father lower number because is the better gen if iFather!=iMother: if iFather > iMother: pFather = p[iMother] pMonther = p[iFather] else: pFather = p[iFather] pMonther = p[iMother] # cross methods : PURE - 50% if math.ceil(totalChromToGenerate/2)<i: newGenReproduced = genetic_cross(pFather,pMonther,"pure", self.totalGens) # cross methods : Same Level - 25% elif math.floor((totalChromToGenerate/2)/2< i-math.ceil(totalChromToGenerate/2)): newGenReproduced = genetic_cross(pFather,pMonther,"same_level", self.totalGens) # cross methods : Inferior Level - 25% else: newGenReproduced = genetic_cross(pFather,pMonther,"inferior_level", self.totalGens) # add new gen To Array self.chrom_reproduced.append(newGenReproduced)
def colour_generator(self): r = random.randrange(0, 250) g = random.randrange(0, 255) b = random.randrange(0, 255) a=random.randrange(120,256) return (r, g, b,a)
def gerarListasDiferentesTamanhos(): import random # IMPORT necessário dentro da class para gerar numeros aleatórios (random.randint) try: # Variaveis tam1 = int(input("Informe o tamanho da primeira lista \n")) tam2 = int(input("Informe o tamanho da segunda lista \n")) i = 0 L1 = [] L2 = [] L3 = [] while True: # Realizo um while continuo. até que todas as interações necessárias # do meu laço, sejam realizadas. if len( L1 ) < tam1: # Verifico o tamanho da lista 1 com relação ao padrão adotado. value = random.randrange(0, 100) L1.append(value) elif len( L2 ) < tam2: # Verifico o tamanho da lista 2 com relação ao padrão adotado. value = random.randrange(0, 100) L2.append(value) else: print("Lista 1 de tamanho {0} e elementos: {1} \n".format( tam1, L1)) print("Lista 2 de tamanho {0} e elementos: {1} \n".format( tam1, L2)) break except ValueError: print("Os Valores devem ser do tipo inteiro (INT)") else: # Após realização das condições do try. Realizo a operação abaixo L3 = L1 + L2 # Alimento uma terceira lista finally: # Finalizo. Exibo dados tratados no final if len(L3) > 0: print("Lista Ordenada: ") L3.sort() # exibo a lista com seus valores em ordem crescente print(L3) callback = str( input('Deseja Realizar novamente a operação S OU N' )) # Atribuo a possibilidade de retonar ao inicio da função. if callback == 'S': gerarListasDiferentesTamanhos() print("Registro de operações realizadas no METODO!!!")
def mutate_motif_with_dirty_bits((motif,ics)): length = len(motif[0]) num_sites = len(motif) i = random.randrange(num_sites) j = random.randrange(length) site = motif[i] b = site[j] new_b = random.choice([c for c in "ACGT" if not c == b]) new_site = subst(site,new_b,j) new_motif = [site if k != i else new_site for k,site in enumerate(motif)] jth_column = transpose(new_motif)[j] jth_ic = 2-dna_entropy(jth_column) new_ics = subst(ics,jth_ic,j) return new_motif,new_ics
def create_random_graph(self, n_verts): # create some verts and put them in a grid grid = [] for i in range(n_verts): grid.append(Vertex(str(i))) #randomly looping through verts and randomly connecting it to the next one with randomized mulidirection for i in range(n_verts - 1): if(random.randrange(n_verts) < n_verts // 2): if(random.randrange(n_verts) < n_verts // 2): self.add_edge(grid[i].label, grid[i+1].label, False) self.add_edge(grid[i].label, grid[i+1].label) for vert in grid: self.add_vertex(vert)
def __init__(self, personalidad): super().__init__(personalidad) # Estas son properties ya que tienen condiciones de no ser menores a 0 self.personalidad = personalidad self.destino = None self.dinero = 1 self.dinero_entrada = self.dinero self.lucidez = 0 self.suerte = 0 self.sociabilidad = 0 self.ansiedad = 0 self.stamina = 0 self.deshonestidad = 0 self.tiempo = 0 self.tiempo_espera = 0 self.prediciendo = False self.nombre = random.choice( [get_first_name("male"), get_first_name("female")]) self.apellido = get_last_name() self.edad = random.randrange(18, 90) self.acciones = acciones self.accion = None self.probabilidad_ganar = 0 self.estado = False self.get_x = 0 self.get_y = 0 self.quiere_ = False self.a_conversado = 0 self.pillado = False self.coludido = False self.sin_dinero = False self.pozo_casino = 0 self.tick_de_llegada = 0 self.tick_de_salida = 0
def _create_veth(ip_command, prefix, mac_address, mtu): last_exc = None for _ in range(0, 3): device_name = prefix + str(random.randrange(1, 1000000)) try: subprocess.check_call( [ip_command, "link", "add", device_name] + (["address", mac_address] if mac_address else []) + (["mtu", str(mtu)] if mtu is not None else []) + ["type", "veth", "peer", "name", device_name + "-tap"] + (["mtu", str(mtu)] if mtu is not None else [])) except Exception as exc: last_exc = exc else: last_exc = None break else: raise last_exc ip_output = subprocess.check_output( [ip_command, "link", "show", "dev", device_name]) m = re.search(b"link/ether ([0-9a-zA-Z:]+)", ip_output) if not m: raise ValueError('Cannot create interface') mac_address = m.group(1) subprocess.check_call( [ip_command, "link", "set", device_name + "-tap", "up"]) return (device_name, mac_address)
def crossover_onepoint(self, other): "Retorna dos nuevos individuos del cruzamiento de un punto entre self y other " #implementacio single o cruzamiento de un punto c = random.randrange(81) pos = c // 9 #se hace division entera chromosome1 = deepcopy(self.chromosome) chromosome2 = deepcopy(other.chromosome) """ ESto se debe devolver a lo normal print("imprime la posicion",pos) print("imprime lo heredado del primero",self.chromosome[:pos]) chromosome1=self.chromosome[:pos]+other.chromosome[pos:] print("el cromosoma1",chromosome1) chromosome2=other.chromosome[:pos]+self.chromosome[pos:] ind1 = Individual_sudoku(chromosome1) ind2 = Individual_sudoku(chromosome2) ################# """ for i in range(pos): block_indices = get_block_indices2( i) ##obtiene la lista para cambiar los bloques chromosome1[block_indices] = other.chromosome[ block_indices] #le pasa al cromosome 1 del other todos los bloques hasta pos chromosome2[block_indices] = self.chromosome[ block_indices] #del self se le pasa los bloques hasta el pos ind1 = Individual_sudoku(chromosome1) ind2 = Individual_sudoku(chromosome2) return [ind1, ind2]
def Tsne_visual(Train, y, filename): mytargets = list(range(0,10)) XX_train, yy_train = Train, y num_classes = len(np.unique(yy_train)) labels = np.arange(num_classes) num_samples_to_plot = 50000 import random idx = [random.randrange(XX_train.shape[0]) for i in xrange(num_samples_to_plot)] X_train, y = XX_train[idx,:], yy_train[idx] # lets subsample a bit for a first impression transformer = TSNE(n_components = 2, perplexity=40, verbose=2) X_transformed = transformer.fit_transform(X_train) # Plotting fig = plt.figure() ax = fig.add_subplot(111) colors = cm.Spectral(np.linspace(0, 1,10)) xx = X_transformed [:, 0] yy = X_transformed [:, 1] print("xx", xx.shape, "yy", yy.shape) print("y_train", max(y) ) # plot the 3D data points for i in range(num_classes): ax.scatter(xx[y==i], yy[y==i], color=colors[i], label=str(i), s=10) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.legend(loc='best', scatterpoints=1, fontsize=5) plt.savefig(filename+'.pdf', format='pdf', dpi=600)
def guessTheNumber(): import random num = random.randrange(1,1001) guess = 1001 count = 0 while num!=guess: try: guess = int(input("Guess a number between 1 and 1000 ")) count+=1 except: print("\nFuck you that's not a number, try again\n\n") count+=1 continue if "69" in str(guess): print("\nNice.") if "420" in str(guess): print("\nSick nasty bro") if abs(guess-num)>300: print("\nAre you serious right now\n\n") elif guess<num: print("\nbruh its higher than that\n\n") elif guess>num: print("\nlowerrrrrrr\n\n") else: print("i dont even f****n know") print("\nThat took you {} tries. Sad.".format(count))
def parse(self, response): self.loggerWithTime("detail_parse") movie_item = DoubanItem() movie_links = self.get_movie_links() for movie_link, in movie_links: movie_item['url'] = movie_link movie_item['uid'] = re.sub("\D", "", movie_link) page_html = requests.get(url =movie_link,cookies = self.cookie).content if page_html.find("页面不存在") >=0: self.loggerWithTime("[%s]页面不存在" % movie_item['uid']) links_sql = "update public.tb_movie_url_task set flag=404 where url ='%s'" % movie_item['url'] self.cur.execute(links_sql) self.db.commit() break if page_html.find("条目不存在") >=0: self.loggerWithTime("[%s]条目不存在" % movie_item['uid']) links_sql = "update public.tb_movie_url_task set flag=403 where url ='%s'" % movie_item['url'] self.cur.execute(links_sql) self.db.commit() break if page_html.find("检测到有异常请求") >=0: self.loggerWithTime(page_html) self.loggerWithTime("开始休眠") time.sleep(random.randrange(10, 180)) break parser = MovieParser(page_html) for field in movie_item.fields.keys(): #遍历item中的字段获取到对应字段的值 if hasattr(parser, field): movie_item[field] = getattr(parser,field) movie_item = parser.get_source_link(movie_item) #返回了更新后的 movie_item yield movie_item
def upload(): if request.method == 'POST': # Get the file from post request f = request.files['image'] # Save the file to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) # Make prediction preds = model_predict(file_path, model) # Process your result for human # pred_class = preds.argmax(axis=-1) # Simple argmax #pred_class = decode_predictions(preds, top=1) # ImageNet Decode pr1 = np.argmax(preds) result = dict[pr1] result = list(result) if result[0] == "No DR": result[1] = "0%" else: result[1] = str("{0:.2f}".format(random.randrange(60, 100))) + "%" result = tuple(result) return make_response(jsonify(result), 201) return None
def scrape_news(url): from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import random #driver = webdriver.Firefox() from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(url) # another forloop that goes into each link and get data on: driver.implicitly_wait(random.randrange(30)) if re.compile(r'(?:.doc)|(?:.pdf)').findall( str(url)): # check whether link is pdf or word doc d = { 'article_source': ['none'], # /html/body/div/div[4]/div[7]/div[1] 'body': ['none'], } X = pd.DataFrame(data=d) driver.close() return X # another forloop that goes into each link and get data on: else: time.sleep(3) ################# if there is a error from socket, then randomize another one driver.get(url) driver.refresh() if re.compile(r'(?:.doc)|(?:.pdf)').findall(str( driver.current_url)): # check whether link is pdf or word doc d = { 'article_source': ['none'], 'body': ['none'], } # NORMAL people's daily papges elif driver.find_elements_by_xpath('/html/body/div[5]/div[2]'): d = { 'article_source': [ driver.find_elements_by_xpath('/html/body/div[5]/div[1]') [0].text ], # /html/body/div/div[4]/div[7]/div[1] 'body': [ driver.find_elements_by_xpath('/html/body/div[5]/div[2]') [0].text ], } else: d = { 'article_source': ['none'], # /html/body/div/div[4]/div[7]/div[1] 'body': ['none'], } df = pd.DataFrame(data=d) driver.close() return df
def crossoperate(population): range = len(population[0]['Gene']) gene_info_1 = population[0]['Gene'] gene_info_2 = population[1]['Gene'] index_1 = random.randrange(1,range) index_2 = random.randrange(1,range) product = [] for i in range: if (i >= min(index_1, index_2) and i <= max(index_1, index_2)): product.append({'Gene':gene_info_1[i]}) else: product.append({'Gene':gene_info_2[i]}) return product
def anime_search(): """ Searches through the Hummingbird Database if a query term is given. Returns the best match anime if a result is found. If nothing is found, return a random anime. If no query term is given, also return a random anime. Arguments: tweet (dict) of the tweet to reply to Returns: A string to be tweeted containing the following: 1) the title of the resulting anime 2) hummingbird url of the resulting anime """ query = tweet['text'] """ Need to remove the @hummingbirdDB and #GiveMeAnime part at the front """ id_base_url = "http://hummingbird.me/api/v1/anime/" max_id = 10877 random_anime_id = random.randrange(1, max_id, 1) if len(query) > 0: anime = requests.get("http://hummingbird.me/api/v1/search/anime", params={'query': query}) txt = anime.text data = json.loads(txt) if(len(data) > 0): title = data[random.randrange(0, len(data)-1, 1)] tweet_text = "#Anime4U How about \"" + title["title"] + "\"? " + title["url"] else: anime_alt = requests.get(id_base_url + str(random_anime_id)) txt = anime.text data = json.loads(txt) title = data[0] tweet_text = "#Anime4U How about \"" + title["title"] + "\"? " + title["url"] else: anime_alt = requests.get(id_base_url + str(random_anime_id)) txt = anime.text data = json.loads(txt) title = data[0] tweet_text = "#Anime4U How about \"" + title["title"] + "\"? " + title["url"] return tweet_text
def step(self): self._candidates: List[Tile] = self._get_candidates(self) self.sensor_result = 15 if len(self._candidates) > 0: self.sensor_result = 9999 for tile in self._candidates: if isinstance(tile, self._target): # get tile distance from sensor temp = self._target_distance(tile) if temp < self.sensor_result: self.sensor_result = temp if self._uncertainty is not None: if random.randrange(100) < self._uncertainty*100: self.sensor_result = random.randrange(-100, 100) if self._systematic is not None: self.sensor_result = (self.sensor_result * (1 + self._systematic))
def deal(self): #Randomly select card remaining_cards = [ card for card in self.deck if card not in self.dealt ] card_index = random.randrange(0, len(remaining_cards) - 1) card = remaining_cards[card_index] self.dealt.append(card) return card
def shuffle(self) -> List: """ Returns a random shuffling of the array. """ for i in range(len(self.nums) - 1, 0, -1): j = random.randrange(0, i + 1) # 交换 self.nums[i], self.nums[j] = self.nums[j], self.nums[i] return self.nums
def ferma_prime_test(num: int, rounds=100) -> bool: if num == 2: return True for i in range(rounds): rnd = random.randrange(2, num) if gcd(rnd, num) != 1 or pow(rnd, num, num - 1) != 1: return False return True
def waxnet_generator(): #start = timeit.default_timer() length = info.WAX_NODES #numpy.set_printoptions(linewidth=200) # 1.1 Initialize distance vector between 200 nodes (routers) network = numpy.zeros((length, length)) #1.2 Assign random values between 1-50 for network # Must be >0 because 0 is the distance from itself # and positive because no Bellman-Ford. for i in range(len(network)): for j in range(len(network)): if i == j: network[i][j] = 0 else: network[i][j] = random.randrange(1, 20, 1) #1.3 Based on Wexman network function calculate pro- # bability of connection, if less than 0.15 (15%) it # is not connected => Assign -1 to the value. Alfa and # Beta are paremeters from Wexman Network. # # Higher Alfa => Higher density # Alfa > 0, Alfa = 1. # # Smaller Beta => Higher density of short edges # Beta < 1, Beta = 0.5 # # L = maximum inter-nodal distance in network # L = max(distance) - min (distance) # # With these parameters % dc_links = [4, 7,5] alfa = 1 beta = 0.4 L = numpy.max(network) - numpy.min(network) for i in range(len(network)): for j in range(len(network)): wex_prob = alfa * math.exp(-(network[i][j]) / (beta * L)) if wex_prob < 0.15: if i != j: network[i][j] = -1 # Count number of disconnected links count = 0 for i in range(len(network)): for j in range(len(network)): if network[i][j] < 0: count += 1 #dc_links = (count / math.pow(len(network), 2)) * 100 #print network #print '% of disconnected links = ' + str(dc_links) + "%" return network
def old_main(): """main function""" nombre_de_points = 100 coordonnees_des_points = 10 limit = random.randrange(2, nombre_de_points) polygones = [Polygon([Point([1, 2]), Point([2, 4]), Point([-1, 2])])] for _ in range(3): points = [ Point([ random.randrange(coordonnees_des_points), random.randrange(coordonnees_des_points), ]) ] segments = [] for _ in range(limit): # on ajoute le polygone si aucun de ses segments ne s'intersecte avec un segment déjà existant point = Point([ random.randrange(coordonnees_des_points), random.randrange(coordonnees_des_points), ]) print(points, segments) failed = is_failed(polygones, segments, points, point) if not failed: segment = Segment([points[-1], point]) if point not in points: points.append(point) if segment not in segments: segments.append(segment) if len(points) > 2: polygon = Polygon(points) if polygon.area() != 0: polygones.append(polygon) with open("generated.poly", "w") as file: for indice, polygone in enumerate(polygones): for point in polygone.points: file.write( f"{indice} {point.coordinates[0]} {point.coordinates[1]}\n" )
def step(self): self._candidates: List[Tile] = self._get_candidates(self) self.sensor_result: bool = False for tile in self._candidates: if isinstance(tile, self._target): self.sensor_result: bool = True if self._uncertainty is not None: if random.randrange(100) < self._uncertainty * 100: self.sensor_result = not self.sensor_result
def shuffle(self): for i in range(len(self.array)): swap_idx = random.randrange(i, len(self.array)) self.array[i], self.array[swap_idx] = self.array[ swap_idx], self.array[i] return self.array # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
def game_loop(): x = d_width * 0.46 y = d_height * 0.75 thing_startx = random.randrange(0, d_width) thing_starty = -500 thing_speed = 10 thing_height, thing_width = (100, 100) x_change = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 if event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change gamedisplay.fill(white) things(thing_startx, thing_starty, thing_width, thing_height, black) thing_starty += thing_speed car(x, y) if x > d_width - c_width or x < 0: crash() if thing_starty > d_height: thing_starty = -thing_height thing_startx = random.randrange(0, d_width - 100) if thing_starty + thing_height > y: if thing_startx + thing_width < x: crash() pygame.display.update() clock.tick(60)
def step(self): self._candidates: List[Tile] = self._get_candidates(self) self.sensor_result: bool = False self._detected_color: str = "" for tile in self._candidates: if isinstance(tile, self._target) and (tile.filling == self._color or self._color is None): self.sensor_result: bool = True self._detected_color: str = tile.filling if self._uncertainty is not None: if random.randrange(100) < self._uncertainty * 100: self.sensor_result = not self.sensor_result
def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ # IMPORTANT: normally when we do new_list = old_list, it creates a new reference to the old list, so even if changes are # made to new_list, the original list is changed. dupArray = self.originalArr.copy() # create a shallow copy of the list shuffledArray = [] for i in range(len(self.originalArr)): remove_idx = random.randrange(len(dupArray)) shuffledArray.append(dupArray.pop(remove_idx)) return shuffledArray
def isPrime(p, s): # The number 2 is not composite, it is prime. if p == 2: return True, p # All even numbers are composite, check for them elif p % 2 == 0: return False, p # Verify p is actually prime for i in range(1, s): a = random.randrange(2, p - 2) if pow(a, p - 1) % p != 1: return False, p return True, p
async def called_affirmation(self, ctx: Context): """We all run out of spoons sometimes, and affirmations can help regain them. Invoke this script and repeat a psuedo-randomly chosen affirmation after me.""" affirmations = self._affirm_list.get_all_records() upper = len(affirmations) call_affirmation_number = random.randrange(2, upper) self._affirm_list.update_cell(1, 8, call_affirmation_number) cell = self._affirm_list.cell(call_affirmation_number, 1).value await ctx.send("An affirmation I sometimes use is - " + cell) current_value = int( self._affirm_list.cell(call_affirmation_number, 5).value) self._affirm_list.update_cell(call_affirmation_number, 5, current_value + 1) return call_affirmation_number
def marat(): import random a = [] for i in range(20): c = random.randrange(100) a.append(c) print(c, end=" ") print() b = int(input("Число: ")) g = 1 for i in a: if i == b: print("Число находится на {}-м месте.".format(g)) else: g += 1
def credithours(): import random hours = random.randrange(0,600) if hours < 30: year = "a freshman by credit hours" elif hours >= 30 and hours < 60: year = "a sophomore by credit hours" elif hours >= 60 and hours < 90: year = "a junior by credit hours" elif hours >= 90 and hours < 120: year = "a senior by credit hours" elif hours >= 120 and hours < 400: year = "a super-senior" else: year = "dead" print("You have {} hours. This makes you {}.".format(hours, year))
def __init__(self): self.juego_asignado = None self.nombre = random.choice( [get_first_name("male"), get_first_name("female")]) self.apellido = get_last_name() self.edad = random.randrange(21, 90) self.t_descanso = normalvariate(14, 5) self.t_descansado = 0 self.t_trabajo = 0 self.t_trabajado = 0 self.trabajando = False self.h_prox_turno = 0 self.tipo = "" self.descansado = 0
cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Merchant Credit'): merch=gen_data.create_company_name() cat=random.choice(Merchant_Category.Green) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Refund'): cat='0000' cat_desc=python_merchant_cat.All_Merchant_Cat[cat] row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Credits) #If we need to make a payment or get credit then assign codes if Balance > limit and flag==0: #print '3' tmpAmt=random.randrange(1,Balance-limit+1,1) tranType = random.choice(Tran_Type_D) cat = random.choice(MCC_debits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] Balance = Balance - tmpAmt merch=gen_data.create_company_name() row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Debits) else: if ((Balance < 0 or Balance==0)and flag==0): #print '4' cr_dbt='C' tranType='Payment' tmpAmt = random.randrange(1,limit/2,1)
s[j][k] = random.choice([-1,1]) #creating empty lists to hold energy and magnetization values energy_list = [] magnet_list = [] #adding the energies and magnetization of the current configuration to the list energy_list.append(energy(s)) magnet_list.append(magnet(s)) t = [] t.append(0) for i in range(num_iter): print i #index of array elements chosen randomly x = random.randrange(0,Nx) y = random.randrange(0,Ny) E_old = energy(s) s[x][y] *= - 1 E_new = energy(s) accepting = acceptance(E_old,E_new) if accepting == True: energy_list.append(E_new) magnet_list.append(magnet(s)) t.append(i) elif accepting == False: s[x][y] *= -1 xvals = np.where(s == 1) yvals = np.where(s == -1) plt.ion()
rra1 = RRA(cf='AVERAGE', xff=0.5, steps=24, rows=1460) rras.append(rra1) myRRD = RRD(filename, ds=dss, rra=rras, start=startTime) myRRD.create() # let's generate some data... currentTime = startTime for i in xrange(maxSteps): currentTime += step # lets update the RRD/purge the buffer ever 100 entires if i % 100 == 0: myRRD.update(debug=False) # let's do two different sets of periodic values #value1 = int(sin(i % 200) * 1000) value1 = random.randrange(1,10000) #value2 = int(sin( (i % 2000)/(200*random()) ) * 200) #value3 = int(sin( (i % 4000)/(400*random()) ) * 400) #value4 = int(sin( (i % 6000)/(600*random()) ) * 600) # when you pass more than one value to update buffer like this, # they get applied to the DSs in the order that the DSs were # "defined" or added to the RRD object. myRRD.bufferValue(currentTime, value1) # add anything remaining in the buffer myRRD.update() # Let's set up the objects that will be added to the graph def1 = DEF(rrdfile=myRRD.filename, vname='myspeed', dsName=ds1.name) #def2 = DEF(rrdfile=myRRD.filename, vname='mysilliness', dsName=ds2.name) #def3 = DEF(rrdfile=myRRD.filename, vname='myinsanity', dsName=ds3.name) #def4 = DEF(rrdfile=myRRD.filename, vname='mydementia', dsName=ds4.name)
tmp = 'mysqlhelper' func = 'count' model = __import__(tmp) ggg = getattr(model, func) print ggg() #通过字符串模式导入函数,需要先找到函数getattr import random print random.random() print random.random()*10 #生成0-1之间的随机数 print random.randint(1,5) #生成1-5间的整形随机数 print random.randrange(1,3) #生成1和2,不会生成3,整形 print random.randint(100000,999999) #生成6位随机数 code = [] for i in range(6): if i == random.randint(1,5): code.append(str(random.randint(1,5))) else: tmp = random.randint(65,90) code.append(chr(tmp)) print code print ''.join(code)
def gen_tran(MCC_credits,MCC_debits,Tran_Country_Credits,Tran_Country_Debits,Tran_Type_C,Tran_Type_D,Upper_Limit,Delta,count,j,usecase): liTrans = [] #Initiate start date for transactions startDate=date(2015,01,01) #Pick out account based on counter acct=ACCTs[j] #Set customer credit limit - skew to clients with $1000-$25000 and 10% with $25K - $50K limit = max(max((randrange(1,101,1)-99),0)* randrange(25000,50000,1000),randrange(1000,25000,1000)) #local Amt variable to calculate customer total usage usedAmt = 0 tmpAmt = 0 Balance = limit maxDate= startDate #Random number generator for transactions per customer NoTrans = randrange(100,150,1) desc='' flag=0 maxCheckin='' maxBook='' #loop to generate NoTrans transactions per customer for k in range(NoTrans): dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S") cr_dbt='D' tranType = '' country=[] cat_desc='' flag=0 #If Balance is within the credit limit, generate credits/debits if(Balance>0 and Balance<=limit*1.2): #Probability of credits (tmpAmt>0) and debits (tmpAmt==0) is driven by parameters Upper_Limit and Delta tmpAmt = max((randrange(1,Upper_Limit,1)+Delta),0)*randrange(1,Balance+1,1) flag=1 #Define time delta for next transaction tdelta = timedelta(days=randrange(1,4,1)) row = [str(count)+'_'+dt] + [acct] #If we have credit or debit within balance if tmpAmt == 0 and flag==1: #print '1' tmpAmt=random.randrange(1,Balance+1,1) tranType = random.choice(Tran_Type_D) cat = random.choice(MCC_debits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] Balance = Balance - tmpAmt merch=gen_data.create_company_name() row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Debits) else: if tmpAmt > 0 and flag==1: #print '2' cr_dbt='C' tranType=random.choice(Tran_Type_C) Balance = Balance + tmpAmt merch='' cat = random.choice(MCC_credits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Merchant Credit'): merch=gen_data.create_company_name() cat=random.choice(Merchant_Category.Green) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Refund'): cat='0000' cat_desc=python_merchant_cat.All_Merchant_Cat[cat] row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Credits) #If we need to make a payment or get credit then assign codes if Balance > limit and flag==0: #print '3' tmpAmt=random.randrange(1,Balance-limit+1,1) tranType = random.choice(Tran_Type_D) cat = random.choice(MCC_debits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] Balance = Balance - tmpAmt merch=gen_data.create_company_name() row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Debits) else: if ((Balance < 0 or Balance==0)and flag==0): #print '4' cr_dbt='C' tranType='Payment' tmpAmt = random.randrange(1,limit/2,1) Balance = Balance + tmpAmt merch = '' cat = '1111' cat_desc=python_merchant_cat.All_Merchant_Cat[cat] row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Credits) #date posted date1 = maxDate+tdelta maxDate = date1 #date of transaction a day later date2 = date1-timedelta(days=1) row.extend([country,date1,date2,tranType,cr_dbt,limit,tmpAmt,Balance,CCs[j], CCTypes[j],usecase,Holders[j],CCsCount[j],Cities[j],States[j],ZIPs[j],Countries[j]]) count = count + 1 checkin='' checkout='' transDetail='' #Add details or Hotel Transactions if((cat_desc=='Hotels/Motels/Inns/Resorts' or cat_desc=='Hotels, Motels, and Resorts') and (UseCase[j]=='28' or UseCase[j]=='29')): if (maxCheckin == ''): checkin=maxDate+timedelta(days=randrange(365,389,1)) checkout=checkin+timedelta(days=randrange(4,11,1)) maxCheckin=checkin tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() hotel=tmp2[1]+' Hotels; '+'; Address: '+addr[1]+' '+addr[2]+', '+addr[0] transDetail='Checkin: '+str(checkin)+'; Checkout: '+str(checkout)+'; Hotel: '+hotel else: checkin=maxCheckin + timedelta(days=randrange(2,5,1)) checkout=checkin+timedelta(days=randrange(4,11,1)) maxCheckin=checkin tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() hotel=tmp2[1]+' Hotels; '+'; Address: '+addr[1]+' '+addr[2]+', '+addr[0] transDetail='Checkin: '+str(checkin)+'; Checkout: '+str(checkout)+'; Hotel: '+hotel if((cat_desc=='Hotels/Motels/Inns/Resorts' or cat_desc=='Hotels, Motels, and Resorts') and UseCase[j]=='30'): checkin=maxDate+timedelta(days=randrange(30,200,1)) checkout=checkin+timedelta(days=randrange(4,11,1)) tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() hotel=tmp2[1]+' Hotels; '+'; Address: '+addr[1]+' '+addr[2]+', '+addr[0] transDetail='Checkin: '+str(checkin)+'; Checkout: '+str(checkout)+'; Hotel: '+hotel #Add details or Airline Transactions if(cat_desc=='Airlines' and (UseCase[j]=='31' or UseCase[j]=='32')): if (maxBook == ''): booking=maxDate+timedelta(days=randrange(1,15,1)) maxBook=booking tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() transDetail='Date Booked: '+str(booking)+'; Name Booked: '+tmp2[0]+tmp2[1]+'; Address: '+addr[1]+' '+addr[2]+', '+addr[0]+'; Source :'+random.choice(Airport_Code)+'; Destination:'+random.choice(Airport_Code) else: booking=maxBook + timedelta(days=randrange(1,15,1)) maxBook=booking tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() transDetail='Date Booked: '+str(booking)+'; Name Booked: '+ tmp2[0] + tmp2[1] + '; Address: '+ addr[1] + ' ' + addr[2]+', '+addr[0]+'; Source :'+random.choice(Airport_Code)+'; Destination:'+random.choice(Airport_Code) if(cat_desc=='Airlines' and UseCase[j]=='33'): booking=maxDate + timedelta(days=randrange(1,15,1)) tmp2=gen_data.create_name() addr=gen_data.create_city_state_zip() transDetail='Date Booked: '+str(booking)+'; Name Booked: '+ tmp2[0] + tmp2[1] + '; Address: '+addr[1]+' '+addr[2]+', '+addr[0]+'; Source :'+random.choice(Airport_Code)+'; Destination:'+random.choice(Airport_Code) row.append(transDetail) liTrans.append(row) #post generating all transactions, check account balance - if overpaid - refund $ and add a refund transaction if Balance > limit: row = [str(count)+'_'+dt]+ [acct]+['Uber Bank']+['0000']+['Refund to Customer from Bank']+[random.choice(Tran_Country_Debits)] date1=maxDate+timedelta(days=90) date2=date1-timedelta(days=1) row.extend([date1, date2, 'Credit Balance Refund','D',limit,Balance-limit,limit,CCs[j],CCTypes[j], usecase,Holders[j],CCsCount[j],Cities[j],States[j],ZIPs[j],Countries[j],'']) count = count + 1 usedAmt = 0 maxDate= datetime(0001,01,01) else: date1 = maxDate+tdelta maxDate = date1 #date of transaction a day later date2 = date1-timedelta(days=1) row = [str(count)+'_'+dt]+[acct]+['Customer Payment']+['1111']+['Customer Payment']+[random.choice(Tran_Country_Credits)] row.extend([date1, date2, 'Payment','C',limit,limit-Balance,limit,CCs[j],CCTypes[j],usecase, Holders[j],CCsCount[j],Cities[j],States[j],ZIPs[j],Countries[j],'']) count = count + 1 usedAmt = 0 liTrans.append(row) return liTrans
def random_content_id(): return random.randrange(4653808699414123826, 5653808699414123826)
def gen_tran(MCC_credits,MCC_debits,Tran_Country_Credits,Tran_Country_Debits,Tran_Type_C,Tran_Type_D,Upper_Limit,Delta,count,j,usecase): liTrans = [] #Initiate start date for transactions startDate=date(2015,01,01) #Pick out account based on counter acct=ACCTs[j] #Set customer credit limit - skew to clients with $1000-$25000 and 10% with $25K - $50K limit = max(max((randrange(1,101,1)-99),0)* randrange(25000,50000,1000),randrange(1000,25000,1000)) #local Amt variable to calculate customer total usage usedAmt = 0 tmpAmt = 0 Balance = limit maxDate= startDate #Random number generator for transactions per customer NoTrans = randrange(100,150,1) desc='' flag=0 maxCheckin='' maxBook='' #loop to generate NoTrans transactions per customer for k in range(NoTrans): dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S") cr_dbt='D' tranType = '' country=[] cat_desc='' flag=0 #If Balance is within the credit limit, generate credits/debits if(Balance>0 and Balance<=limit*1.2): #Probability of credits (tmpAmt>0) and debits (tmpAmt==0) is driven by parameters Upper_Limit and Delta tmpAmt = max((randrange(1,Upper_Limit,1)+Delta),0)*randrange(1,Balance+1,1) flag=1 #Define time delta for next transaction tdelta = timedelta(days=randrange(1,4,1)) row = [str(count)+'_'+dt] + [acct] #If we have credit or debit within balance if tmpAmt == 0 and flag==1: #print '1' tmpAmt=random.randrange(1,Balance+1,1) tranType = random.choice(Tran_Type_D) cat = random.choice(MCC_debits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] Balance = Balance - tmpAmt merch=gen_data.create_company_name() row.append(merch) row.append(cat) row.append(cat_desc) country=random.choice(Tran_Country_Debits) else: if tmpAmt > 0 and flag==1: #print '2' cr_dbt='C' tranType=random.choice(Tran_Type_C) Balance = Balance + tmpAmt merch='' cat = random.choice(MCC_credits) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Merchant Credit'): merch=gen_data.create_company_name() cat=random.choice(Merchant_Category.Green) cat_desc=python_merchant_cat.All_Merchant_Cat[cat] if(tranType=='Refund'): cat='0000' cat_desc=python_merchant_cat.All_Merchant_Cat[cat]
for stat, value in data.items(): sampled_data[stat] = "{0}|@{1}".format(value, sample_rate) return sampled_data return {} @staticmethod def send(_dict, addr): """ Sends key/value pairs via UDP. >>> StatsdClient.send({"example.send":"11|c"}, ("127.0.0.1", 8125)) """ # TODO(rbtz@): IPv6 support udp_sock = socket(AF_INET, SOCK_DGRAM) # TODO(rbtz@): Add batch support for item in _dict.items(): print(":".join(item).encode('utf-8')) udp_sock.sendto(":".join(item).encode('utf-8'), addr) if __name__ == "__main__": import random import time random.seed(int(time.time())) client = StatsdClient() for i in xrange(random.randrange(100000)): client.timing("stats.sample.timing", random.randrange(500)) for i in xrange(random.randrange(100000)): client.count("stats.sample.count", random.randrange(500))