def execute(self, *args, **options): with transaction.atomic(): for ii in range(10): for jj in ['Projektowanie Webaplikacji', 'Analiza Matematyczna', 'Programowanie Obiektowe']: models.Course.objects.create( name = "{} {}".format(jj, ii) ) for ii in range(100): models.Room.objects.create( room_name="Sala {}".format(ii), number_of_places=random.randint(5, 15) ) for ii in range(100): models.Lecturer.objects.create( name = names.get_full_name() ) rooms = models.Room.objects.all() lecturers = models.Lecturer.objects.all() for year in [2013, 2014, 2015]: for course in models.Course.objects.all(): for ii in range(3): date_from = datetime.time(random.randint(8, 18)) models.CourseInstance.objects.create( course = course, room = random.choice(rooms), lecturer = random.choice(lecturers), time_from=date_from, time_to = datetime.time(date_from.hour+2), year=year, weekday = random.randint(0, 7) ) for ii in range(1000): student = models.Student.objects.create( name = names.get_full_name() ) for jj in range(3): student.courses.add(random.choice(models.Course.objects.all())) student.save() for s in models.Student.objects.all(): if random.randint(0, 10) != 5: for c in s.courses.all(): for ii in range(10): models.Mark.objects.create( student = s, course=c, mark = random.randint(2, 5) )
def stations(request): if request.method == 'PUT': # add a new station jreq = json.loads(request.raw_post_data) station = Station(name=jreq['name']) # set default alert level station.alertlevel = AlertLevel.objects.order_by("-threshold")[:1].get() # build the default map station.wide = 3 station.high = 3 airlock = Module.objects.filter(is_entry=True)[:1].get() station.save() cell = StationCell(station=station, x=1, y=1, module=airlock) cell.save() # create starting crew name = names.get_full_name() person = Person(station=station, stationcell=cell, name=name) person.save() # set up the planet planet = Planet(station=station, cargo=600, credits=10000) planet.name = "%s %i" % (names.get_last_name(), random.randint(1, 12)) planet.save() for pa in PlanetAttribute.objects.all(): s = pa.planetattributesetting_set.all().order_by('?')[0] planet.settings.add(s) """ for tg in TradeGood.objects.all(): stg = MarketTradeGood(station=station, tradegood=tg) stg.quantity = 0 stg.bid = tg.price * 0.99 stg.ask = tg.price * 1.01 stg.save() ptg = MarketTradeGood(planet=planet, tradegood=tg) ptg.quantity = 50 ptg.bid = tg.price * 0.99 ptg.ask = tg.price * 1.01 ptg.save() """ # set up recruits for ii in xrange(10): person = Person(station=station, name=names.get_full_name()) person.save() # now save station.save() # and return return { "station": station.get_json() } else: # return all objs = {} for obj in Station.objects.all(): objs[obj.pk] = obj.name return {"stations": objs}
def testTournamentMultiPlayers(): id_round=1 start_time = time.time() final_players= list() print "Number of participants [",swiss_trnmnt._participants,"]" for i in range(swiss_trnmnt._participants): # register players' name randomly using third-package names try: swiss_trnmnt.registerPlayer(names.get_full_name()) except Exception as ex: swiss_trnmnt.rollback() if ex.pgcode == '23505': # avoit duplicated player in same tournamnt swiss_trnmnt.registerPlayer(names.get_full_name()) else: raise Exception('Unexpected error registering players',str(ex)) swiss_trnmnt.rankingInit() while id_round <=swiss_trnmnt._total_rounds: print "Round=[",id_round,"]" # result of pairings for next match [(id1,name1,id2,name2),...] swiss= swiss_trnmnt.swissPairings() print '\n' print "Next match=",swiss,'\n' testMatchesRandomly(swiss,id_round) # establish winner of match randomly id_round +=1 print '--- SWISS TOURNAMENT FINISHED ---\n' print ' Final Standings' print ('ID\tNAME\t\tWINS') print ('---------------------------') final_stands=swiss_trnmnt.playerStandings() for i in final_stands: print i[0],'\t',i[1][:13],'\t',i[2] # it prints ID | NAME | WINS final_players=swiss_trnmnt.topEightPlayers() print (''' \nThe final TOP players using opponents-points for tie-break''') print ('ID\tNAME\t POSITION') print ('---------------------------') x=1 for top8 in final_players: for rows in top8: print rows[0],'\t',rows[1][:10],'\t',x x+=1 print '\n---Starting single-elimination tournament---' while id_round <=swiss_trnmnt._total_rounds+swiss_trnmnt._rounds_single: # round's number for single is 3 print "Round final=[",id_round,"]" single= swiss_trnmnt.siglePairingElimination() print "Next match=",single, '\n' testMatchesRandomly(single,id_round) # establish winner of match randomly id_round +=1 swiss_trnmnt.setWinnerTournament() swiss_trnmnt.closeTournament() print("Total execution --- %s seconds ---" % (time.time() - start_time))
def Person(self): #creating random data person = copy.deepcopy(self.person_data) #person data name = names.get_full_name() person_id = name.replace(" ","") website = "https://"+person_id+".com" email = person_id+"@yahoo.com" person_desc = names.get_full_name()\ +" "+names.get_full_name() phone = ("("+"".join([str(random.randint(0, 9)) for i in range(3)])\ +")"+"".join([str(random.randint(0, 9)) for i in range(7)])).decode() person[0]['pedigree']['true_as_of_secs'] \ = int(math.floor(time.time())) person[0]['dataunit']['person_property']['id']['person_id'] \ = person_id person[0]['dataunit']['person_property']['property']['website']\ = website person[1]['pedigree']['true_as_of_secs'] \ = int(math.floor(time.time())) person[1]['dataunit']['person_property']['id']['person_id'] \ = person_id person[1]['dataunit']['person_property']['property']['email']\ = email person[2]['pedigree']['true_as_of_secs'] \ = int(math.floor(time.time())) person[2]['dataunit']['person_property']['id']['person_id'] \ = person_id person[2]['dataunit']['person_property']['property']['desc'] \ = person_desc person[3]['pedigree']['true_as_of_secs'] \ = int(math.floor(time.time())) person[3]['dataunit']['person_property']['id']['person_id'] \ = person_id person[3]['dataunit']['person_property']['property']['name'] \ = name person[4]['pedigree']['true_as_of_secs'] \ = int(math.floor(time.time())) person[4]['dataunit']['person_property']['id']['person_id'] \ = person_id person[4]['dataunit']['person_property']['property']['phone'] \ = phone return person
def __init__(self): self.name = names.get_full_name() self.rules = [] self.gameScore = 0 self.lastScore = 0 self.scores = [] self.sequence = ''
def log_analytics(request, event, properties): try: import analytics from ipware.ip import get_ip as get_ip if settings.DEBUG: return if not hasattr(settings, "SEGMENT_IO_KEY"): logger.warning("Cannot send analytics. No Segment IO Key has been set") return if "pingdom" in request.META.get("HTTP_USER_AGENT", ""): logger.warning("Not recording analytics. Ignored pingdom bot") return api_key = settings.SEGMENT_IO_KEY ip = get_ip(request) name = names.get_full_name() uid = request.session.get("uid", name) request.session["uid"] = uid analytics.init(api_key) analytics.identify(uid, { "$name" : uid, }, { "$ip" : ip} ) analytics.track(uid, event=event, properties=properties) except Exception, e: logger.exception("Error handling analytics")
def sessione_utente(server_url, persona=None, utente=None, password=None): if not (persona or utente): raise ValueError("sessione_utente deve ricevere almeno una persona " "o un utente.") if persona: try: utenza = persona.utenza except: utenza = crea_utenza(persona=persona, email=email_fittizzia(), password=names.get_full_name()) elif utente: utenza = utente try: password_da_usare = password or utenza.password_testing except AttributeError: raise AttributeError("L'utenza è già esistente, non ne conosco la password.") sessione = crea_sessione() sessione.visit("%s/login/" % server_url) sessione.fill("auth-username", utenza.email) sessione.fill("auth-password", password_da_usare) sessione.find_by_xpath('//button[@type="submit"]').first.click() # Assicurati che il login sia riuscito. assert sessione.is_text_present(utenza.persona.nome) return sessione
def main(): authors = [] author_set = set() i = 1 while i <= AUTHOR_COUNT: author_name = names.get_full_name() if author_name not in author_set: authors.append({ 'id': i, 'name': author_name }) author_set.add(author_name) i += 1 books = [] book_set = set() i = 1 while i <= BOOK_COUNT: book_title = generate_book_title() if book_title not in book_set: books.append({ 'id': i, 'title': book_title, 'authors': get_authors(), }) book_set.add(book_title) i += 1 data = {'authors': authors, 'books': books} print json.dumps(data, indent=1)
def make_users(numb): """Generate a list of unique account names and returns the list. """ user_list = [] start = 0 # Keep running the loop until the number of unique names has been # generated and appended to the list while start != numb: user = names.get_full_name() if user not in user_list: user_list.append(user) start = start + 1 account_list = [] xnumb = 0 # Create unique account names and append to the list for user in user_list: account = '{0}{1}'.format(user.split(' ')[0].lower()[0:2], user.split(' ')[1].lower()) if account not in account_list: account_list.append(account) elif account in account_list: account_list.append('{0}{1}'.format(account, xnumb)) xnumb = xnumb + 1 return account_list
def __init__(self): ''' Initialize a user object ''' self._name = names.get_full_name() self._state = "" self._lat = "" self._long = "" self._active = False
def test_create_conflict(self): name = names.get_full_name() _, friend = yield from self._create_friend(name=name) _.close() _, friend = yield from self._create_friend(name=name) assert _.status == 409 _.close()
def __init__(self): self.name = names.get_full_name(gender='male') self.primary_position = "f" self.shot_rating = random.randint(6,14) three_point_shot = random.randint(2,5) self.three_point_rating = self.shot_rating + three_point_shot self.shots_per_game = random.randint(7,14) self.defensive_rebound_rating = random.randint(9,20) self.offensive_rebound_rating = random.randint(3,13) self.assist_rating = random.randint(5,20) self.offense_results.three_point_shot = (1, 38+random.randint(0,17)) self.offense_results.free_throw_shot = (1, random.randint(68,78)) self.defense_results.three_point_shot = (1, random.randint(28,35)) fgf_o_tweak = random.randint(0,8) fg_o_range = random.randint(6,14) fg_o_end = 11 + fgf_o_tweak + fg_o_range assist_range = random.randint(5,10) assist_end = fg_o_end + 1 + assist_range to_range = random.randint(0,13) o_foul_range = random.randint(1,10) steal_range = random.randint(2,11) steal_start = 99 - steal_range to_start = steal_start - 1 - to_range o_foul_start = to_start - 1 - o_foul_range miss_range = random.randint(14,26) miss_start = o_foul_start - 1 - miss_range if (miss_start-1) < (assist_end+1): miss_start = assist_end+2 self.offense_results.plays = {"fg_foul_range": (1, 10+fgf_o_tweak), "fg_range": (11+fgf_o_tweak, fg_o_end), "assist_range": (fg_o_end+1, assist_end), "foul_range": (assist_end+1, miss_start-1), "miss_range": (miss_start, o_foul_start-1), "block_range": None, "offensive_foul_range": (o_foul_start, to_start-1), "turnover_range": (to_start, steal_start-1), "steal_range": (steal_start, 99)} fg_d_tweak = random.randint(0,8) foul_d_tweak = random.randint(5,21) miss_d_range = random.randint(4,36) miss_d_start = fg_d_tweak + foul_d_tweak + 28 miss_d_end = miss_d_start + miss_d_range block_range = random.randint(30,36) - miss_d_range if block_range < 0: block_range = 0 block_end = miss_d_end + 1 + block_range to_d_range = random.randint(8,21) to_d_end = block_end + 1 + to_d_range #this deals with guys that block a ton of shots if block_end > 98: block_end = 98 to_d_end = 99 steal_d_start = 99 elif to_d_end > 98: to_d_end = 99 steal_d_start = 99 else: steal_d_start = to_d_end+1 self.defense_results.plays = {"fg_foul_range": None, "fg_range": (1, 23+fg_d_tweak), "assist_range": None, "foul_range": (28+fg_d_tweak, 28+fg_d_tweak+foul_d_tweak), "miss_range": (miss_d_start, miss_d_end), "block_range": (miss_d_end+1, block_end), "offensive_foul_range": None, "turnover_range": (block_end+1, to_d_end), "steal_range": (steal_d_start, 99)} self.game_stats = GameStats()
def fixture_random(): code = count(24400) # patients p = models.Patient(id=str(code.next())) # name with accent p.name = u'John Heyder Oliveira de Medeiros Galv\xe3o' p.blood_type = random.choice(models.blood_types) p.type_ = random.choice(models.patient_types) p.put() keys = [p.key] for _ in range(5): p = models.Patient(id=str(code.next())) p.name = names.get_full_name() p.blood_type = random.choice(models.blood_types) p.type_ = random.choice(models.patient_types) p.put() keys.append(p.key) # transfusions for _ in range(40): tr = models.Transfusion(id=str(code.next())) tr.patient = random.choice(keys) tr.date = random_date() tr.local = random.choice(models.valid_locals) tr.text = random_text() tr.bags = [] for _ in range(2): bag = models.BloodBag() bag.type_ = random.choice(models.blood_types) bag.content = random.choice(models.blood_contents) tr.bags.append(bag) if random.choice((True, False)): tr.tags = ['naovisitado'] else: if random.choice((True, False)): tr.tags.append('rt') else: tr.tags.append('semrt') tr.put() # users # admin user u = models.UserPrefs(id=ADMIN_USERID, name='admin', email="*****@*****.**", admin=True, authorized=True) u.put() # ordinary user1 u = models.UserPrefs(id=ORDINARY_USERID, name="user", email="*****@*****.**", admin=False, authorized=True) u.put() # ordinary user1 u = models.UserPrefs(id=ORDINARY_USERID * 2, name="user2", email="*****@*****.**", admin=False, authorized=True) u.put()
def get_random_student(id): fake = faker.Faker() name = names.get_full_name() first_last = name.lower().split(' ') email = first_last[0][0] + '.' + first_last[1] + '@innopolis.ru' address = fake.address().replace('\n', ' ') return student(id, name, email, address)
def random(cls, parent): obj = cls() obj.set_container_key(parent.identity_key()) obj.name = names.get_full_name() if parent.employees: obj.id = max([e.id for e in parent.employees]) + 1 else: obj.id = 0 return obj
def random(cls, parent): obj = cls() obj.set_container_key(parent.identity_key()) obj.name = names.get_full_name() if parent.students: obj.id = max([s.id for s in parent.students]) + 1 else: obj.id = 0 return obj
def create_new(): gender = choice(['male', 'female']) name = names.get_full_name(gender) skill = 1 salary = find_salary(skill) job = choice(['artist', 'writer']) employer = None employee_list.append(Employee(name, gender, skill, salary, job, employer, False)) return Employee(name, gender, salary, job, employer, False)
def create_incident(): incident = Incident() incident.name = names.get_full_name() incident.username = '******' % incident.name.replace(" ", "_") incident.put() dic = incident.to_dict() dic['id'] = incident.key.id() return _make_rest_response(dic, incident.key.id())
def random(cls, parent): obj = cls() obj.member_id = parent obj.name = names.get_full_name() obj.date_of_birth = datetime.date(1940, 1, 1) + datetime.timedelta(days=np.random.geometric(.00001)) n_claims = np.random.geometric(.1) obj.claims = [] for _ in range(n_claims): obj.claims.append(cls.relationships['claims'][0].random(obj)) return obj
def main(): final_file = "" for i in range(2000): random_country = random.randint(0, 56) random_position = random.randint(0, 5) final_file += get_username() + "|" + get_full_name() + "|" + countries[random_country] + "|" + positions[random_position] + "\n" #Write to a new file. a = open('Player.txt', 'w') a.write(final_file) a.close()
def create_user(): user = User() user.name = names.get_full_name() user.username = '******' % user.name.replace(" ", "_") user.put() dic = user.to_dict() dic['id'] = user.key.id() return _make_rest_response(dic, user.key.id())
def update_name_generator(nodes, amount=50): """ Generates update statements on names. :param amount: number of names to change. """ for id in random.sample(range(1, len(nodes) + 1), amount): new_name = names.get_full_name() yield 'UPDATE NODE Person(id=%d) SET name="%s";' % ( id, new_name )
def create_student_with_age_group(age_group): low = ranges[age_group]["low"] high = ranges[age_group]["high"] low_range = start_date - dateutil.relativedelta.relativedelta(months=low) high_range = start_date - dateutil.relativedelta.relativedelta(months=high) birth_date = random_date(high_range, low_range) student = Student(name=names.get_full_name(), birthdate=birth_date) student.save() return student
def generate_user_data(num_users): global users_list, x, i, users users_list = [] for x in xrange(num_users): users_list.append({ 'age': random.randint(18, 75), 'user_id': ''.join(random.choice('0123456789ABCDEF') for i in range(16)), 'name': names.get_full_name() }) users = {"users": users_list} dump_json_data('users_data.json', users) return users
def gen_user(): real_name = names.get_full_name() first_name, last_name = real_name.lower().split(' ') return User( name=gen_maybe(real_name, 0.5), email='{0}{1}{2}{3}@{4}'.format( random.choice([first_name, first_name[0]]), random.choice(string.ascii_lowercase) if gen_bool() else '', random.choice([last_name, last_name[0]]), random.randrange(10) if gen_bool() else '', random.choice(['berkeley.edu', 'gmail.com'])), is_admin=gen_bool(0.05))
def __init__(self,arrival_time,service_start_time,service_time): self.arrival_time = arrival_time self.service_start_time = service_start_time self.service_time = service_time self.service_end_time = self.service_start_time+self.service_time self.waiting_time = self.service_start_time-self.arrival_time self.name = names.get_full_name() self.total_time = self.service_end_time - self.arrival_time if self.waiting_time != 0: self.didWait = True else: self.didWait = False
def writeNames(x): """WRITES x NAMES ONTO DATA ATTACHED WITH THEIR SPECIALTIES""" for i in range(x): newName = names.get_full_name() newSpecialties = [] for i in range(int(str(math.floor(float(3*random.random())))[0]) + 1): newSpec = randomSpecialty() if newSpec in newSpecialties: newSpecialties += [] newSpecialties += [randomSpecialty()] newLine = newName + ":" + ",".join(newSpecialties) + '\n' theFile.write(newLine)
def generate(): AGE_MIN = 18 AGE_MAX = 45 is_male = True if random.randint(0, 1) == 0 else False name = names.get_full_name(gender=('male' if is_male else 'female')) gender = 'M' if is_male else 'F' age = random.randint(AGE_MIN, AGE_MAX) bartender = Bartender(name, gender, age) return bartender
def _a_lot_of_friends(self): # create a lot of friends all_names = [] for i in range(100): name = names.get_full_name() all_names.append(name) _, f = yield from self._create_friend(name=name) t = yield from _.text() print(t) assert _.status==201 _.close() return all_names
def generate_subscriber_subscribers( number_users ): total_subscribers = random.randint(1, number_users) print "Provisioning %d users in the system ..." % options.number_users subscribers = [] for i in range(1, total_subscribers): subscribers.append( {'name': names.get_full_name(), 'phone': generate_phone_number(), 'offered_services': generate_offer() }) return subscribers
def handle(self, *args, **kwargs): total = kwargs['total'] for i in range(total): member = Member.objects.create( real_name=names.get_full_name(), tz=choice(pytz.all_timezones), ) Activity.objects.create( member=member, start_time=gen_datetime().strftime("%Y-%m-%d %H:%M:%S"), end_time=gen_datetime().strftime("%Y-%m-%d %H:%M:%S") )
def handle(self, *args, **options): MEDIA = ("oil on paper", "watercolor on paper", "steel", "c-print", "digital print") for x in range(0, 100): artwork = Artwork( title=names.get_full_name(), artist_first_name=names.get_first_name(), artist_last_name=names.get_last_name(), work_year=randint(2012, 2014), size="%d x %d inches" % (randint(8, 15), randint(8, 15)), medium=choice(MEDIA), # assumes images are already in media directory" image="images/IMG_0%d.JPG" % randint(241, 250), ) artwork.save()
def display_submit_note(ibox, topic): """Display a web form in which user can edit and submit a note.""" if not storage.Inbox.does_exist(ibox): abort(404) elif not storage.Inbox.is_enabled(ibox): abort(404) fake_name = get_full_name() topic_string = topic if topic_string: topic_string = " about " + topic return render_template('submit_note.htm.j2', user=inbox, topic=topic_string, fake_name=fake_name)
def __init__(self, empty=False): if not empty: self.gender = 'male' if randrange(2) == 1 else 'female' self.portrait = get_random_portrait(self.gender) self.full_name = names.get_full_name(gender=self.gender) self.first_name = self.full_name.split(' ')[0] self.name = self.full_name.replace(' ', '_').lower() self._hash = hash(self.name) self.hunger = self.tiredness = -10 self.social = self.sanity = self.fulfilment = 0 self.witnessed = [] self.predicates = [] self.predicates.append(PredicateInstance('alive', self)) self.predicates.append(PredicateInstance('single', self))
def create_tenant_users(no_of_users_to_create, tenant_name, cluster_name='ceph'): admin_ops = UserMgmt() all_users_details = [] for i in range(no_of_users_to_create): user_details = admin_ops.create_tenant_user( user_id=names.get_first_name().lower() + random.choice(string.ascii_lowercase) + "." + str(random.randint(1, 1000)), displayname=names.get_full_name().lower(), cluster_name=cluster_name, tenant_name=tenant_name) all_users_details.append(user_details) return all_users_details
def get_valid_instagram_accounts(): try: current_name = "".join(names.get_full_name().split()) # result = os.popen("https://www.instagram.com/" + current_name) result = urllib.request.urlopen("https://www.instagram.com/" + "Tea") # print(current_name,result) status_code = result.getcode() print(status_code) if status_code == 200: soup = BeautifulSoup(result, 'html.parser') soup = soup.prettify() print(soup.find(id="window._sharedData")) return "" except: pass
def formoneJSON(): area = random.choice(schools) gender = random.choice(['women', 'men']) if gender == 'women': name = names.get_full_name('female') else: name = names.get_full_name('male') photourl = 'https://randomuser.me/api/portraits/' + gender + '/' + str(random.randint(0, 99)) + '.jpg' onejson = { 'id': str(uuid.uuid4()), 'photo': photourl, 'class': 'senior', 'name': name, 'age': random.randint(55, 100), 'email': name.lower().replace(' ', '') + '@gmail.com', 'tasks': randomize_tasks(), 'base_rent': area['rent'], 'closest_school': area['name'], 'distance': random.randint(0, 15), 'city': area['city'], 'matches': [], } return onejson
def create_contact(self, number): cust_model = self.env['res.partner'] type_of_partner = [{ 'customer': True }, { 'supplier': True }, { 'supplier': True, 'customer': True }] for i in range(number): value = {'name': str(names.get_full_name())} value.update(random.choice(type_of_partner)) cust_model.create(value) return True
async def on_message(message): if message.author == client.user: return if message.content.startswith('$names'): name_message = "_**" + random.choice(name_messages) + "**_" + '\n' new_names = [] for i in range(5): new_name = names.get_full_name() new_names.append(new_name) names_string = "`" + ", ".join(new_names) + "`" await message.channel.send(name_message + names_string)
def search(): Gender = gender.get() Type = types.get() if Gender == 'Male' and Type == "Full Name": name = names.get_full_name(gender="male") text.insert('end', name) elif Gender == 'Male' and Type == "First Name": name = names.get_first_name() text.insert('end', name) elif Gender == 'Male' and Type == "Last Name": name = names.get_last_name() text.insert('end', name) elif Gender == 'Female' and Type == "Full Name": name = names.get_full_name(gender="female") text.insert('end', name) elif Gender == 'Female' and Type == "First Name": name = names.get_first_name() text.insert('end', name) elif Gender == 'Female' and Type == "Last Name": name = names.get_last_name() text.insert('end', name)
def __init__(self, n_objects=10, n_users=10): # list of objects to consider objects = [namegenerator.gen() for _ in range(n_objects)] # fields to consider (features) fields = [ "unicorniness", "magic_skills", "number_of_trump_appearances" ] # some users users = [names.get_full_name() for _ in range(n_users)] super(ToyRandomDataset, self).__init__(objects=objects, fields=fields, users=users)
def __init__(self, orgName='nameless'): # each attribute of the class will store the response for a different field self.orgName = orgName # contact info self.contact_name = names.get_full_name() # grab a random name self.email = '{}@{}.com'.format(self.contact_name.split(' ')[0].lower(), self.orgName.lower()) # location self.city = self.set_city() self.lat, self.lng = self.set_latLng(self.city) # organization info self.jurisdiction = self.set_jurisdiction(self.city) self.fundingSource = random.choice(['EU', 'Philanthropy', 'Government', 'Other'])
def do_GET(self): self.protocol_version = 'HTTP/1.1' status = 200 if (self.path == '/'): response = names.get_full_name() elif (self.path == '/male'): response = names.get_full_name(gender='male') elif (self.path == '/female'): response = names.get_full_name(gender='female') elif (self.path == '/health'): response = "OK" else: status = 404 response = "Not Found" response = response.encode("utf8") self.send_response(status) self.send_header('Content-Type', 'text/plain; charset=utf-8') self.send_header('Content-Length', len(response)) self.end_headers() self.wfile.write(response) self.wfile.write('\n')
async def test_user_search_on_categories(self): username = "******" name = "ToshiBot" categories = await self.setup_categories() async with self.pool.acquire() as con: await con.execute("INSERT INTO users (username, toshi_id, name, is_app, is_public) VALUES ($1, $2, $3, true, true)", username, TEST_ADDRESS, name) await con.executemany("INSERT INTO app_categories VALUES ($1, $2)", [(1, TEST_ADDRESS), (2, TEST_ADDRESS)]) await con.execute("INSERT INTO users (username, toshi_id, name, is_app, is_public) VALUES ($1, $2, $3, true, true)", username + "1", TEST_PAYMENT_ADDRESS, name) await con.executemany("INSERT INTO app_categories VALUES ($1, $2)", [(2, TEST_PAYMENT_ADDRESS), (3, TEST_PAYMENT_ADDRESS)]) await con.execute("INSERT INTO users (username, toshi_id, name, is_app, is_public) VALUES ($1, $2, $3, true, true)", namegen.get_first_name(), TEST_ADDRESS_2, namegen.get_full_name()) # TODO: test different insert order for key in ['1', 'cat1']: resp = await self.fetch("/search/apps?category={}".format(key)) self.assertResponseCodeEqual(resp, 200) body = json_decode(resp.body) self.assertIn("results", body) self.assertEqual(len(body["results"]), 1) body = body["results"][0] self.assertEqual(len(body["categories"]), 2) self.assertEqual(body["categories"][0]["name"], categories[0][2]) self.assertEqual(body['categories'][0]['tag'], categories[0][1]) self.assertEqual(body["categories"][0]["id"], categories[0][0]) self.assertEqual(body["categories"][1]["name"], categories[1][2]) self.assertEqual(body['categories'][1]['tag'], categories[1][1]) self.assertEqual(body["categories"][1]["id"], categories[1][0]) resp = await self.fetch("/search/apps?category=4") self.assertResponseCodeEqual(resp, 200) body = json_decode(resp.body) self.assertIn("results", body) self.assertEqual(len(body["results"]), 0) resp = await self.fetch("/search/apps?query=toshi&category=2") self.assertResponseCodeEqual(resp, 200) body = json_decode(resp.body) self.assertIn("results", body) self.assertEqual(len(body["results"]), 2)
def populateGraph(self, numUsers, avgFriendships): """ Takes a number of users and an average number of friendships as arguments Creates that number of users and a randomly distributed friendships between those users. The number of users must be greater than the average number of friendships. """ # Reset graph self.lastID = 0 self.users = {} self.friendships = {} for _ in range(numUsers): self.addUser(get_full_name()) ids = [id for id in self.users.keys()] num_friendships = (avgFriendships * numUsers) // 2 possibilities = combinations(numUsers, 2) - 1 picked = [] while len(picked) < num_friendships: candidate = randrange(possibilities) drop = len(picked) for i in range(len(picked)): if candidate >= picked[i]: candidate += 1 else: drop = i break picked.insert(drop, candidate) possibilities -= 1 for pointer in picked: segment = len(ids) - 1 while pointer >= segment: pointer = pointer - segment segment -= 1 first_id_index = len(ids) - 1 - segment second_id_index = first_id_index + 1 + pointer self.addFriendship(ids[first_id_index], ids[second_id_index])
def arbys(email): global count s = requests.Session() url = "https://arbys.fbmta.com/members/subscribe.aspx" name = names.get_full_name().replace(" ", "") num = random.randint(1, 9999) email = name + str(num) + "@" + domain headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "Host": "arbys.fbmta.com", "Origin": "https://arbys.com", "Referer": "https://arbys.com/get-deals" } payload = { "ListID": "27917287443", "SiteGUID": "220b8a14-335c-42e0-8b07-1dfe8ec259cd", "_Theme": "27917287575", "InputSource": "W-Mobile", "Birthdate": "", "FirstName": names.get_first_name(), "LastName": names.get_first_name(), "EmailAddress": email, "Zip": "98499", "StoreCode": "00413", "DOBM": "2", "DOBD": "6", "OverThirteen": True, "MobilePhone": "" } r = s.post(url, data=payload, headers=headers) if "Thank You!" in r.content: count += 1 print("Successfully obtained deal for {} - Count = {}".format( email, count)) account = open("emails.txt", "a") account.write(email + "\n") else: arbys() print("Retrying...")
def random_email(username_also=False): """ Return a random email """ random_numbers = str(random.randrange(0, 5000)) random_years = str(random.randrange( 1833, 2050)) # 1833 when computer was invented (ABACUS) name_full = names.get_full_name() name_first = names.get_first_name() name_last = names.get_last_name() if (username_also == True): prefix = random.choice( [name_full.replace(" ", ""), name_first, name_last]) two = prefix.lower() + str(random.randrange( 0, 500)) # Random Name + number three = generate_username( 1)[0] + random_numbers # Random Username + random_number four = generate_username( 1)[0] + random_years # Random Username + Random Years five = prefix.lower() # Random name only six = prefix.lower() + str(random.randrange( 0, 500)) # Random name + Random number 0 to 500 seven = generate_username( 1)[0] + random_numbers # random Username + random number eight = generate_username( 1)[0] + random_years # Random Username + random year FINAL_EMAIL = random.choice( [two, three, four, five, six, seven, eight]) else: service = [ "@gmail.com", "@yahoo.com", "@protonmail.com", "@outlook.com", "@yandex.com" ] prefix = random.choice( [name_full.replace(" ", ""), name_first, name_last]) email_service = random.choice( [service[0], service[1], service[2], service[3], service[4]]) mail_one = prefix.lower() + email_service mail_two = prefix.lower() + str(random.randrange(0, 500)) + email_service mail_three = generate_username(1)[0] + random_numbers + email_service mail_four = generate_username(1)[0] + random_years + email_service FINAL_EMAIL = random.choice( [mail_one, mail_two, mail_three, mail_four]) return FINAL_EMAIL, prefix.lower()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-o", "--output", dest="output", required=True) parser.add_argument("-n", "--nrows", dest="nrows", type=int) args = parser.parse_args() output_file = args.output n_rows = args.nrows or 100 data = [{ "name": names.get_full_name(), "age": randint(0, 100), "n_friends": randint(0, 300) } for _ in range(n_rows)] df = pd.DataFrame(data) df = df.reindex(columns=["name", "age", "n_friends"]) df.to_csv(output_file)
def post(self, request): if "ex_id" and "image" in request.data: person, _ = Person.objects.get_or_create( ex_id=request.data["ex_id"], defaults={'name': names.get_full_name()}) image_string = request.data["image"] Catch.objects.create( person=person, image=ContentFile(base64.b64decode(image_string), name=str(request.data["ex_id"]) + time.strftime("%Y%m%d-%H%M%S") + '.jpg')) return Response(status=status.HTTP_201_CREATED) else: return Response({"error": "no external id or image provided"}, status=status.HTTP_204_NO_CONTENT)
def create_users() -> list: try: logging.info("Creating test users.") data = [] for i in range(10): data.append({ 'user': names.get_full_name(), 'password': generate_hash(f'12{i}45'), 'token': str(uuid.uuid4()) }) return data except Exception as e: logging.exception(f"Exception raised while creating users: {e}") return []
def create_username(self) -> str: try: username: str = "" username: str = names.get_full_name() username: str = username.replace( " ", random.choice(self.username_char_between)) if random.randint(0, 1) >= 1: username = username.lower() if random.randint(0, 1): username = username + "@" + str( random.choice(self.email_provider)) except Exception as e: username = self.create_username() return str(username)
def generate_pessoa (cpf_set): cpf = randint(10000000000, 99999999999) if cpf not in cpf_set: cpf_set.add(cpf) sex = ['male', 'female'] [randint(0,1)] name = names.get_full_name(gender=sex) age = randint(1,100) pessoa = { 'CPF':cpf, 'primeiro_nome':name.split(' ')[0], 'ultimo_nome':name.split(' ')[1], 'sexo':sex, 'idade': age } return pessoa return None
def insert_data(): for i in range(1, 50 + 1): surname = names.get_last_name() name = names.get_first_name() c.execute(f"INSERT INTO personen VALUES (?, ?, ?)", (name, surname, i)) conn.commit() for i in range(100): key = random.randint(1, 50 + 1) telefon = "+" + str(random.randint(100000000, 999999999)) email = names.get_full_name().replace( " ", ".").lower() + "@" + random.choice( ("gmail.com", "aol.com", "chello.at", "tmobile.net")) c.execute(f"INSERT INTO kontaktdaten VALUES (?, ?)", (key, random.choice((telefon, email)))) conn.commit()
def save(self, *args, **kwargs): super().save(*args, **kwargs) for seat in range(self.hall.capacity): if not seat: continue if random.getrandbits(1) == 1: ticket = Ticket(seance=self, place=seat, user_name=names.get_full_name(), user_phone=Seance.generate_random_number(), user_email=Seance.generate_random_email()) print(ticket.user_phone) print(ticket.user_name) print(ticket.user_email) ticket.save()
def getStudents(): params = request.get_json(force=True) school = params["school"] students = [] for i in range(1, 25): student = { "name": names.get_full_name(), "score": str(random.randint(50, 650)) } students.append(student) students.sort(reverse=True, key=(lambda x: x["score"])) i = 1 for student in students: student["rank"] = i i += 1 return jsonify(students)
def get_phone_number(driver): try: shop_phone_number_1 = None shop_phone_number_2 = None view_phone_number_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//div[text()='View Phone Number']", ))) ActionChains(driver).move_to_element(view_phone_number_button).click( view_phone_number_button).perform() # view_phone_number_button.send_keys("\n") form_name = WebDriverWait(driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//span[text()='Fill this form with your correct details to view phone numbers']/following-sibling::input[@placeholder='Name']", ))) form_name.send_keys(names.get_full_name()) form_email_id = WebDriverWait(driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//span[text()='Fill this form with your correct details to view phone numbers']/following-sibling::input[@placeholder='Email Address']", ))) form_email_id.send_keys( f"raj_singh_{random.randint(1000,9999)}@gmail.com") form_phone_no = WebDriverWait(driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//span[text()='Fill this form with your correct details to view phone numbers']/following-sibling::input[@placeholder='Phone']", ))) form_phone_no.send_keys(random.randint(8000000000, 9999999999)) driver.find_element_by_xpath( "//span[text()='Fill this form with your correct details to view phone numbers']/following-sibling::input[@value='Submit']" ).send_keys("\n") shop_phone_number_1 = driver.find_element_by_xpath( "//div[@id='phoneNumbers']/a").text try: shop_phone_number_2 = driver.find_element_by_xpath( "//div[@id='phoneNumbers']/a/following-sibling::a").text except: return shop_phone_number_1, shop_phone_number_2, True # for value in shop_phone_number_list: # shop_phone_number.append(value.text) # print(shop_phone_number) return shop_phone_number_1, shop_phone_number_2, True except: return shop_phone_number_1, shop_phone_number_2, False
def register_http(user_refrence_code=""): #id_ = secrets.token_hex(16) id_ = str('%030x' % random.randrange(16**30))[-10:] post_data_ = { "sign": "9f078cb0ebc3c5bf5f9b775727a7989e", "key": "167", "method_name": "user_register", "name": "", "email": "", "password": "******", "device_id": "", "phone": "9732202402", "user_refrence_code": "" } post_data_["name"] = names.get_full_name() post_data_["email"] = ''.join( random.choices(string.ascii_lowercase + string.digits, k=10)) + "@ymail4.com" post_data_["device_id"] = "3a49b1b" + id_ post_data_["user_refrence_code"] = user_refrence_code n_ = "9" for b in range(9): n_ = n_ + random.SystemRandom.choices(random, "1234567890")[0] post_data_["phone"] = n_ post_data_ = str(post_data_).replace("\'", "\"") #print(post_data_) post_data_ = (base64.b64encode(str(post_data_).encode()).decode()[:-1]) # #print(post_data_) if br: r_ = requests.post("https://dashboard.vimoearn.com/api_new.php", data={"data": post_data_}, headers=headers) #r_ = r_.text else: curl = pycurl.Curl() curl.setopt(pycurl.URL, 'https://dashboard.vimoearn.com/api_new.php') curl.setopt(pycurl.POST, 1) body_as_dict = {"data": post_data_} body_as_json_string = json.dumps(body_as_dict) # dict to json body_as_file_object = StringIO(body_as_json_string) curl.setopt(pycurl.READDATA, body_as_file_object) curl.setopt(pycurl.POSTFIELDSIZE, len(body_as_json_string)) curl.perform() curl.close() return (r_)
def create_super_hero_data(N=100): fFantasyName = ['Wonder ', 'Super ', 'X ', 'King','Queen ', 'Tornado ', 'Cyclone ', 'Atomic ', 'Demon ', 'Draconis ', 'Lord', 'Lady ', 'One Punch ', 'Beast-', 'Eternal ', 'Ultimate ', 'Justice ', 'Laser ', 'Demon ', 'Superior ', 'Iron ', 'Crystal ', 'Fat ', 'Blast ', '', 'The Amazing ', 'Indominus '] sFantasyname = ['Boy','Girl', 'Man', 'Woman', 'Black Hole', 'Master', 'Sensei', 'Genesect', 'Samuri', 'Ninja', 'Saiyan', 'Knight', 'Guardian', 'Protector', 'Terror', 'Emperor', 'Diamond', 'Angel', 'Hunter', 'Rocket', 'Dynamite', 'Cyborg', 'Sorceror', '', 'Swordsman', 'God'] superpowers_list = ['Flight', 'X-Ray Vision', 'Laser Eyes', 'Super Strength', 'Super Speed', 'Regeneration', 'Telekinesis', 'Hypnosis', 'Martial Arts Mastery', 'Incredible Combat Skill', 'Magical Abilities', 'Incredible Genius', 'insane Swordskills'] weaknesses_list = ['Kryptonite', 'Acidic Substances', 'Arrogance', 'Recklessness', 'Obesity', 'Anorexia', 'Clumsiness', 'you are a Crybaby', 'Depression', 'that you have a Low Self-Esteem', 'you are Easily Manipulated', 'Lactose Intolerance', 'Diabetes'] nomeFantasia = pd.Series([*product(fFantasyName,sFantasyname)]).apply(lambda x: " ".join(x)).sample(N) realNames = [names.get_full_name() for x in range(N)] weaknesses = [", ".join(random.choices(weaknesses_list, k=random.randint(0,10))) for x in range(N)] superpower = [", ".join(random.choices(superpowers_list, k=random.randint(0,3))) for x in range(N)] batID = [str(uuid.uuid4()) for x in range(N)] result = { "BatID" : batID, "NomeFantasia" : nomeFantasia, "NomeReal" : realNames, "Poder" : superpower } return pd.DataFrame(result)
def generate_users(): with open("data/users.csv", "w", encoding="utf-8") as file: # string = "uid;nombre;apellido;email;telefono;pais\n" string = "" for uid in range(20): if uid == 0: nombre, apellido = "Administrador", "Zorzal" email = "*****@*****.**" country = "Chile" else: nombre, apellido = names.get_full_name().split(" ") email = (nombre[0] + apellido).lower() + "@uc.cl" country = random.choice(list(pycountry.countries)).name if len(country) > 30: country = "Chile" string += "{};{};{};{};{};{}\n".format(uid, nombre, apellido, email, number_gen(), country) file.write(string)
def create_villain_data(N=100): result = {} superVillains = ["The Lazy Lion","The Hungry Scorpion","The Gigantic Waspman","The Voiceless Mage","Absent Monarch","Awful Sage","Upset Creature","Agent Blue Masquerade","The Reaper","Silverclaw","The Unwritten Puma","The Real Falcon","The Gigantic Nighthawk","The Thin Slayer","Curious Mercenary","Agent Puzzling Master","Captain Third Marksman","Captain Blue Fox","Tecton","Miss Guidance","The Pink Demon","The Handy Mongoose","The Awful Magician","The Hungry Swordsman","Master Mute Freak","Proud Wolfman","Cowardly Mongoose","Master Misty Mole","Eva Destruction","Catastrophe","The Ice Scimitar","The Dramatic Zombie","The Talented Gorilla","The Repulsive Gloom","Absent Raven","Ice Scout","Shaggy Siren","Professor Fiery Slayer","Brain Freeze","Meltdown","The Aggressive Burglar","The Limping Wonder","The Adorable Devil","The Unusual Starling","Master Earthen Marksman","Captain Smooth Cricket","Professor Special Crane","Defiant Wonderman","Disembowler","Bronze Butcher","The Thin Beetle","The Electric Antman","The Deranged Mastermind","The Light Mantis","Lord Ugly Whiz","Unnatural Android","Professor Electron Wonder","Fiery Knuckles","Tasmanian Tiger","Miss Judgement","The Blue Hijacker","The Rare Assassin","The Mute Cricket","The Dazzling Beetle","Master Ghost Sage","Nimble Enchanter","Commander Rapid Bandit","Dynamic Starling","Faye Tality","Catastrophe","The Last Conjurer","The Wretched Gangster","The Ruthless Merlin","The Hypnotic Angel","Gullible Jackal","Water Genius","Secret Nightowl","Agent Frightening Mugger","The Black Falcon","Disembowler","The Huge Assassin","The Messy Hawk","The Wise Doctor","The Greasy Shadow","Master Creepy Clown","Frightening Duke","Agent Flashy Scorpion","Puzzling Beetle","Arachnis","he Spooky Prophet","The Colossal Horror","The Wild Wolverine","The Second Eagle","Gifted Dragonfly","Talented Mugger","Mister Second Scepter","Yellow Ant","Miss Judgement","Warped Warrior","The Rabid Whiz","The Light Agent","The Proud Master","The Lonely Arsonist","Master Copper Shadow","Agent Molten Mercenary","Doctor Electric Scout","Nimble Haunt","Black Cat","Miss Chievous"] weaknesses_list = ['Kryptonite', 'Acidic Substances', 'Arrogance', 'Recklessness', 'Obesity', 'Anorexia', 'Clumsiness', 'you are a Crybaby', 'Depression', 'that you have a Low Self-Esteem', 'you are Easily Manipulated', 'Lactose Intolerance', 'Diabetes'] nomeFantasia = pd.Series(superVillains).sample(N) realNames = [names.get_full_name() for x in range(N)] weaknesses = [", ".join(random.choices(weaknesses_list, k=random.randint(0,10))) for x in range(N)] batID = [str(uuid.uuid4()) for x in range(N)] idades = [random.randint(15,200) for x in range(N)] result = { "BatID" : batID, "NomeFantasia" : nomeFantasia, "NomeReal" : realNames, "Idade" : idades, "Fraqueza" : weaknesses } return pd.DataFrame(result)