async def dankmeme(self, ctx): """The dankest of memes""" pymeme = discord.Embed(title="Meme", description="**Meme Request**", color=0xe91e63) async with aiohttp.ClientSession() as cs: async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r: res = await r.json() pymeme.set_image(url=res['data']['children'][random2.randint(0, 25)]['data']['url']) await ctx.send(embed=pymeme)
async def aww(self, ctx): """Cute animals""" pymeme = discord.Embed(title="Awww", description="**CUTE DOGGO AND CAT**", color=0xe91e63) async with aiohttp.ClientSession() as cs: async with cs.get('https://www.reddit.com/r/aww/new.json?sort=hot') as r: res = await r.json() pymeme.set_image(url=res['data']['children'][random2.randint(0, 25)]['data']['url']) await ctx.send(embed=pymeme)
async def Wholesome(self, ctx): """Wholesome memes""" pymeme = discord.Embed(title="wholesomememes", description="**a great command when you feel down**", color=0xe91e63) async with aiohttp.ClientSession() as cs: async with cs.get('https://www.reddit.com/r/wholesomememes/new.json?sort=hot') as r: res = await r.json() pymeme.set_image(url=res['data']['children'][random2.randint(0, 25)]['data']['url']) await ctx.send(embed=pymeme)
def CodeUpdate(): # Process ID ProcessId = "(B-02)" # Capturamos la Variable Email Enviada EmailUser = request.form['Email'] TokenUser = random2.randint(1000, 9999) connection = pymysql.connect(host='192.168.100.51', user='******', password='******', db='External-Api', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: try: with connection.cursor() as cursor: # Read a single record sql = "SELECT `User` FROM `User` WHERE `User`=%s" cursor.execute(sql, (EmailUser)) result = cursor.fetchone() connection.commit() try: User = str(result.get('User')) except: User = "******" if (User == EmailUser): # Read a single record sql_update_query = """UPDATE User set CodeUser = %s where User = %s""" data_tuple = (TokenUser, EmailUser) cursor.execute(sql_update_query, data_tuple) connection.commit() # Send Email Text = "Actualizacion - Code: " SendEmail(EmailUser, TokenUser, Text, ProcessId) print(ProcessId, " -Verification Code was updated to", EmailUser) return jsonify([{ "Email": EmailUser, "Code": TokenUser, "Mensaje": "Verification Code was updated verify your email" }]) else: print(ProcessId, " -ERROR User not found", EmailUser) return jsonify({"Error": "User not found"}) finally: connection.close() except: print("error En el proceso de Actualizacion del Codigo de Acceso")
def generateOutputGivenInput(chars): print("Creating sequence") N = len(chars) output = np.zeros((N, 28, 28), dtype=np.float) for i in range(N): loc = np.where(y_train == int(chars[i])) L = len(loc[0]) index = random2.randint(0, L - 1) temp = X_train[loc[0][index], :, :, :] output[i, :, :] = temp return output
def Rand(start, end, length): list = [] while len(list) < length: res = [] for j in range(2): res.append(random2.randint(start, end)) if res not in list: list.append(res) if res == [0, 0] or res == [end, end]: list.remove(res) list = [i for i in list + obs if i in list and i not in obs] list.sort() return list
def get_text_messages(message): print(message.text) if message.text == "Привет": bot.send_message(message.chat.id, "Привет, друг!", reply_markup=markup) if (message.text == "Расскажи анекдот" or message.text == "/joke"): with open('jokes.txt', 'r') as nnn: joke = [line.strip() for line in nnn] nnn.close() ran = random2.choice(joke) bot.send_message(message.chat.id, ran, reply_markup=markup) if (message.text.startswith('/roll') or message.text.startswith(b"\xF0\x9F\x8E\xB2".decode("utf-8"))): message.text.strip(" ") print(message.text) bot.send_message(message.chat.id, random2.randint(1, 100), reply_markup=markup) if message.text == b"\xF0\x9F\x92\xB0".decode("utf-8"): bot.send_message(message.chat.id, 'money money money', reply_markup=markup) if message.text.lower() == "спасибо": bot.send_message(message.chat.id, 'Всегда пожалуйста!', reply_markup=markup) if message.text == b"\xF0\x9F\x98\x82".decode("utf-8"): bot.send_message(message.chat.id, 'Рад, что тебе весело!', reply_markup=markup) if message.text.lower() == 'скажи погоду': owm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc', language="ru") place = 'Островец' weather_advice = "" observation = owm.weather_at_place(place) w = observation.get_weather() veter = (str(round(w.get_wind()["speed"]))) vlazhnost = (str(round(w.get_humidity()))) temperatura = (str(round(w.get_temperature('celsius')["temp"]))) if float(temperatura) <= 15: weather_advice += "советую одеться потеплее " if float(veter) >= 10: weather_advice += "сегодня ветренно " bot.send_message(message.chat.id, 'В городе' + ' ' + place + ' ' + 'сейчас' + ' ' + w.get_detailed_status() + ', ветер' + ' ' + veter + ' ' + 'метров в секунду' + ', влажность' + ' ' + vlazhnost + ' ' + 'процентов' + ', температура' + ' ' + temperatura + ' ' + 'градусов по Цельсию,' + weather_advice, reply_markup=markup_2)
def save_image_from_form(image, owner, Id): filename = secure_filename(image.filename) if allowed_file(filename): directory = os.path.join(config.IMAGE_FILE_FOLDER, owner, Id) if not os.path.exists(directory): os.makedirs(directory) file_type = filename.rsplit('.', 1)[1].lower() img_name = str(random2.randint(10000, 99999))+'.'+file_type img_directory = os.path.join(directory, img_name) img_path = os.path.join(config.IMAGE_URL_PATH, owner, Id, img_name) image.save(img_directory) return img_path else: return False
def random_tierN_board_generator(n): current_state = start_state copyN = n while copyN > 0: all_moves = game.GenerateMoves(current_state) # print(len(all_moves)) random_index = random2.randint(0, len(all_moves) - 1) current_state = Santorini_2.DoMove( [current_state[0][:], current_state[1].copy()], all_moves[random_index]) copyN -= 1 if game.PrimitiveValue(current_state) != 'undecided' and current_state[ 0].count('3') > 0 and current_state[0].count('4') > 0: return random_tierN_board_generator(n) return current_state
def save_encoded_image(image, owner, Id): try: file_type = 'png' directory = os.path.join(config.IMAGE_FILE_FOLDER, owner, Id) if not os.path.exists(directory): os.makedirs(directory) img_name = str(random2.randint(10000, 99999))+'.'+file_type img_directory = os.path.join(directory, img_name) img_path = os.path.join(config.IMAGE_URL_PATH, owner, Id, img_name) image_result = open(img_directory, 'wb') # create a writable image and write the decoding result image_result.write(image) #image.save(img_directory) return img_path except: return False
def get_key_msg(str, name): msg = [ name + ',是你救了我嗎?嗯,既然這樣還是要謝謝你呢\nヽ( ̄ω ̄〃)ゝ', '其實啊,和' + name + '交情太好是不行的...\n不過,反正很開心就算了吧♪', '我的魔法,挺厲害的吧?哼哼~♪\n' + name + '你再多讚美讚美我幾句♪', '完美完美! 紮紮實實地越來越厲害了不是嘛♪\n我果然是想做就做得到!', '恢復魔法也多少會用了,要是有什麼萬一的話,也不是救不了'+ name + '你啦。不過這種萬一還是不要發生比較好啦><', '和那傢伙的心靈相連之力... 感覺還不賴呢。\n什麼!' + name + '你都聽到了嗎!?\n馬、馬上給我忘了,笨蛋啊啊~!', '我會用這股新的力量保護你的... 那個... \n' + name + ',你不准離開我身邊喔!', '我的魔力和' + name + '的力量逐漸合而為一... ! \n來,放馬過來吧!今天的我可是脫胎換骨了!', '這就是你和我的真正的力量呢...! \n只要和' + name + '再一起,感覺就不會輸!', ] num = random.randint(0,len(msg)-1) return msg[num]
def random(grid): avail_spots = [] avail_spots_rows = [] avail_spots_cols = [] for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == 0: avail_spots_rows.append(i) avail_spots_cols.append(j) avail_spots = list(zip(avail_spots_rows, avail_spots_cols)) len_avail_spots = len(avail_spots) if len_avail_spots - 1 == 0: row, col = avail_spots[0] return row, col spot = random2.randint(0, len_avail_spots - 1) row, col = avail_spots[spot] return row, col
def roll_dice(die, rolls, modifier): ''' take die int, call randint() rolls amount, add the modifier to each roll ''' print('----------------') for i in range(rolls): cast = randint(1, die) # Kepp track of crit to use to not show base and modifier if they are implemented crit = False if cast == 20: # crit hit true crit = True if cast == 1 and die == 20: # crit miss true crit = True # print info about rolls is there is a modifier if modifier != 0 and crit == False: print(f'base cast is {cast}') print(f"modifier is {modifier}") # account for crit hits and crits misses while rolling a d20 if cast == 20: print( colored(f"Roll {i + 1} is 20! Critical Hit!", 'green', attrs=['bold'])) elif cast == 1 and die == 20: print( colored(f"Roll {i + 1} is 1. Critical miss! Dangit!", 'red', attrs=['bold'])) # if the modifer makes the roll go below 1, print 1 elif cast + (int(modifier)) < 1: print(colored(f"Roll {i + 1} is 1", 'cyan')) # otherwise just do the math and print the value elif modifier != 0: print(colored(f"Roll {i + 1} is {cast + (int(modifier))}", 'cyan')) else: print(colored(f"Roll {i + 1} is {cast}", 'cyan')) print('----------------')
def app_initiation_api(): data = request.get_json() if request.get_json() else {} if not utils.initiation_validator(data)[0]: return jsonify(utils.initiation_validator(data)[1]) cellNumber = data['cellNumber'] registerCode = str(random2.randint(10000, 99999)) sms_result = utils.send_sms(cellNumber, registerCode) user = models.User.query.filter_by(cellNumber=cellNumber).first() if user: return jsonify({ 'status': 303, 'message': { 'phone number': cellNumber, 'register code': registerCode, 'userId': user.userId } }) return jsonify({ 'status': config.HTML_STATUS_CODE['Success'], 'message': { 'phone number': cellNumber, 'register code': registerCode } })
def process(i): d = random2.randint(-3,3) ret = i + d return (0 if ret < 0 else (65535 if ret > 65535 else ret))
def melodygen(self, tempo, length, profile='random', p_unity=40, repetition_rate=13, crossfd=30): self.sound = self.notegen(0, tempo) rhythmbox = [ 'single', 'up_triplet', 'down_triplet', 'turn', 'reverse_turn', 'up_accia', 'down_accia', 'up_scale', 'down_scale', 'up_thirds', 'down_thirds', 'lower_thrill_slow', 'upper_thrill_slow' ] if profile == 'random': for x in range(length): # random rhythm class selector r = random2.randint(0, p_unity) # random origin note selector n = random2.randint(0, int(len(self.scale)) - 1) if r >= len(rhythmbox): self.rhythmgen(rclass='single', note_index=n, tempo=tempo, crossfd=crossfd) else: self.rhythmgen(rclass=rhythmbox[r], note_index=n, tempo=tempo, crossfd=crossfd) # Provides stacking repitition for *some* structure if x % repetition_rate == 0 and x > 0: self.sound = self.sound.append(self.sound) elif profile == 'alarm': for k in range(length): self.rhythmgen(rclass='up_triplet', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='up_triplet', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='pause', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='down_triplet', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='down_triplet', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='pause', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='down_thirds', note_index=4, tempo=tempo, crossfd=crossfd) self.rhythmgen(rclass='pause', note_index=4, tempo=tempo, crossfd=crossfd) return self.sound
def __init__(self): self.cnt = Duck.cnt Duck.cnt += 1 self.x = random2.randint(-200, 200) self.y = random2.randint(-200, 200) self.turtle = turtle
def roll_die(): self.sides = randint(1, 6)
def NewUser(): # Process Id ProcessId = "(A-01)" try: # Capturamos la Variable Email Enviada EmailUser = request.form['Email'] #Contrasena = request.form['Contrasena'] #Peticion = request.form['Peticion'] print (EmailUser) # Generamos Un Token Aleatorio CodeUser = random2.randint(1000, 9999) Status = 3 # Conexion DB connection = pymysql.connect(host='192.168.100.51', user='******', password='******', db='External-Api', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) with connection.cursor() as cursor: # Validar Usuario Existente # Read a single record sql = "SELECT `User` FROM `User` WHERE `User`=%s" cursor.execute(sql, (EmailUser)) result = cursor.fetchone() connection.commit() try: User = str(result.get('User')) except: print (ProcessId, " -Usuario no encontrado") User = "******" if (User == EmailUser): print (ProcessId, " -ERROR: The User is already Registered, User was not Created", EmailUser) return jsonify({ "Error": "The user is already Registered"}) else: # Read a single record sql = "INSERT INTO `User` (User, CodeUser, Status) Values (%s,%s,%s)" cursor.execute(sql, (EmailUser, CodeUser, Status)) connection.commit() print (ProcessId, " -OK: User was successfully created: ", EmailUser) return jsonify({"User": EmailUser, "Mensaje": "Successful Registration, Verify your Email and Validate the Code"}) # Send Email # subject Text = "Successful Registration - Code: " # call Email Funtion SendEmail (EmailUser, CodeUser, Text, ProcessId) print (ProcessId, " -Validation Email, was sent successfully for: ", EmailUser) except Exception as e: print(e) return jsonify({ "Error": "Ocurrio Un Error Intente Nuevamente"}) finally: connection.close()
import random2 TokenUser = random2.randint(1000, 9999) print("Token New User: ", TokenUser)
# Keyboard Presses wn.listen() wn.onkeypress(go_up, 'Up') wn.onkeypress(go_down, 'Down') wn.onkeypress(go_left, 'Left') wn.onkeypress(go_right, 'Right') # Main game loop while True: wn.update() # Checking the collision with the food.. if head.distance(food) < 20: # Moving the food.. x_food = random2.randint(-250, 250) y_food = random2.randint(-250, 250) food.goto(x_food, y_food) new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape('square') new_segment.color('green') new_segment.penup() segments.append(new_segment) # Decreasing the delay delay -= 0.001 # Increasing the scores.. score_m += 10 if score_m > high_score:
import random2 result = random2.randint(0, 1) if result == 1: print("Heads") else: print("Tails")
def get_album_image(key): images = client.get_album_images(album[key]) num = random.randint(0, len(images) - 1) url = images[num].link return url
self.__turtle.pendown() self.__turtle.begin_fill() self.__turtle.circle(self.__size) self.__turtle.end_fill() return def screen_self(self): self.__turtle.reset() def move(self): x, y = random2.randint(1, 100), random2.randint(1, 100) self.__loc = self.__loc[0] + x, self.__loc[1] + y return def sound(self): print('cackle') return l = [] for i in range(10): D = Duck(i, 'D' + str(i)) x, y = random2.randint(-200, 200), random2.randint(-200, 200) D.loc = (x, y) D.display(turtle) l.append(D) input()
grid = final_left(grid) elif move == b'w': grid = final_up(grid) elif move == b's': grid = final_down(grid) else: print("*** PLEASE USE VALID KEYS FOR MOVES ***") main(grid) rnd = 0 for row in grid: for i in row: if i == 0: rnd += 1 if rnd != 0: row, col = random(grid) grid[row][col] = 2 loser(grid) draw_grid(grid) size, win_number = start() grid = initial_grid(size) row = random2.randint(0, size - 1) col = random2.randint(0, size - 1) grid[row][col] = 2 draw_grid(grid) winner(grid) loser(grid) main(grid)
print("\n## Running sorting ##") ### Sorting Plots ### # i = insertion sort, s = selection sort # a = average, b = best, w = worst i_a, i_b, i_w = [], [], [] s_a, s_b, s_w = [], [], [] rand_arr = [] sorted_arr = [] rev_arr = [] for k in range(1, 101): # Build list of random ints for i in range(k): rand_arr.append(random2.randint(1, 1000)) rand_arr2 = rand_arr.copy() sorted_arr.append(k) rev_arr = sorted_arr.copy() rev_arr.reverse() rev_arr2 = rev_arr.copy() # C(n) lists for all n and relative cases s_a.append(sort.select_sort(rand_arr)) s_b.append(sort.select_sort(sorted_arr)) s_w.append(sort.select_sort(rev_arr)) i_a.append(sort.insert_sort(rand_arr2)) i_b.append(sort.insert_sort(sorted_arr)) i_w.append(sort.insert_sort(rev_arr2))
scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' images = [rock, paper, scissors] choice = int(input("Type 0 for rock, 1 for paper, 2 for scissors")) if choice >= 3 or choice < 0: print("The number you entered is invalid") else: print(f"You chose {images[choice]}") comp_choice = random2.randint(0, 2) print(f"Computer chose {images[comp_choice]}") if choice == comp_choice: print('Draw!') elif comp_choice == 0 and choice == 2: print("The computer wins") elif comp_choice == 2 and choice == 0: print("You win!") elif choice > comp_choice: print("You win!") else: print("The computer wins")
def move(self): x, y = random2.randint(1, 100), random2.randint(1, 100) self.__loc = self.__loc[0] + x, self.__loc[1] + y return
from random2 import randint N = 10 a = [] for i in range(N): a.append(randint(1, 99)) print(a) i = 0 while i < N - 1: j = 0 while j < N - 1 - i: if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] j += 1 i += 1 print(a)
# esto se añade al principio del archivo import random2 # learn more: https://python.org/pypi/random2 ## Asi se saca un numero aleatorio entero, entre los dos límites dados x = random2.randint(0, 4) print(x)
import random2 validGuess = "Y" correct = random2.randint(1, 6) guess = int(input("Input a number between 1 and 6 ")) if guess < 0 or guess > 7: print("Input a correct number") validGuess = "N" while validGuess == "Y": if guess == correct: print("Well Done!") validGuess = "N" else: print("Try again.") validGuess = "N"