def neighbor_switch_jumps(state): big_jumps = find_big_jumps(state) goodTrks = good_tracks(state) track1=random.choice(goodTrks) track2 = random.choice(goodTrks) num_of_jumps = len(big_jumps[track1]) if num_of_jumps >= 1: which_jump = randint(0,num_of_jumps-1) time_jump1 = big_jumps[track1][0] temp = state[track1][time_jump1:lifetime] state[track1][time_jump1:lifetime] = state[track2][time_jump1:lifetime] state[track2][time_jump1:lifetime] = temp '''elif num_of_jumps>2: print('num of jumps' + str(num_of_jumps)) print('list of big jumps' + str(big_jumps)) which_jump = randint(0,num_of_jumps-2) print('which jump : ' + str(which_jump)) time_jump1 = big_jumps[track1][which_jump] time_jump2= big_jumps[track1][which_jump+1] temp = state[track1][time_jump1:time_jump2] state[track1][time_jump1:time_jump2] = state[track2][time_jump1:time_jump2] state[track2][time_jump1:time_jump2] = temp ''' return state
def count_helper(diamonds,clubs,hearts,spades): random.choice("diamonds","clubs","hearts","spades") if random.choice=="diamonds": return count_helper(diamonds+1,hand-1) elif random.choice=="clubs": return count_helper(clubs+1,hand-1) elif random.choice=="hearts" return count_helper(hearts+1,hand-1) else: return count_helper(spades+1,hand-1)
def gen_cc_external(merchant,no_trans,count): for i in range(no_trans): acct=random.choice(python_account_ID.accountid) cc_list=python_CC.CC_Dict[acct] #7)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 maxDate= datetime(0001,01,01) NoTrans = randrange(100,150,1) #loop to generate NoTrans transactions per customer, we can add logic for probabilities of # transactions if neccessary random number generator to avoid the constant value for j in range(NoTrans): dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S") #generate amount for current transaction with 50%-50% distribution on credits and debits tmpAmt = max((randrange(1,3,1)-1),0)* randrange(1,limit,100)*(-1) #if not credit then generate debit if tmpAmt == 0: tmpAmt = randrange(1,limit,100) #add current amount to client total account usage usedAmt = usedAmt + tmpAmt #pull value from dictionary for randomly selected merchant category cat = '' tranType = '' row = [str(count)+'_'+dt] + [acct] + [gen_data.create_company_name()] #set transaction type based on amount if tmpAmt < 0: tranType = random.choice(Transaction_Type_Credits) row.append('Non-BMO Acct') row.append('') else: tranType = random.choice(Transaction_Type_Debits) cat = random.choice(merchant) row.append(cat) row.append(python_merchant_cat.All_Merchant_Cat[cat]) #tranType random.choice(Transaction_Type) #date posted date1 = gen_data.create_date(past=True) if date1 > maxDate: maxDate = date1 #date of transaction a day later date2 = date1-timedelta(days=1) row.extend([date1, date2, tranType,random.choice(Country_Red),limit,tmpAmt,usedAmt,cc_list[0],cc_list[1]]) count = count + 1 writer.writerow(row) #post generating all transactions, check account balance - if overpaid - refund $ and add a refun transaction if usedAmt < limit * (-1): row = [str(count)+'_'+dt]+ [acct] + ['']+['']+[''] date1temp=maxDate+timedelta(days=90) date2=date1temp-timedelta(days=1) row.extend([date1temp, date2, 'Refund','',limit,abs(limit-abs(usedAmt))*(-1),0,cc_list[0],cc_list[1]]) count = count + 1 usedAmt = 0 maxDate= datetime(0001,01,01) writer.writerow(row)
def neighbor(state): # make random change in random number of spots # swap random range timepoint = randint(0, lifetime - 1) goodTrks = good_tracks(state) track1=random.choice(goodTrks) goodTrks.remove(track1) track2=random.choice(goodTrks) temp = state[track1][timepoint:lifetime] state[track1][timepoint:lifetime] = state[track2][timepoint:lifetime] state[track2][timepoint:lifetime] = temp return state
def detTime(): #temporary solution global currentTime global itemn global items global itemw global iteme now=getTimeStamp() if(now-currentTime>interval): itemn=random.choice(item0) items=random.choice(item1) itemw=random.choice(item2) iteme=random.choice(item3) currentTime=now
def __randomInvasionTick(self, task=None): """ Each hour, have a tick to check if we want to start an invasion in the current district. This works by having a random invasion probability, and each tick it will generate a random float between 0 and 1, and then if it's less than or equal to the probablity, it will spawn the invasion. An invasion will not be started if there is an invasion already on-going. """ # Generate a new tick delay. task.delayTime = randint(1800, 5400) if self.getInvading(): # We're already running an invasion. Don't start a new one. self.notify.debug('Invasion tested but already running invasion!') return task.again if random() <= self.randomInvasionProbability: # We want an invasion! self.notify.debug('Invasion probability hit! Starting invasion.') # We want to test if we get a mega invasion or a normal invasion. # Take the mega invasion probability and test it. If we get lucky # a second time, spawn a mega invasion, otherwise spawn a normal # invasion. if config.GetBool('want-mega-invasions', False) and random() <= self.randomInvasionProbability: # N.B.: randomInvasionProbability = mega invasion probability. suitName = self.megaInvasionCog numSuits = randint(2000, 15000) specialSuit = random.choice([0, 0, 0, 1, 2]) else: suitName = choice(SuitDNA.suitHeadTypes) numSuits = randint(1500, 5000) specialSuit = False self.startInvasion(suitName, numSuits, specialSuit) return task.again
def calc_sim_rec(dist_df,likes,dislikes,n=0,larger_is_closer=True): if likes == []: return random.choice(dist_df.index) else: #dists_df = dist_df[dist_df.index.isin(cluster_dict)] p = get_sims(list(likes),list(dislikes),dist_df,n,larger_is_closer) return p[0:n]
def neighbor_onespot(state): # make random change for one random spots timepoint = randint(0, lifetime - 2) goodTrks = good_tracks(state) track1=random.choice(goodTrks) goodTrks.remove(track1) track2=random.choice(goodTrks) temp = state[track1][timepoint] state[track1][timepoint] = state[track2][timepoint] state[track2][timepoint] = temp temp2 = state[track1][timepoint+1] state[track1][timepoint+1] = state[track2][timepoint+1] state[track2][timepoint+1] = temp2 return state
def calc_sim(dist_df,likes,dislikes,cluster_dict=None,cluster_no=None,n=0): if likes == []: return random.choice(cluster_dict[cluster_no]) else: if cluster_dict != None and cluster_no != None: dists_df = dist_df[dist_df.index.isin(cluster_dict[cluster_no])] p = get_sims(list(likes),list(dislikes),dists_df,larger_is_closer=True) return p[n]
def create_expression(): """This function takes no arguments and returns an expression that generates a number between -1.0 and 1.0, given x and y coordinates.""" expr1 = lambda x, y: (x + y)/2 * cos(y) * tan(5 ** 4) *cos(pi * sin(pi * cos)) expr2 = lambda x, y: (x - y)/2 * random() expr3 = lambda x, y: x * y/4 * random() expr4 = lambda x, y: tan(6 * x) * cos(x) expr5 = lambda y, x: (sin(pi)) + tan(y**2) return random.choice([expr1, expr2, expr3, expr4, expr5])
def place_random(self, entity): empty = [] for x in range(0, self.width): for y in range(0, self.height): if self[x, y] is None: empty.append((x, y)) if len(empty) == 0: raise World.FullRoomException() self[random.choice(empty)] = entity
def check(self, val, client_id=None): if client_id is None: final_set = self.get(random.choice(list(self.client_list))) else: final_set = self.get(client_id) final_set = eval(final_set) if val in final_set: return True else: return False
def strong_password(wordLen=8): import random for k in range(200): word = '' for i in range(wordLen): word += random.choice('-+_()*&$#@!<>;?|{}"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstu') print word
def alpha_num_password(wordLen=8): import random for k in range(200): word = '' for i in range(wordLen): word += random.choice('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstu') print word
def alpha_uppercase(wordLen=8): import random for k in range(200): word = '' for i in range(wordLen): word += random.choice('abcdefghijklmnopqrstuz') print word
def getItemScanned(): detTime() locat=random.choice(location); if (locat==location[0]): tempc=random.choice(item0) out=[locat,random.choice(itemn),getTimeStamp()] elif (locat==location[1]): tempc=random.choice(item1) out=[locat,random.choice(items),getTimeStamp()] elif (locat==location[2]): tempc=random.choice(item2) out=[locat,random.choice(itemw),getTimeStamp()] elif (locat==location[3]): tempc=random.choice(item3) out=[locat,random.choice(iteme),getTimeStamp()] return out
def gen(filename, start, end, filters): with open(filename, 'w') as f: dt = start while dt < end: f.write(dt.strftime("%Y%m%d%H%M%S") + ":" + u",".join(map(unicode, random.choice(src))) + "\n") dt = dt + tdelta if filters is not None and dt < end and filters(dt): print 'next ' + dt.strftime("%Y-%m-%d %H:%M:%S") print 'finish write to ' + filename + "from " + start.strftime("%Y-%m-%d %H:%M:%S") + " to " + end.strftime("%Y-%m-%d %H:%M:%S")
def rolloutUniform(self, gameState, history, depth): "*** YOUR CODE HERE ***" if depth > self.depth or gameState.isWin() or gameState.isLose(): return 0 # rollout policy here is to choose an action uniformly from the actions bestAction = random.choice(gameState.getLegalPacmanActions()) nextGameState, observation, reward = gameState.generateStateObservationReward(self, self.ghostAgents, bestAction) totalReward = reward + self.gamma * self.rollout(nextGameState, history + (bestAction, observation), depth + 1) return totalReward
def selection(pop, parent_chance=0.25, parent_selection_threshold=0.5): parents = [] pop.sort() # sorted(pop, key=fitness) # unfinished parents.append(pop[:int(len(pop)*parent_chance)]) for indiv in pop: if indiv in parents: pass else: if (random() > parent_selection_threshold): parents.append(indiv) if len(parents) == 1: parents.append(random.choice(pop)) return parents
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 process_request(self, request, spider): USER_AGENT_LIST = [ 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.1.6000', 'Opera/9.0 (Macintosh; PPC Mac OS X; U; en)', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20120813 Firefox/16.0', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' ] agent = random.choice(USER_AGENT_LIST) # 从上面列表中随机抽取一个代理 request.headers['User_Agent'] = agent # 设置请求头的用户代理
def randomWalk (start, adjList, len): """Find a path in graph of langth len by following a random edge.""" # Choose a random starting place. u = start path = [u.center] for i in range (len): # Choose a random edge coming out of u. choice = random.choice ([edge for edge in adjList.query (u)]) # Append the end of that edge to the path. path.append (choice.v.center) # Set the current vertex to this new vertex u = choice.v return path
def muatation_deviation_based(population: [Genome], teams:[Team],distances_avg,distances,cities,dates,fixture): fitness_values = [] for genome in population: value = fitness(genome,distances_avg,distances,cities,dates,fixture) fitness_values.append(value) std = statistics.stdev(fitness_values) if std < 10: random_number_genome = random.randint(0, len(population)-1) random_number_team = random.randint(0, len(population[0])-1) team = random.choice(teams) mutated_population = population # print("mute",random_number_genome,random_number_team, mutated_population[random_number_genome][random_number_team], "por:",team) mutated_population[random_number_genome][random_number_team] = team else: return population return mutated_population
def process_request(self, request, spider): try: ip_list_https = ['https://100.100.100.100:440'] ip_list_http = ['http://100.100.100.100:440'] if request.url[0:5] == 'https': ip_list = ip_list_https else: ip_list = ip_list_http ip = random.choice(ip_list) logging.info('request url=' + request.url) logging.info('proxy ip=' + ip) request.meta['proxy'] = ip except Exception as e: logging.info( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' Exception: ' + str(e))
def generarClavePublica(): p = sy.randprime(50, 50000) q= sy.randprime(50,50000) n = p*q phi = ((p-1)*(q-1)) print (phi) e = random.choice(primosEntreSi(phi)) print ('p:', p, 'q:', q, 'n:', n, 'phi:', phi, 'e:', e) print('E', e, 'N', n) clave = [] clave.append(n) clave.append(e) clave.append(phi) return clave
def get_random_cafe(): cafes = db.session.query(Cafe).all() random_cafe = random.choice(cafes) return jsonify( cafe={ "id": random_cafe.id, "name": random_cafe.name, "map_url": random_cafe.map_url, "img_url": random_cafe.img_url, "location": random_cafe.location, "seats": random_cafe.seats, "has_toilet": random_cafe.has_toilet, "has_wifi": random_cafe.has_wifi, "has_sockets": random_cafe.has_sockets, "can_take_calls": random_cafe.can_take_calls, "coffee_price": random_cafe.coffee_price, })
def _selectOneToDelete(self): pathlist = map(lambda x : os.path.join(self.workingDir, x), os.listdir(self.workingDir)) candidateList = [xfile for xfile in pathlist if os.path.isfile(os.path.join(self.workingDir, xfile))] if not len(candidateList) > 0: return None if self.deletePolicy == DELETE_RANDOM: return random.choice(candidateList) else: sortedByLastChange = sorted(candidateList, key=os.path.getmtime) if self.deletePolicy == DELETE_NEWEST_FIRST: return sortedByLastChange[-1] elif self.deletePolicy == DELETE_OLDEST_FIRST: return sortedByLastChange[0]
def generate_test_item(template, student): test_item = TestItem.objects.create(template=template, student=student) prototypes = Prototype2Test.objects.filter(test=template).order_by('index') for i, prototype in enumerate(prototypes): problem_heads = ProblemHead.objects.all(prototype=prototype) problem_head = random.choice(problem_heads) head_item = ProblemHeadItem.objects.create(test=test_item, problem_head=problem_head, index=i) points = ProblemPoint.objects.filter(problem_head=problem_head) for j in range(points): ProblemPointItem.objects.create(problem_item=head_item, num_in_problem=j)
def genesis(self,numPlayers,numMonsters,x_space,y_space): self.x_space = x_space self.y_space = y_space for count in range(numPlayers): #Initializes each player at a random spot in the "center quarter" of the stage. startPointX, startPointY = randint(self.x_space*1/4,self.x_space*3/4), randint(self.y_space*1/4,self.y_space*3/4) print('startX: {} startY: {}'.format(startPointX, startPointY)) self.players.append(Player(startPointX, startPointY, count+1)) monsterStartPoints = ((0, 0), (0, y_space-1), (x_space-1, y_space-1), (x_space-1, 0)) for count in range(numMonsters): startPointX, startPointY = random.choice(monsterStartPoints) self.monsters.append(Monster(startPointX, startPointY)) print('Let there be light! I am a {}x{} world, with {} players and {} monsters.'.format(self.x_space,self.y_space,len(self.players),len(self.monsters))) # TODO Remove print check
def welcome(update, context): for new_user_obj in update.message.new_chat_members: chat_id = update.message.chat.id new_user = "" message_rnd = random.choice(message_list) WELCOME_MESSAGE = open(welcome_dir + message_rnd, 'r', encoding='UTF-8').read().replace("\n", "") try: new_user = "******" + new_user_obj['username'] except Exception as e: new_user = new_user_obj['first_name'] WELCOME_MESSAGE = WELCOME_MESSAGE.replace("username", str(new_user)) print(WELCOME_MESSAGE) context.bot.send_message(chat_id=chat_id, text=WELCOME_MESSAGE, parse_mode=telegram.ParseMode.HTML)
def setup_tibanna(tibanna_id=None, buckets=None): try: subprocess.check_call(f'tibanna --version', shell=True) except subprocess.CalledProcessError: logger.err('Error: tibanna is not installed. Please run `pip install -S tibanna`') sys.exit(1) if not tibanna_id: tibanna_id = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(8)) assert not check_tibanna_id_exists(tibanna_id), 'Random tibanna ID already exists: ' + tibanna_id step_func_name = f'tibanna_unicorn_{tibanna_id}' if not check_tibanna_id_exists(tibanna_id): buckets_str = '' if not buckets else ('-b ' + ','.join(buckets)) run_simple(f'tibanna deploy_unicorn -g {step_func_name} {buckets_str} --no-setenv') return step_func_name
def answer_fifth(message): if not message.text.isdigit(): bot.send_message(message.chat.id, 'Только числа!', parse_mode='Markdown') return None if int(message.text) == 29: secrete_liter = random.choice(secrete_word) secrete_word.remove(secrete_liter) bot.send_message(message.chat.id, text, parse_mode='Markdown') bot.send_message(message.chat.id, secrete_liter, parse_mode='Markdown') ans_seq.pop() bot.send_message(message.chat.id, 'Введи слово', parse_mode='Markdown') ans_seq.append('holms') else: text = 'Еще варианты? Умник...' bot.send_message(message.chat.id, text, parse_mode='Markdown')
def pick_treasure(self): weapon_bonus = Weapon("Spike", 25) spell_bonus = Spell("Silver", 30, 7) mana_bonus = 6 health_potion_bonus = 10 T = random.choice( [mana_bonus, health_potion_bonus, weapon_bonus, spell_bonus]) if T == mana_bonus: self.hero.take_mana(mana_bonus) print("Found mana. Hero mana is now {}".format(self.hero.mana)) elif T == health_potion_bonus: self.hero.take_healing(health_potion_bonus) print("Found health potion bonus.Hero health is {}".format(self.hero.health)) elif T == weapon_bonus: self.hero.equip(T) print("Found a weapon.") else: self.hero.learn(T) print("Found a spell.")
def quicksort(numbers, direction): if len(numbers) <= 1: return numbers else: randomNumber = random.choice(numbers) small = [] big = [] element = [] for number in numbers: if number < randomNumber: small.append(number) elif number > randomNumber: big.append(number) else: element.append(number) if direction == "asc": return quicksort(small, "asc") + element + quicksort(big, "asc") else: return quicksort(big, "des") + element + quicksort(small, "des")
def createDoors(self): for room in self.rooms: (x, y) = room.center() wall = random.choice(["north", "south", "east", "west"]) if wall == "north": wallX = int(x) wallY = int(room.y1 + 1) elif wall == "south": wallX = int(x) wallY = int(room.y2 - 1) elif wall == "east": wallX = int(room.x2 - 1) wallY = int(y) elif wall == "west": wallX = int(room.x1 + 1) wallY = int(y) self.level[wallX][wallY] = 0
def cut_and_paste_poem(base_poem, seeder, length, cut_length, find_length): import random poem = seeder while len(poem) < length: if len(seeder) == 0: index = random.randint(0, len(base_poem) - cut_length) sentence = base_poem[index:index + cut_length] poem += '\n\n' + sentence seeder = sentence[-find_length:] else: all_occurence = list(find_all(base_poem, seeder)) # Not found anything if len(all_occurence) == 0: seeder = seeder[1:] else: index = random.choice(all_occurence) + len(seeder) sentence = base_poem[index:index + cut_length] poem += sentence seeder = sentence[-find_length:] return poem
def add_random(self, movie_list, seed=None): random_movie = None if seed is None: loop = True while loop: random_movie = random.choice(movie_list) if random_movie not in self.__watchlist: self.__watchlist.append(random_movie) break else: ran = Random(seed) loop = True while loop: random_movie = movie_list[ran.randint(0, len(movie_list) - 1)] if random_movie not in self.__watchlist: self.__watchlist.append(random_movie) break return random_movie
def eat_agent(self,agent_id): seed=random.random() fire=random.choice([False,True]) eat_mass=0.0 self.fire_attempts+=1 #self.d_fat-=self.dragon.fire_cost if seed<self.world.hunt_success_prob: #print("eat large agent",self.agents[agent_id].name) if "large" in self.agents[agent_id].name: eat_mass=self.world.l_biomas self.l_eaten+=1 elif "small" in self.agents[agent_id].name: eat_mass=self.world.s_biomas self.s_eaten+=1 del self.agents[agent_id] del self.world.agents[agent_id] del self.action_space[agent_id] self.changed_in_step=True self.dragon.daily_income-=eat_mass #print('eaten ',eat_mass, self.dragon.daily_income) self.d_mass+=eat_mass
def diagram_four(): driver.find_element_by_xpath( "/html/body/section/div/ui-view/div/div[4]/div/div[1]/div[16]/div/a/div[2]" ).click() driver.find_element_by_xpath( "/html/body/section/div/ui-view/div[1]/div[1]/button").click() driver.find_element_by_xpath( "/html/body/section/div/ui-view/div[2]/div/div/div/div/div/button/span" ).click() driver.find_element_by_xpath( "/html/body/section/div/ui-view/div[3]/div/div[5]/div[3]/h3[1]/button/span" ).click() input = driver.find_element_by_xpath( "/html/body/section/div/ui-view/div[3]/div/div[5]/div[4]/textarea") for i in range(300): input.send_keys(random.choice(string.ascii_letters)) time.sleep(5) driver.find_element_by_xpath( "/html/body/section/div/ui-view/div[3]/div/div[5]/button[2]").click() driver.find_element_by_xpath( "/html/body/div/div/div/div/div/div/h3/div/a").click()
def logic(): ###hole den entry wert und speichere ihn try: howMany = int(self.EntryInt.get()) for i in range(howMany): randomNr1 = str(randrange(10)) randomNr2 = str(randrange(10)) randomNr3 = str(randrange(10)) randomNr4 = str(randrange(10)) randomNr5 = str(randrange(10)) randomLetter1 = random.choice(string.ascii_letters) randomLetter2 = random.choice(string.ascii_letters) randomLetter3 = random.choice(string.ascii_letters) randomLetter4 = random.choice(string.ascii_letters) randomLetter5 = random.choice(string.ascii_letters) randomLetter6 = random.choice(string.ascii_letters) ##xx000 aCombi = link+randomLetter1+randomLetter2+randomNr1+randomNr2+randomNr3+randomNr4 ##xx0x0x bCombi = link+randomLetter1+randomLetter2+randomNr1+randomLetter3+randomNr2+randomLetter4 ##00xxxx cCombi = link+randomNr1+randomNr2+randomLetter1+randomLetter2+randomLetter3+randomLetter4 ##xx00xx dCombi = link+randomLetter1+randomLetter2+randomNr1+randomNr2+randomLetter3+randomLetter4 ##xxxxxx eCombi = link+randomLetter1+randomLetter2+randomLetter3+randomLetter4+randomLetter5+randomLetter6 ##xxx000 fCombi = link+randomLetter1+randomLetter2+randomLetter3+randomNr1+randomNr2+randomNr3 yourLinks = random.choice([aCombi, bCombi, cCombi, dCombi, eCombi, fCombi]) self.listBox.insert(END, yourLinks) except ValueError: messagebox.showwarning("No indication set", "Please indicate the number of links you want to create.\n\nNavigate to the 'links' entry box and enter a number.\n\nHave fun! :)")
def RandomPath(): [pointsArray, pathsArray, gains, costMatrix] = readData() maxGain = -sys.float_info.max minGain = sys.float_info.max suma = 0 f2 = open('randomPath.txt', 'w') for root in pointsArray: max = -1 resetPoints(pointsArray) choicePointArray = pointsArray[:] path = Path(root) choicePointArray.remove(root) pointNo = randint(3, 99) for i in range(0, pointNo-1): toAdd = random.choice(choicePointArray) path.addVertex(toAdd) choicePointArray.remove(toAdd) path.addLastVertex(root) f2.write(' '.join(path.printPath('i')) + '\n')
def getMove( data, plays_c ): #snake strategy. Not much efficient as hardcoded stuffs are here. sc, mv = float('-inf'), 5 mx = data.max() for move in getAvailableMoves(data): moved = c(data.copy(), move) if mx == data[0][0] and moved.max() != moved[0][0]: continue #stuck the head; temp added if (moved == data).all(): continue score = 0 score += minimaxab(moved.copy(), -np.inf, np.inf, plays_c, False) if move == 0 or move == 2: score += 10000 #motivation on up or left. t_sc = score if t_sc > sc: sc = t_sc mv = move elif t_sc == sc: if mv in [0, 2]: continue mv = random.choice([mv, move]) return mv
def splitLeaf(self): # begin splitting the leaf into two children if (self.child_1 != None) or (self.child_2 != None): return False # This leaf has already been split ''' ==== Determine the direction of the split ==== If the width of the leaf is >25% larger than the height, split the leaf vertically. If the height of the leaf is >25 larger than the width, split the leaf horizontally. Otherwise, choose the direction at random. ''' splitHorizontally = random.choice([True, False]) if (self.width / self.height >= 1.25): splitHorizontally = False elif (self.height / self.width >= 1.25): splitHorizontally = True if (splitHorizontally): max = self.height - self.MIN_LEAF_SIZE else: max = self.width - self.MIN_LEAF_SIZE if (max <= self.MIN_LEAF_SIZE): return False # the leaf is too small to split further split = random.randint(self.MIN_LEAF_SIZE, max) # determine where to split the leaf if (splitHorizontally): self.child_1 = Leaf(self.x, self.y, self.width, split) self.child_2 = Leaf(self.x, self.y + split, self.width, self.height - split) else: self.child_1 = Leaf(self.x, self.y, split, self.height) self.child_2 = Leaf(self.x + split, self.y, self.width - split, self.height) return True
def challengeHOF(challenger, HOF, reqwinpercentage = 0.5): if len(HOF) < 5: return True numdefenders = len(HOF) / 5 #numdefenders = 50 defenders = [0] * numdefenders enemies = range(len(HOF)) for i in xrange(numdefenders): selection = random.choice(enemies) enemies.remove(selection) defenders[i] = selection challwins = 0 gamecount = 0 for champindex in defenders: if greatjourney.game(challenger, HOF[champindex]) == 1: challwins += 1 gamecount += 1 if challwins >= reqwinpercentage * numdefenders: return True if challwins + (numdefenders - gamecount) < int(reqwinpercentage * numdefenders): return False return False
def random_word(tokens, tokenizer): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here) :return: (list of str, list of int), masked tokens and related labels for LM prediction """ output_label = [] for i, token in enumerate(tokens): prob = random.random() # mask token with 15% probability if prob < 0.15: prob /= 0.15 # 80% randomly change token to mask token if prob < 0.8: tokens[i] = "[MASK]" # 10% randomly change token to random token elif prob < 0.9: tokens[i] = random.choice(list(tokenizer.vocab.items()))[0] # -> rest 10% randomly keep current token # append current token to output (we will predict these later) try: output_label.append(tokenizer.vocab[token]) except KeyError: # For unknown words (should not occur with BPE vocab) output_label.append(tokenizer.vocab["[UNK]"]) logger.warning( "Cannot find token '{}' in vocab. Using [UNK] insetad". format(token)) else: # no masking token (will be ignored by loss function later) output_label.append(-1) return tokens, output_label
def get_random_cafe(): cafes = db.session.query(Cafe).all() random_cafe = random.choice(cafes) return jsonify( cafe={ # Omit the id from the response # "id": random_cafe.id, "name": random_cafe.name, "map_url": random_cafe.map_url, "img_url": random_cafe.img_url, "location": random_cafe.location, # Put some properties in a sub-category "amenities": { "seats": random_cafe.seats, "has_toilet": random_cafe.has_toilet, "has_wifi": random_cafe.has_wifi, "has_sockets": random_cafe.has_sockets, "can_take_calls": random_cafe.can_take_calls, "coffee_price": random_cafe.coffee_price, } })
def process_request(self, request, spider): user_agent_list = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)", "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" ] agent = random.choice(user_agent_list) request.headers['User_Agent'] = agent
def new_wormhole(self, cells, obstacles, cells_op=[]): corners = [[1, 1], [1, self.height - 2], [self.width - 2, 1], [self.width - 2, self.height - 2]] forbiddens = [] forbiddens.extend(cells) forbiddens.extend(obstacles) forbiddens.extend(cells_op) new_wormhole = [1, 1] if contains(forbiddens, corners): while new_wormhole in forbiddens: new_wormhole = [ randint(1, self.width - 2), randint(1, self.height - 2) ] self.wormhole = new_wormhole return new_wormhole else: while new_wormhole in forbiddens: new_wormhole = random.choice(corners) self.wormhole = new_wormhole return new_wormhole
def get_request(url, text_only=False, **kwargs): _proxy = kwargs.get("proxy") _rand_proxy = None headers = { 'User-Agent': get_user_agent(), 'Accept-Encoding': 'gzip, deflate', } if kwargs.get('xml_http_request', False): headers['X-Requested-With'] = 'XMLHttpRequest' if _proxy and len(_proxy) > 0: try: _rand_proxy = random.choice(_proxy) except IndexError as error: print("Proxy Failed : {0}".format(error)) print("Continuing Without Proxy.") _rand_proxy = None proxy = { "http": _rand_proxy, "https": _rand_proxy } logging.debug('GET url: {0}'.format(url)) logging.debug('GET proxy: {0}'.format(proxy)) sess = requests.session() connection = sess.get(url, headers=headers, proxies=proxy) if connection.status_code != 200: print("Whoops! Seems like I can't connect to website.") print("It's showing : %s" % connection) print("Run this script with the --verbose argument and report the issue along with log file on Github.") print("Can't connect to website %s" % url) return None else: if text_only: return connection.content return json.loads(connection.text.encode("utf-8"))
def cmh_autotune(self, module, message, additional_data, cm): message = message[len(self.CONTROL_AUTOTUNE) + 2:] # get tune type, requested record type, length and encoding for crafting the answer (query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7]) if self.DNS_proto.get_RR_type(RRtype)[0] == None: return True # extra parameters added to be able to response in the proper way additional_data = additional_data + ( True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0]) if (query_type == 0) or (query_type == 3): # record && downstream length discovery message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) if query_type == 1: # A record name length discovery message = struct.pack("<i", binascii.crc32(message[7:])) if query_type == 2: # checking download encoding, echoing back request payload message = message[7:] module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT + message, additional_data) return True
def auto_click(articles, proxies=[]): if not articles: return for ip in proxies: useful = is_useful(ip) print(ip, useful) if not useful: continue for _ in range(len(articles)): article_link = random.choice(articles) print(ip, article_link) try: requests.get(protoarticle(ip, article_link), timeout=TIME_OUT, headers=req_headers, proxies=ip2proxy(ip)) print((article_link, "ok")) time.sleep(0.25) except Exception as e: print((article_link, "fail", e)) time.sleep(0.1) break
def algo_main(parameters): popsize = parameters[3] bestindividual = select_best(pop) for k in parameters[2]: selcted = selction(pop, parameters[3]) newoff = [] while len(newoff) != popsize: off = [random.choice(selcted[g] for g in xrange(2))] if random.random() > c_prob: crossoff = crossoperate(off) crossoff_fit = fitness_get(crossoff) if random.random() > m_prob: mutaoff = mutation(crossoff, parameters) mutaoff_fit = fitness_get(mutaoff) newoff.append({'Gene':mutaoff, 'fitness':mutaoff_fit}) else: newoff.append({'Gene':crossoff, 'fitness':crossoff_fit}) pop = newoff best_ind = select_best(pop) fits_all = [pop[k]['fitness'] for k in len(pop)] if best_ind['fitness'] > bestindividual: bestindividual = best_ind
def studenttoken(request, studentid): try: s = Studentregistration.objects.get(id=studentid) name = request.POST['name'] email = request.POST['email'] category = request.POST['category'] description = request.POST['description'] studenttoken = ''.join([random.choice(string.digits + string.ascii_letters) for i in range(0, 6)]) q = Query2() q.name = name q.email = email q.category = category q.description = description q.token = studenttoken q.studentregistration = s q.save() except: msg = "Something wents wrong" return render(request, 'student/query2.html', {'msg': msg}) else: msg = "You are successfully login." return render(request, 'student/studentprofile.html', {'msg': msg,'q': q,})
def __call__(self, url): result = None if self.cache: try: result = self.cache[url] except KeyError: print url + " is not available in cache!" pass else: if self.num_retries > 0 and 500 <= result['code'] < 600: result = None else: print url + " is available in cache!" if result is None: self.throttle.wait(url) proxy = random.choice(self.proxies) if self.proxies else None headers = {'User-agent': self.user_agent} result = self.download(url, headers, proxy, self.num_retries) if self.cache and result is not None: self.cache[url] = result else: return None return result['html']
def f(name): for i in [1,2]: try: us_set=['Mozilla','IE','Opera','Chrome','Magic','theSage','Iceweasel','Rockmelt'] ua=random.choice(us_set) req=urllib2.Request('http://graph.facebook.com/'+name+'?fields=id,name',headers={'User-Agent':ua}) r=urllib2.urlopen(req) r=r.read() r=eval(r) result.append((r['id'],r['name'])) cnt.append(True) if len(names)>550: time.sleep(60)# to prevent blocking of ip address by limiting rate except Exception as e: print e.reason,len(cnt) if 'Nont Found' in e.reason: if len(names)>550: time.sleep(60)# to prevent blocking of ip address by limiting rate break if 'Forbidden' in e.reason: time.sleep(600) if len(names)>550: time.sleep(60)# to prevent blocking of ip address by limiting rate pass
def random_available_cell(self): cells = self.available_cells() if len(cells): return random.choice(cells)
'9223':'Bail and Bond Payments', '9311':'Tax Payments Government Agencies', '9399':'Government Services (Not Elsewhere Classified)', '9402':'Postal Services Government Only', '9405':'U.S. Federal Government Agencies or Departments', '9950':'Intra Company Purchases' }; with open('CreditCard_Transaction_MerchantCredits.csv','w') as f1: writer=csv.writer(f1, delimiter=',',lineterminator='\n',) writer.writerow(['rownum'] +['Account_Number'] + ['Merchant_Name']+['Merchant_Category_Code']+['Merchant_Category_Desc'] +\ ['Post_Date'] + ['Transaction_Date'] + ['Transaction_Type'] +['Merchant_Country']+['Credit_Limit']+['Amount']) for i in range(10): dt=datetime.now().strftime("%Y-%m-%d %H:%M:%S") row = [str(i)+'_'+dt]+[random.choice(python_account_ID.accountid)] +[gen_data.create_company_name()] cat=random.choice(Merchant_Category) row.append(cat) row.append(All_Merchant_Cat[cat]) date1= gen_data.create_date(past=True) date2=date1-timedelta(days=1) row.append(date1) row.append(date2) #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)) tmpAmt = randrange(1,limit,100) row.extend([random.choice(Transaction_Type_Credits),random.choice(Country),limit,tmpAmt]) writer.writerow(row)
def main(): # welcome to the danger zone parser = argparse.ArgumentParser( # random comment here for no reason ;) formatter_class=argparse.RawTextHelpFormatter, prog='spry', description='++++++++++++++++++++++++++++\n+++ SPRY +++++++++++++++++++\n+++ s0c1@l m3d1a sc@nn3r +++\n++++++++++++++++++++++++++++', epilog = '''EXAMPLE: \n check instagram \n spry jamesanthonycampbell \n ''') parser.add_argument('username', help='specific username, like realdonaldtrump') parser.add_argument('-p', '--proxy', help='proxy in the form of 127.0.0.1:8118', nargs=1, dest='setproxy', required=False) parser.add_argument('-w', '--wait', help='max random wait time in seconds, \n5 second default (randomly wait 1-5 seconds)', dest='setwait', nargs='?',const=3,type=int,default=3) parser.add_argument('-u', '--user-agent', help='override random user-agent\n(by default randomly selects between \n+8500 different user agent strings', dest='useragent', nargs='?',const='u',default='u') parser.add_argument('--report', dest='reporting', action='store_true') parser.add_argument('-v','--verbose-useragent',dest='vu',action='store_true') parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version='Version: '+__version__)) parser.set_defaults(reporting=False,vu=False) args = parser.parse_args() cprint(welcomer,'red') # args strings username = args.username setproxy = args.setproxy # note, the correct way to check if variable is NoneType if setproxy != '' and setproxy is not None: proxyoverride = True if '9050' in setproxy[0] or '9150' or 'tor' in setproxy[0]: usingtor = True else: usingtor = False else: proxyoverride = False setwait = args.setwait reporting = args.reporting useragent = args.useragent vu = args.vu if useragent == 'u': overrideuseragent = False useragent = random.choice(useragents) # if user agent override not set, select random from list if vu: cprint('\nUseragent set as %s\n' % (useragent,),'blue') headers = {'User-Agent': useragent} i = 0 # counter for how many are 200's social_networks_list=['https://twitter.com/','https://www.instagram.com/','https://www.linkedin.com/in/','https://foursquare.com/','https://www.flickr.com/photos/','https://www.facebook.com/','https://www.reddit.com/user/','https://new.vk.com/','https://github.com/','https://ok.ru/','https://www.twitch.tv/','https://venmo.com/','http://www.goodreads.com/','http://www.last.fm/user/','https://api.spotify.com/v1/users/','https://www.pinterest.com/','https://keybase.io/','https://bitbucket.org/','https://pinboard.in/u:','https://disqus.com/by/','https://badoo.com/profile/','http://steamcommunity.com/id/','http://us.viadeo.com/en/profile/','https://www.periscope.tv/','https://www.researchgate.net/profile/','https://www.etsy.com/people/','https://myspace.com/','http://del.icio.us/','https://my.mail.ru/community/','https://www.xing.com/profile/'] totalnetworks = len(social_networks_list) # get the total networks to check print('\n\n[*] Starting to process list of {} social networks now [*]\n\n'.format(totalnetworks)) for soc in social_networks_list: # get domain name domainname = urlparse(soc).netloc domainnamelist = domainname.split('.') for domainer in domainnamelist: if len(domainer) > 3 and domainer != 'vk' and domainer != 'ok' and domainer != 'last' and domainer != 'mail': realdomain = domainer elif domainer == 'vk': realdomain = domainer elif domainer == 'ok': realdomain = domainer+'.ru' elif domainer == 'last': realdomain = domainer+'.fm' elif domainer == 'mail': realdomain = domainer+'.ru' # get proxy settings if any if proxyoverride == True: if usingtor: socks_proxy = "socks5://"+setproxy[0] proxyDict = { "http" : socks_proxy } else: #print(setproxy) http_proxy = "http://"+setproxy[0] https_proxy = "https://"+setproxy[0] proxyDict = { "http" : http_proxy, "https" : https_proxy } sleep(randint(1,setwait)) sys.stdout.flush() # try to load the social network for the respective user name # make sure to load proxy if proxy set otherwise don't pass a proxy arg # DONT FORGET TO HANDLE LOAD TIMEOUT ERRORS! - ADDED exception handlers finally 2-5-2017 JC if proxyoverride == True: try: r=requests.get(soc+username,stream=True, headers=headers, proxies=proxyDict) except requests.Timeout as err: print(err) continue except requests.RequestException as err: print(err) continue else: try: r=requests.get(soc+username,stream=True, headers=headers) except requests.Timeout as err: print(err) continue except requests.RequestException as err: print(err) continue # switch user agents again my friend if overrideuseragent == False: useragent = random.choice(useragents) # if user agent override not set, select random from list if vu: # if verbose output then print the user agent string cprint('\nUseragent set as %s\n' % (useragent,),'blue') if soc == 'https://www.instagram.com/' and r.status_code == 200: #print(r.text) soup = BeautifulSoup(r.content,'html.parser') aa = soup.find("meta", {"property":"og:image"}) # test instagram profile image print #print (aa['content']) # this is the instagram profile image instagram_profile_img = requests.get(aa['content']) # get instagram profile pic open('./'+username+'.jpg' , 'wb').write(instagram_profile_img.content) #exit() try: total_length = int(r.headers.get('content-length')) except: total_length = 102399 for chunk in progress.dots(r.iter_content(chunk_size=1024),label='Loading '+realdomain): sleep(random.random() * 0.2) if chunk: #sys.stdout.write(str(chunk)) sys.stdout.flush() sys.stdout.flush() #print(r.text) if r.status_code == 200: cprint("user found @ {}".format(soc+username),'green') i = i+1 else: cprint("Status code: {} no user found".format(r.status_code),'red') print('\n\n[*] Total networks with username found: {} [*]\n'.format(i)) if reporting: # if pdf reporting is turned on (default on) create_pdf(username, i) cprint('Report saved as {}-report.pdf. \nTo turn off this feature dont pass in the --report flag.\n'.format(username),'yellow')
row.append('SEG_MODEL_TYPE') row.append('SEG_MODEL_NAME') row.append('SEG_MODEL_GROUP') row.append('SEG_M_GRP_DESC') row.append('SEG_MODEL_SCORE') row.extend(['ARMS_MANUFACTURER','AUCTION','CASHINTENSIVE_BUSINESS','CASINO_GAMBLING','CHANNEL_ONBOARDING','CHANNEL_ONGOING_TRANSACTIONS',\ 'CLIENT_NET_WORTH','COMPLEX_HI_VEHICLE','DEALER_PRECIOUS_METAL','DIGITAL_PM_OPERATOR','EMBASSY_CONSULATE','EXCHANGE_CURRENCY','FOREIGN_FINANCIAL_INSTITUTION',\ 'FOREIGN_GOVERNMENT','FOREIGN_NONBANK_FINANCIAL_INSTITUTION','INTERNET_GAMBLING','MEDICAL_MARIJUANA_DISPENSARY','MONEY_SERVICE_BUSINESS','NAICS_CODE',\ 'NONREGULATED_FINANCIAL_INSTITUTION','NOT_PROFIT','OCCUPATION','PRIVATELY_ATM_OPERATOR','PRODUCTS','SALES_USED_VEHICLES','SERVICES','SIC_CODE',\ 'STOCK_MARKET_LISTING','THIRD_PARTY_PAYMENT_PROCESSOR','TRANSACTING_PROVIDER']) writer.writerow(row) for i in range(16800000): row = next(reader) rel = random.choice(python_account_ID.accountid)*max((randrange(0,10000,1)-9999),0) if rel <> 0: row.append(rel[0]) row.append(random.choice(Related_Type)) else: row.append('') row.append('') party_start=gen_data.create_date() Consent_Share = random.choice(Yes_No_Consent) row.extend([random.choice(Party_Type) , random.choice(Party_Relation) , party_start , gen_data.create_date() , \ random.choice(Yes_No), random.choice(Yes_No) , gen_data.create_date() , randrange(0,100,1) , random.choice(Official_Lang)]) if Consent_Share == 'Yes':
def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size))