def test_personal_shopper_assignment(self): #Create some personal shoppers personal_shopper1 = PersonalShopper.objects.create( first_name=names.get_first_name(gender="female"), last_name=names.get_last_name(), ) personal_shopper2 = PersonalShopper.objects.create( first_name=names.get_first_name(gender="female"), last_name=names.get_last_name(), ) personal_shopper1.save() personal_shopper2.save() personal_shopper1.regions.add(self.region) personal_shopper2.regions.add(self.region) #Create some users without recent orders and assign them to personal shopper 1 for _ in xrange(5): member = Member.objects.create( first_name=names.get_first_name(gender='male'), last_name=names.get_last_name(), phone_number=random.randint(1, 9999999999), region=random_region(), personal_shopper=personal_shopper1, ) member.save() #Check if a new member would be assigned to personal shopper 2 self.assertEqual(assign_personal_shopper(self.region), personal_shopper2)
def test_competitor_creation(sh): prefix = Preferences.TestingPrefix sh = SetupHelper.SetupHelper() sh.setManualDbCursor(DatabaseConnection.DatabaseConnection().getDatabaseCursor()) if random() < 0.5: print sh.createNewCompetitor(names.get_last_name(), names.get_first_name(gender='male'), "U18M", prefix) else: print sh.createNewCompetitor(names.get_last_name(), names.get_first_name(gender='female'), "U18F", prefix)
def test_correct_files(self): with patch_file(test_files): self.assertEqual(names.get_first_name(gender='male'), "Male") self.assertEqual(names.get_first_name(gender='female'), "Female") self.assertEqual(names.get_last_name(), "Last") # Test with cached responses self.assertEqual(names.get_first_name(gender='male', cached=True), "Male") self.assertEqual(names.get_first_name(gender='female', cached=True), "Female") self.assertEqual(names.get_last_name(True), "Last")
def __init__(self): # Gender self.gender = self.gender() self.genderTitle = self.genderTitle() self.genderPronoun = self.genderPronoun() self.genderPossessive = self.genderPossessive() # Basics self.firstName = names.get_first_name(self.gender) self.lastName = names.get_last_name() self.personality = self.personality(self.gender) # Appearance self.eyecolor = data.pick('appearance.eyes.color') self.skincolor = data.pick('appearance.skin.color') self.hairtype = data.pick('appearance.hair.type') self.haircolor = data.pick('appearance.hair.color') self.hairstyle = data.pick('appearance.hair.style.'+self.gender) self.height = data.pick('appearance.height') self.build = data.pick('appearance.build.'+self.gender) # Other self.minimumAge = 18 self.previousService = self.previousService() self.birthPlace = data.pick('places.birthplaces')
def crea_sede(presidente=None, estensione=LOCALE, genitore=None, locazione=None): ESTENSIONE_DICT = dict(ESTENSIONE) locazione = locazione or crea_locazione() s = Sede( nome="Com. " + ESTENSIONE_DICT[estensione] + " " + names.get_last_name(), tipo=Sede.COMITATO, estensione=estensione, genitore=genitore, telefono='+3902020202', email='*****@*****.**', codice_fiscale='01234567891', partita_iva='01234567891', locazione=locazione ) s.save() if presidente is not None: d = Delega( inizio="1980-12-10", persona=presidente, tipo=PRESIDENTE, oggetto=s ) d.save() return s
def inserir_randomico(self, repeat=10): ''' Inserir registros com valores randomicos names ''' lista = [] for _ in range(repeat): date = datetime.datetime.now().isoformat(" ") fname = names.get_first_name() lname = names.get_last_name() name = fname + ' ' + lname email = fname[0].lower() + '.' + lname.lower() + '@email.com' c = gen_city() city = c[0] uf = c[1] lista.append((name, gen_age(), gen_cpf(), email, gen_phone(), city, uf, date)) try: self.db.cursor.executemany(""" INSERT INTO clientes (nome, idade, cpf, email, fone, cidade, uf, criado_em) VALUES (?,?,?,?,?,?,?,?) """, lista) self.db.commit_db() print("Inserindo %s registros na tabela..." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: print("Aviso: O email deve ser único.") return False
def gen_nurse(self): b, nurse = User.create_user(username=self.random_alphanum(5, 20), password="******", usertype=UserType.Nurse, email=self.random_email(), first_name=names.get_first_name(), last_name=names.get_last_name(), print_stdout=False) nurse = nurse.get_typed_user() nurse.hospital = self.random_hospital().first() nurse.is_pending = False nurse.save()
def gen_admin(self): b, admin = User.create_user(username=self.random_alphanum(5, 20), password="******", usertype=UserType.Administrator, email=self.random_email(), first_name=names.get_first_name(), last_name=names.get_last_name(), print_stdout=False) admin = admin.get_typed_user() admin.hospital = self.random_hospital().first() admin.is_pending = False admin.save()
def mk_author_db(db_path="author.db", pops=500): """ Makes and Author DB and populates it :param db_path: the path where the DB is created :pops: The amount of entries that will be generated """ conn, cur = get_conn_cur(db_path) cur.execute("""CREATE TABLE author ( aid INTEGER , firstname TEXT, lastname TEXT, city TEXT, bid INTEGER)""") #Get This working.... author_list = [] author_list.extend ( [(0, 'Mathias', 'Jensen', 'Hadsten', 3), (1, 'Mathias', 'Jensen', 'Hadsten', 4), (2, 'Alexander', 'Danger', 'Skanderborg', 0), (3, 'Alexander', 'Danger', 'Skanderborg', 4), (6, 'Alexander', 'Danger', 'Hadsten', 4), (4, 'Arash', 'Kjær', 'Kobenhavn', 1), (5, 'Michael', 'Med K', None, 2)]) for x in range(ENTRIES_AUTHOR): author_list.append((x+6, names.get_first_name(), names.get_last_name(), random.choice(CITIES), x+6)) cur.executemany("INSERT INTO author VALUES(?, ?, ?, ?, ?)", author_list) conn.commit() conn.close()
def create_some_fixtures(sender, instance, created, **kwargs): import names import random if not created: return for x in range(5): first = names.get_first_name() last = names.get_last_name() full_name = u'{} {}'.format(first, last) email = u'{}@example.com'.format(first.lower().strip()) Contact.objects.create(user=instance, full_name=full_name, email=email) adj = random.choice(['crazy', 'black', 'fancy', 'sneaky', 'giant', 'spicy']) thing = random.choice(['shoe', 'cat', 'lamp', 'car', 'parrot', 'burrito']) title = u'{} wants a {} {}'.format(first, adj, thing) description = 'This is not a very good description is it?' Deal.objects.create(user=instance, title=title, description=description, value=random.random() * 100)
def populate_candidates(): """ Sends requests to connect to populate our sandbox Connector with 5 random candidates. """ for i in range(5): last_name = names.get_last_name() candidate = { 'first_name': names.get_first_name(), 'last_name': last_name, 'email': '{}{}@example.com'.format(last_name, choice(range(100))) } candidate_data = { # A random job_id will be fine as we are in a sandbox environment 'candidate': candidate, 'applications': [{'job_id': '101'}] } # We can choose to either include a callback header with our # request, or to poll until the application is complete. Here # we use the callback functionality. headers = { 'content-type': 'application/rolepoint.v2+json', 'x-rolepoint-callback-url': url_for( 'application_processed_callback', app_id=len(CREATED_CANDIDATES), _external=True ) } requests.post( CONNECT_URL + '/v1/{}/candidate'.format(CONFIG['connector_id']), json=candidate_data, auth=AUTH, headers=headers ) candidate['status'] = 'In Progress' CREATED_CANDIDATES.append(candidate)
def __init__(self): id_length = random.randint(config.min_id_length, config.max_id_length) self.id = utils.random_string(id_length) sex = random.choice(['male', 'female']) if sex == 'male': self.sex = 'M' else: self.sex = 'F' self.first_name = names.get_first_name(sex) self.last_name = names.get_last_name() self.middle_name = '' if config.gen_mid_name: if random.random() < config.gen_mid_name_chance: if random.randint(0, 1): self.middle_name = names.get_first_name(sex) else: self.middle_name = names.get_first_name(sex)[0] start = datetime.datetime(1900, 1, 1) end = datetime.datetime.now() self.birth_date = utils.random_date_between(start, end) self.aliases = [] if config.gen_alias: for i in xrange(config.gen_alias_max): if random.random() < config.gen_alias_chance: self.aliases.append(self.generate_alias()) self.studies = self.generate_studies(self.birth_date)
def insert_random_seller(self, repeat=qsellers): ''' Inserir registros com valores randomicos ''' seller_list = [] for _ in range(repeat): d = gen_timestamp(2014, 2015) + '+00' fname = names.get_first_name() lname = names.get_last_name() email = fname[0].lower() + '.' + lname.lower() + '@example.com' birthday = gen_timestamp() + '+00' active = rstr.rstr('01', 1) internal = rstr.rstr('01', 1) commissioned = rstr.rstr('01', 1) commission = 0.01 seller_list.append( (gen_cpf(), fname, lname, email, gen_phone(), birthday, active, internal, commissioned, commission, d, d)) try: self.db.cursor.executemany(""" INSERT INTO vendas_seller (cpf, firstname, lastname, email, phone, birthday, active, internal, commissioned, commission, created, modified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) """, seller_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_seller." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: print("Aviso: O email deve ser único.") return False
def test_empty_file(self): empty_files = { 'first:male': full_path('test/empty.txt'), 'first:female': full_path('test/empty.txt'), 'last': full_path('test/empty.txt'), } with patch_file(empty_files): self.assertEqual(names.get_first_name(gender='male'), "") self.assertEqual(names.get_first_name(gender='female'), "") self.assertEqual(names.get_last_name(), "") # Test with cached responses self.assertEqual(names.get_first_name(gender='male', cached=True), "") self.assertEqual(names.get_first_name(gender='female', cached=True), "") self.assertEqual(names.get_last_name(True), "")
def gen_doctor(self): b, doc = User.create_user(username=self.random_alphanum(5, 20), password="******", usertype=UserType.Doctor, email=self.random_email(), first_name=names.get_first_name(), last_name=names.get_last_name(), print_stdout=False) doc = doc.get_typed_user() doc.hospitals = self.random_hospital(random.randint(1, 10)) doc.is_pending = False doc.save()
def crea_persona(): p = Persona( nome=names.get_first_name(), cognome=names.get_last_name(), codice_fiscale=codice_fiscale(), data_nascita="1994-2-5" ) p.save() return p
def fill_persons(cur): # 100 random persons... for i in range(0,100): # Creates Person with random first and last name. Also other random functions are inserted. person = ( names.get_first_name(), names.get_last_name(),' ',random.randint(60000 , 999999), "functie", 0) # Inserts record in the table. cur.execute('''INSERT INTO Persons VALUES(NULL,?,?,?,?,?,?);''', person)
def randomPlayer(): p = Player(None, names.get_first_name(gender='male'), names.get_last_name()) p.rate1B = random.gauss(0.154, 0.051) p.rate2B = random.gauss(0.044, 0.015) p.rate3B = random.gauss(0.004, 0.001) p.rateHR = random.gauss(0.025, 0.008) p.rateBB = random.gauss(0.079, 0.026) p.rateHBP = random.gauss(0.008, 0.003) return p
def crea_persona(): p = Persona.objects.create( nome=names.get_first_name(), cognome=names.get_last_name(), codice_fiscale=codice_fiscale(), data_nascita="{}-{}-{}".format(random.randint(1960, 1990), random.randint(1, 12), random.randint(1, 28)) ) p.refresh_from_db() return p
def create_personal_shoppers(amount): for _ in xrange(amount): personal_shopper = PersonalShopper.objects.create( first_name=names.get_first_name(gender='female'), last_name=names.get_last_name(), ) personal_shopper.is_active = bool(random.getrandbits(1)) personal_shopper.save() personal_shopper.regions.add(random_region())
def _create_customers(self): print "Adding {0} customers ".format(self.num_customers), for _ in xrange(self.num_customers): name = gen_names.get_first_name() surname = gen_names.get_last_name() user = Customer(first_name=name, last_name=surname, email=name+"@"+surname+".com") user.save() sys.stdout.write('.') print "OK"
def __init__(self): threading.Thread.__init__(self) self.daemon = True # set a default name self.name = names.get_last_name() self.quit = False self.getStateStatistics = Statistics() self.setPaddleSpeedStatistics = Statistics()
def generate_pass(minimum_length=9): """Return a really simple password. This will NOT actally protect against any attackers. It is just so we can have randomly-generated passwords in our config files and such. """ password = '' while len(password) < minimum_length: password = '******'.format(names.get_last_name().lower(), random.randint(0, 9999)) return password
def generate_user(organization, session, **kwargs): first_name = names.get_first_name() user = create_user( organization_id=organization.id, first_name=names.get_first_name(), last_name=names.get_last_name(), email='{}+{}@company.com'.format(first_name, uuid.uuid4()), session=session, **kwargs ) return user
def random_person(idx): first = names.get_first_name() last = names.get_last_name() middle = random.choice([names.get_first_name, names.get_last_name, lambda: None])() blood_type = random.choice(['A', 'A', 'B', 'B', 'O', 'O', 'O', 'O', 'AB']) return {'id': idx, 'first_name': first, 'middle_name': middle, 'last_name': last, 'blood_type': blood_type }
def make_students(self, options): self.students = [] for _ in xrange(options.get('count')[0]): stud = mommy.prepare( Student, university=random.choice(self.universities), first_name=names.get_first_name(), last_name=names.get_last_name(), age=random.randint(17, 25) ) self.students.append(stud) Student.objects.bulk_create(self.students)
def generate_post(secret_key=settings.CLICKBANK_SECRET_KEY, data=None): """ Generate a post with a given secret key for use with testing """ import names first_name = names.get_first_name() last_name = names.get_last_name() post_data = { u'caccountamount': amount_generator(), u'cnoticeversion': u'4.0', u'cbf': u'', u'ctranspaymentmethod': random.choice(Notification.PAYMENT_METHOD_CHOICES)[0], u'corderamount': amount_generator(), u'ctaxamount': amount_generator(), u'ccustzip': zip_generator(), u'ctransreceipt': receipt_generator(), u'ccustfullname': ' '.join([first_name, last_name]), u'ctid': string_generator(), u'corderlanguage': language_generator(), u'ccustcounty': string_generator(), u'ccustcc': string_generator(2), u'ccuststate': string_generator(2), u'cbfpath': u'', u'cfuturepayments': string_generator(length=1, chars=string.digits), u'crebillamnt': amount_generator(), u'ccustaddr2': string_generator(20), u'cshippingamount': amount_generator(), u'ctransaction': random.choice(Notification.TRANSACTION_TYPE_CHOICES)[0], u'ctransvendor': string_generator(), u'ccustshippingzip': zip_generator(), u'ctransaffiliate': string_generator(), u'ccustemail': string_generator(), u'cupsellreceipt': receipt_generator(), u'cprodtitle': string_generator(), u'ctransrole': random.choice(Notification.ROLE_CHOICES)[0], u'crebillstatus': random.choice(Notification.REBILL_STATUS_CHOICES)[0], u'cbfid': u'', u'cvendthru': u'', u'cprodtype': random.choice(Notification.PRODUCT_TYPE_CHOICES)[0], u'ccustfirstname': first_name, u'ctranstime': u'1383333571', u'ccurrency': string_generator(chars=string.ascii_uppercase, length=3)[0], u'cprocessedpayments': str(random.randrange(1, 100)), u'ccustshippingcountry': string_generator(), u'ccustlastname': last_name, u'cnextpaymentdate': future_date_generator(), u'cproditem': string_generator(chars=string.digits), u'ccustaddr1': string_generator(length=20), u'ccustcity': string_generator(length=10), u'crebillfrequency': u'', u'ccustshippingstate': string_generator(length=2, chars=string.ascii_uppercase) } post_data[u'cverify'] = make_secret(post_data) return post_data
def create_members(amount): for _ in xrange(amount): member = Member.objects.create( first_name=names.get_first_name(gender='male'), last_name=names.get_last_name(), phone_number=random.randint(1, 9999999999), region=random_region(), ) member.save() return Member.objects.all()
def fill_persons(): # 100 random persons... for i in range(0, 100): # Creates Person with random first and last name. Also other random functions are inserted. person = (get_first_name(), get_last_name(), " ", random.randint(60000, 999999), "functie", 0) # Inserts record in the table. for i in range(100): persoon = Person( first_name=get_first_name(), last_name=get_last_name(), email="", phone_number=681365020, function="function", date_of_birth="12/12/12", ) session.add(persoon) session.commit()
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 edit(): token = rand_token() if token is None: return profile = dict() if random.randint(0, 100) % 3 == 0: profile['first_name'] = names.get_first_name() if random.randint(0, 100) % 3 == 0: profile['last_name'] = names.get_last_name() if random.randint(0, 100) % 3 == 0: profile['birth_date'] = random.randint(0, 1541376257) if random.randint(0, 100) % 3 == 0: profile['status'] = ' '.join(gibberish.generate_words(random.randint(3, 10))) print('edit user profile: {0}'.format(profile)) r = requests.patch('http://hl-course-server-service/profile/{0}'.format(token), json=profile) if r.status_code != 200: print("can't edit user profile: {0}".format(r.text))
def __init__(self, first_purchase_date): """ Initialize a customer object Parameters: first_purchase_date (datetime): the date the customer first made a purchase customer_id (int): a unique id number for the customer """ self.first_purchase_date = first_purchase_date self.last_purchase_date = self.first_purchase_date self.first_name = names.get_first_name() self.last_name = names.get_last_name() self.email = self.first_name + "." + self.last_name + "@gmail.com" self.phone_num = "" for i in range(0, 10): self.phone_num += str(rand.randint(0, 9)) self.customer_id = "NULL" self.shoe_club_id = "NULL" self.shoe_club_signup_date = datetime.strptime("9999-01-01", "%Y-%m-%d") self.shoe_club_status = "Inactive"
def loadAndWrite(local_loop_Count: int, fileName=r'output\HashFileLoad.csv', mode='a+', lockMode=True): global main_current with open(fileName, mode, newline='') as file: writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',') for i in range(local_loop_Count): genderId = random.randint(1, 2) genderInd = 'male' if genderId == 2: genderInd = 'female' fields = [] fields.append(str(uuid.uuid4())) fields.append(names.get_first_name(gender=genderInd)) fields.append(names.get_first_name()) fields.append(names.get_last_name()) fields.append(fake.date_of_birth(minimum_age=18, maximum_age=60)) fields.append(random.randint(1001, 9999)) if genderId == 1: fields.append('M') else: fields.append('F') fields.append(random.randint(1111111111, 9999999999)) if lockMode: threadLock.acquire() writer.writerow(fields) main_current += 1 threadLock.release() else: writer.writerow(fields) main_current += 1
def help(amnt): for i in range(int(amnt)): url = "https://secure1.chla.org/site/SPageNavigator/valentine2018.html?s_src=vday18hps" 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', 'Host': 'secure1.chla.org', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } s = requests.session() r1 = s.get(url, headers=headers) url2 = "https://secure1.chla.org/site/SSurvey?2655_1940_2_1861=Pterodactyl&cons_first_name={}&cons_last_name={}&cons_email={}@gmail.com&2655_1940_5_1864=&ACTION_SUBMIT_SURVEY_RESPONSE=Send+my+valentine&cons_info_component=t&SURVEY_ID=1940".format( names.get_first_name(), names.get_last_name(), str(random.randint(111111111, 999999999))) h2 = headers r2 = s.get(url2, headers=h2) if "Donation2" in r2.url: print("Gave $1 To Charity And A Card To A Kid")
def test_delete_student(self): """Test case for delete_student """ body = Student() body.first_name = names.get_first_name() body.last_name = names.get_last_name() body.grades = {'math': 8, 'history': 9} response = self.client.open( '/service-api/student', method='POST', data=json.dumps(body), content_type='application/json') student_id = (response.json) response = self.client.open( '/service-api/student/{student_id}'.format(student_id=student_id), method='DELETE') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) response = self.client.open( '/service-api/student/{student_id}'.format(student_id=-1), method='DELETE') self.assert404(response, 'Response body is : ' + response.data.decode('utf-8'))
def crea_sede(presidente=None, estensione=LOCALE, genitore=None, locazione=None): ESTENSIONE_DICT = dict(ESTENSIONE) locazione = locazione or crea_locazione() s = Sede(nome="Com. " + ESTENSIONE_DICT[estensione] + " " + names.get_last_name(), tipo=Sede.COMITATO, estensione=estensione, genitore=genitore, telefono='+3902020202', email='*****@*****.**', codice_fiscale='01234567891', partita_iva='01234567891', locazione=locazione) s.save() if presidente is not None: d = Delega(inizio="1980-12-10", persona=presidente, tipo=PRESIDENTE, oggetto=s) d.save() return s
def get_rnd_customer(gender): gender_list = ['male', 'female', 'none'] city_list = ['Wolfsburg', 'Hannover', 'Hamburg', 'Stuttgart', 'Dresden', 'Berlin'] street_list = ['School Street', 'Village Street', 'Garden Street', 'Station Street', 'Main Street', 'Market Street'] postalcode_list = [10115, 10117, 10120, 10215, 10251, 10200, 10532, 20211, 20116, 50817, 50125, 50126, 50241] title_list=['Doctor', 'President', 'Professor','Major','Director'] gendername='' customer = Customer() if gender=="": gender=random.choice(['M','F']) if gender.upper()=='M': gendername='male' customer.salutation='Mr.' elif gender.upper()=='F': gendername='female' customer.salutation='Ms.' elif gender.upper()=='O': gendername='None' customer.salutation='Mx.' customer.lastname = names.get_last_name() customer.firstName=names.get_first_name(gender=gendername) customer.fullName = customer.firstName +' ' + customer.lastname customer.personalEmail=customer.firstName.lower()+'.'+customer.lastname.lower()+'@personaemail.com' customer.serviceEmail=customer.firstName.lower()+'.'+customer.lastname.lower()+'@officeemail.com' customer.personalTelephone = '+4900000000000' customer.serviceTelephone='+491111111111111' yyyy=random.randrange(1970,1999) mm=random.randrange(1,12) dd=random.randrange(1,30) customer.dateOfBirth=yyyy.__str__()+'-'+mm.__str__()+'-'+dd.__str__() customer.place=random.choice(city_list) customer.street=random.choice(street_list) customer.postalCode=random.choice(postalcode_list) customer.title=random.choice(title_list) return customer.toJson()
def create_some_fixtures(sender, instance, created, **kwargs): import names import random if not created: return for x in range(5): first = names.get_first_name() last = names.get_last_name() full_name = u'{} {}'.format(first, last) email = u'{}@example.com'.format(first.lower().strip()) Contact.objects.create(user=instance, full_name=full_name, email=email) adj = random.choice( ['crazy', 'black', 'fancy', 'sneaky', 'giant', 'spicy']) thing = random.choice( ['shoe', 'cat', 'lamp', 'car', 'parrot', 'burrito']) title = u'{} wants a {} {}'.format(first, adj, thing) description = 'This is not a very good description is it?' Deal.objects.create(user=instance, title=title, description=description, value=random.random() * 100)
def inserir_randomico(self, repeat = 10): # Inserir registros com vaçpres randomicos names lista = [] for _i in range(repeat): date = datetime.datetime.now().isoformat(" ") fname = names.get_first_name() lname = names.get_last_name() name = fname + ' ' + lname email = fname[0].lower() + '.' + lname.lower() + '@email.com' c = gen_city() city = c[0] uf = c[1] lista.append((name, gen_age(), gen_cpf(), email, gen_phone(), city, uf, date)) try: self.db.cursor.execute(""" INSERT INTO clientes (nome, idade, cpf, email, fone, cidade, fone, cidade uf, criado_em) VALUES (?,?,?,?,?,?,?,?) """, lista) self.db.commit() print ("Inserindo %s registros na tebla..." % repeat) print("registros criado com sucesso.") except sqlite3.IntegrityError: print("Aviso: email deve ser único.") return False
def test_get_student_by_last_name(self): """Test case for get_student_by_last_name Find student by last name """ body = Student() body.first_name = names.get_first_name() body.last_name = names.get_last_name() body.grades = {'Chinese': 8, 'history': 9} response = self.client.open( '/service-api/student', method='POST', data=json.dumps(body), content_type='application/json') query_string = [('last_name', (response.json)['last_name'])] # 学生的last_name response = self.client.open( '/service-api/student/', method='GET', query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) self.assertTrue(response.is_json) self.assertIsInstance(response.json, dict)
def test_get_student_by_id(self): """Test case for get_student_by_id Find student by ID """ body = Student() body.first_name = names.get_first_name() body.last_name = names.get_last_name() body.grades = {'math': 8, 'history': 9} response = self.client.open('/service-api/student', method='POST', data=json.dumps(body), content_type='application/json') student_id = (response.json) query_string = [('math', 9)] response = self.client.open( '/service-api/student/{student_id}'.format(student_id=student_id), method='GET', query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) self.assertTrue(response.is_json) self.assertIsInstance(response.json, dict)
def __init__(self): # Load training images self.mixing = 0.5 self.mutation = 0.05 self.population = 20 self.gen = 0 #self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True) self.brains = [ NeuralNetwork([20**2, 6, 3], names.get_first_name(), names.get_last_name()) for i in range(self.population) ] plt.ion() plt.show() self.fig = plt.figure() self.bestAI = self.brains[0], 0 self.best = [] self.avg = [] self.ax1 = plt.gca() self.ax1.set_ylim(0, 100) self.line, = self.ax1.plot([], self.best, 'b-') self.line2, = self.ax1.plot([], self.avg, 'r-') time.sleep(0.5) self.trial_all()
def get_random_name(length): first_name = names.get_first_name().lower() last_name = names.get_last_name().lower() full_name = "_".join(names.get_full_name().split(" ")).lower() return random.choice([first_name, last_name, full_name]) + ''.join( str(random.randint(1, 10)) for i in range(length))
def main(): now = datetime.datetime.now().strftime('%m%d%H%M%S') email = '*****@*****.**' claimNo = 'claim' + now policyNo = 'policy' + now firstName = names.get_first_name() lastName = names.get_last_name() currentAddress = '62 O\'Connell Street Upper' currentCity = 'Dublin' currentCounty = '4' cars = { 'Toyota': ['Camry', 'Corolla', 'Prius'], 'Honda': ['Accord', 'Civic', 'CR-V'], 'Ford': ['F-150', 'Escape', 'Focus'] } make, models = random.choice(list(cars.items())) model = random.choice(models) driver = webdriver.Chrome() # Navigate to webpage driver.get("https://vice-frontend-integration.snapsheet.tech/") # Sign in driver.find_element_by_css_selector( '[data-test-id="login_form_email_input"]').send_keys(email) driver.find_element_by_css_selector( '[data-test-id="login_form_password_input').send_keys( "INSERTPASSWORDHERE") driver.find_element_by_css_selector( '#app > div > div._2YAjRhynbRDMGwIOqUCPA1 > div:nth-child(2) > div > div:nth-child(6) > button' ).click() time.sleep(2) # Create New Claim driver.find_element_by_css_selector( '#app > div > div > div.O2oH4V0LOoizIYDgzvgNj > div > div._266sD5YxjUkjzOakD2jBHv > button > span' ).click() driver.find_element_by_css_selector( '#app > div > div > div._1YlF0xeG8atxX5hpNMebqS > div > label:nth-child(3) > input' ).send_keys(policyNo) driver.find_element_by_css_selector( '#app > div > div > div._1YlF0xeG8atxX5hpNMebqS > div > label:nth-child(4) > input' ).send_keys(claimNo) driver.find_element_by_css_selector( '[data-test-id="new-short-claim-submit-button"]').click() time.sleep(1) # Select 'New Exposure' driver.find_element_by_css_selector( '[data-test-id="exposure-list-view-new-button"]').click() # Populate Exposure fields driver.find_element_by_xpath( '//*[@id="app"]/div/div/div[2]/div/div[2]/div/div[2]/div/div[1]/div[2]/div/div/div/div[1]/div/label/div' ).click() driver.find_element_by_xpath( '//label[@for="claimant.firstName"]/following-sibling::input[1]' ).send_keys(firstName) driver.find_element_by_xpath( '//label[@for="claimant.surname"]/following-sibling::input[1]' ).send_keys(lastName) driver.find_element_by_xpath( '//label[@for="claimant.address.address1"]/following-sibling::input[1]' ).send_keys(currentAddress) driver.find_element_by_xpath( '//label[@for="claimant.address.city"]/following-sibling::input[1]' ).send_keys(currentCity) driver.find_element_by_xpath( '//label[@for="claimant.address.region"]/following-sibling::input[1]' ).send_keys(currentCounty) driver.find_element_by_xpath( '//label[@for="claimant.preferredContact"]/following-sibling::div[1]/label[1]/div/span' ).click() driver.find_element_by_xpath( '//label[@for="claimant.email"]/following-sibling::input[1]' ).send_keys(email) driver.find_element_by_xpath( '//label[@for="claimant.phone"]/following-sibling::input[1]' ).send_keys('13195412283') driver.find_element_by_xpath( '//label[@for="vehicle.registrationNumber"]/following-sibling::input[1]' ).send_keys('182-D-12345') driver.find_element_by_xpath( '//label[@for="vehicle.vin"]/following-sibling::input[1]').send_keys( '19XFC2F54JE004299') driver.find_element_by_xpath( '//label[@for="vehicle.make"]/following-sibling::input[1]').send_keys( make) driver.find_element_by_xpath( '//label[@for="vehicle.model"]/following-sibling::input[1]').send_keys( model) driver.find_element_by_xpath( '//label[@for="vehicle.year"]/following-sibling::input[1]').send_keys( '2018') driver.find_element_by_xpath( '//label[@for="vehicle.address.address1"]/following-sibling::input[1]' ).send_keys(currentAddress) driver.find_element_by_xpath( '//label[@for="vehicle.address.city"]/following-sibling::input[1]' ).send_keys(currentCity) driver.find_element_by_xpath( '//label[@for="vehicle.address.region"]/following-sibling::input[1]' ).send_keys(currentCounty) # Click 'Save' to save new exposure driver.find_element_by_css_selector( '[data-test-id="exposure-new-view-save-button"]').click() time.sleep(2) print('\nYour Claim Number is %s.\n' % claimNo) driver.quit()
def test_user_login(self): driver = self.driver driver.get("https://www.vetofficesuite.com/user/login") email_field = driver.find_element_by_xpath("//form[@id='frm']/p[3]/input") email_field.clear() email_field.send_keys("Yevtest") password_field = driver.find_element_by_xpath("//form[@id='frm']/p[4]/input") password_field.clear() password_field.send_keys("Test1234") button_login = driver.find_element_by_xpath("//form[@id='frm']/div/div[2]/input") button_login.click() create_client = driver.find_element_by_xpath("//div[2]/ul/li[3]/a") create_client.click() for i in range(0,300): def makeEmail(): extensions = ['com','net','org','gov'] domains = ['gmail','yahoo','comcast','verizon','charter','hotmail','outlook','frontier'] winext = extensions[random.randint(0,len(extensions)-1)] windom = domains[random.randint(0,len(domains)-1)] acclen = random.randint(1,20) winacc = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(acclen)) finale = winacc + "@" + windom + "." + winext return finale randemail = str(makeEmail()) def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) randophone = str(random_with_N_digits(10)) randoname = names.get_first_name() randolname = names.get_last_name() client_name = driver.find_element_by_xpath("//fieldset/p/input") client_name.send_keys("" + randoname + "") print("Name created: " + randoname + "") client_last_name = driver.find_element_by_xpath("//fieldset[2]/p/input") client_last_name.send_keys("" + randolname + "") print("Last Name created: " + randolname + "") client_address = driver.find_element_by_xpath("//p[4]/input") client_address.send_keys("Mechnikova 18") client_city = driver.find_element_by_xpath("//p[5]/input") client_city.send_keys("Dnipro") client_email = driver.find_element_by_xpath("//fieldset[2]/p[7]/input") client_email.send_keys("" + randemail + "") print("Email created: " + randemail + "") client_zip = driver.find_element_by_xpath("//p[6]/input") client_zip.send_keys("49008") client_phone = driver.find_element_by_xpath("//p[7]/input") client_phone.send_keys("" + randophone + "") print("Phone created: " + randophone + "") select = Select(driver.find_element_by_name('USA_state_client')) select.select_by_visible_text("Alabama") saveButton = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//form/p[2]/input"))) saveButton.click() time.sleep(5) create_client = driver.find_element_by_xpath("//a[contains(text(),'Create new client')]") create_client.click() print("--- --- ---")
import sys import names import os from webapp.models import User users = [] for i in range(1, 100): first_name, last_name = names.get_first_name(), names.get_last_name() users.append({ "name": "{} {}".format(first_name, last_name), "email": "{}.{}@zuora.com".format(first_name, last_name).lower() }) for user in users: userEntry = User(name=user["name"], email=user["email"]) userEntry.save()
def get_rondom_name(self): import ipdb ipdb.set_trace() return 'r_' + names.get_last_name()
for season in range(numOfSeasons): for team in range(numOfTeams): for index in range(len(title)): # Create the coach list coach = [] # ID coach.append(id) # Team ID coach.append(team + 1) # Generate a random gender gender = randint(0, 1) # First name coach.append(names.get_first_name(gender='male')) if gender == 1 \ else coach.append(names.get_first_name(gender='female')) # Last name coach.append(names.get_last_name()) # Full Name coach.append(coach[2] + ' ' + coach[3]) # Title coach.append(title[index]) id += 1 coach_writer.writerow(coach)
def generate_multiple_accounts(n): for i in range(n): generate_account(names.get_first_name(), names.get_last_name())
import json import names import random data = {} data['Players'] = [] for i in range(50): data['Players'].append({ 'talent': random.uniform(0.5, 1), 'map_skill': random.uniform(0.5, 1), 'weapon_skill': random.uniform(0.5, 1), 'utility_usage': random.uniform(0.5, 1), 'game_sense': random.uniform(0.5, 1), 'communication': random.uniform(0.5, 1), 'mood': random.uniform(0.5, 1), 'motivation': random.uniform(0.5, 1), 'alive': True, 'nationality': 'Serbia', 'name': names.get_first_name(gender="male"), 'surname': names.get_last_name(), 'age': random.randint(18, 31), 'cost': random.randint(100000, 300000), 'team': None }) with open("Game/db/column_add/data.txt", 'w') as outfile: json.dump(data, outfile)
import time import names import random from people_finder import PeopleFinder from people_finder import Person import csv list_people = [] i = 0 more_sleep = 0 while i < 50: sleep = random.randint(10, 50) time.sleep(sleep) last = names.get_last_name() dob = str(random.randint(1950, 2000)) info = PeopleFinder.query('', last, '', dob, '', '') if info is not None: if info['addreses'] is not None: print(info) list_people.append(Person('', '', last, dob, '', '', info)) i += 1 with open('file.csv', mode='w') as out: csv_out = csv.writer(out, delimiter=',') csv_out.writerow([ 'first name', 'middle name', 'last name', 'dob', 'city', 'state', 'info' ]) for row in list_people: csv_out.writerow(row)
def create_students(): for i in range(31): student_id = 1000000 + i gender = choice(["male", "female"]) first_name = names.get_first_name(gender=gender) last_name = names.get_last_name() email_sutd = f"{first_name.lower()}_{last_name.lower()}@mail.sutd.edu.sg" email_personal = f"{first_name.lower()}@gmail.com" sc_status = choice([True, False]) weightage_order = [1, 2, 3, 4, 5, 6, 7, 8, 9] shuffle(weightage_order) data = { "username": str(student_id), "password": str(student_id), "student_id": str(student_id), "full_name": f"{first_name} {last_name}", "gender": gender, "enrollment_type": choice(("PhD", "MArch", "MSSD", "UG", "UG", "UG")), "year_of_enrollment": randint(2009, 2022), "sc_status": sc_status, "pr_status": False if sc_status else choice((True, False)), "nationality": "Singaporean" if sc_status else choice( ("Chinese", "Indian", "Indonesian", "Malaysian")), "phone_number": str(randint(80000000, 99999999)), "email_sutd": email_sutd, "email_personal": email_personal, "local_addr_post_code": str(randint(300000, 999999)), "local_addr_street": "Changi South Avenue 1", "local_addr_unit": f"#{str(randint(10, 99))}-{str(randint(100, 199))}", "preference_roommate": [str(randint(1000000, 1000030))], "preference_room": { "room_type": choice(("DOUBLE", "SINGLE", "SINGLE_ENSUITE")), "room_type_2nd": choice( ("DOUBLE", "SINGLE", "SINGLE_ENSUITE")), "block": choice(("59", "57", "55", "ANY")), "block_2nd": choice(("59", "57", "55", "ANY")), "level_range": choice(("UPPER", "MIDDLE", "LOWER", "ANY")), "window_facing": choice( ("CAMPUS", "AIRPORT", "BUILDING", "ANY")), "near_to_lift": choice((True, False)), "near_to_washroom": choice((True, False)), "level_has_pantry": choice((True, False)), "level_has_mr": choice((True, False)), "level_has_gsr": choice((True, False)), "level_has_rr": choice((True, False)), "weightage_order": weightage_order, }, "preference_lifestyle": { "sleep_time": choice((21, 22, 23, 0, 1, 2, 3)), "wakeup_time": choice((5, 6, 7, 8, 9, 10, 11)), "like_social": randint(0, 10), "like_quiet": randint(0, 10), "like_clean": randint(0, 10), "diet": choice(("Standard", "Vegetarian", "Vegan", "Raw", "No Sugar", "Halal")), "use_aircon": choice((True, False)), "smoking": choice((True, False)), }, "is_house_guardian": True if student_id <= 1000005 else False, "travel_time_hrs": round(uniform(0.0, 2.0), 2), } post_request(endpoint="/api/auth/register/student", data=data, token=None)
def get_last_name(): last_name = names.get_last_name() return last_name
# This script will create an "Employee Table" with randomized employee names and hire dates and export to a CSV file. # Change the rows variable to control the number of rows exported. # pip install --upgrade names, pandas, pandas_datareader, scipy, matplotlib, pyodbc, pycountry, azure ### This looping operation will install the modules not already configured. import importlib, os, sys, uuid packages = ['numpy', 'pandas'] for package in packages: try: module = importlib.__import__(package) globals()[package] = module except ImportError: cmd = 'pip install --user ' + package os.system(cmd) module = importlib.__import__(package) import names, random, datetime, numpy as np, pandas as pd, time, string, csv rows = 100 employeeid = np.array([str(uuid.uuid4()) for _ in range(rows)]) lastname = np.array([''.join(names.get_last_name()) for _ in range(rows)]) firstname = np.array([''.join(names.get_first_name()) for _ in range(rows)]) nowdate = datetime.date.today() hiredate = np.array([nowdate - datetime.timedelta(days=(random.randint(30,180))) for _ in range(rows)]) salary = np.array([str(random.randint(50,100)*1000) for _ in range(rows)]) inputzip = zip(employeeid,lastname,firstname,hiredate,salary) inputlist = list(zip(employeeid,lastname,firstname,hiredate,salary)) df = pd.DataFrame(inputlist) df.to_csv('20200507.tbl',index=False,header=["EmployeeID","LastName","FirstName","HireDate","Salary"])
'Calzad de la Virgen', "Retorno 1" ] return calles[randint(0, 4)] + ' ' + '#' + str(randint(1, 100)) def municipio(): muns = [ 'Coyoacán', 'Alvaro Obregón', 'Azcapotzalco', 'Miguel Hidalgo', 'Tlalpan', 'Benito Juárez' ] return muns[randint(0, 5)] for i in range(50): nombre = names.get_first_name() apellidos = names.get_last_name() + ' ' + names.get_last_name() f_nac = fecha() dia, mes, anio = [int(v) for v in f_nac.split("-")] edad = calcular_edad(date(dia, mes, anio)) direc = direccion() cp = str(randint(10000, 99999)) mun = municipio() estado = "CDMX" tel = '55' + str(randint(10000000, 99999999)) cad = f'INSERT INTO CLIENTES VALUES ({i+1},"{nombre}","{apellidos}",\'{f_nac}\',{edad},"{direc}","{cp}","{mun}","{estado}","{tel}")' conn = en.connect() conn.execute(cad) conn.close() en.dispose()
def make_season(i): s = Season.objects.create(player=Player.objects.all()[i], team_irl=random.choice([ 'paperopoli', 'topolinia', 'gotham city', 'metropolis' ]), price=random.randint(1, 40)) s.roles.add(Role.objects.get(role=random.choice(['P', 'D', 'C', 'A']))) for i in range(10): s.performances.add(Performance.objects.all()[random.randint(0, 19)]) s.save() for j in range(20): for i in range(random.randint(1, 5)): make_season(i) # create some teams for i in range(10): t = Team.objects.create( user=User.objects.get(username='******'.format(i)), name=names.get_last_name(), league=League.objects.all()[random.randint(0, 2)], history=random.choice([None, 'la storia della mia squadra'])) for i in range(5): r = Roster.objects.create(player=Player.objects.all()[i], team=t, price_paid=random.randint(1, 50)) r.save() t.save()
def gen_last_name(): return names.get_last_name()
def get_employee_last_name(self): return names.get_last_name()
def task(): s = requests.session() # here we post site key to 2captcha to get captcha ID (and we parse it here too) captcha_id = s.post("http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}".format(API_KEY, site_key, url)).text.split('|')[1] # then we parse gresponse from 2captcha response recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id)).text print("solving ref captcha...") while 'CAPCHA_NOT_READY' in recaptcha_answer: print('Captcha not ready...') sleep(5) recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id)).text recaptcha_answer = recaptcha_answer.split('|')[1] def random_string_generator_variable_size(min_size, max_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(randint(min_size, max_size))) def random_with_N_digits(n): range_start = 10 ** (n - 1) range_end = (10 ** n) - 1 return randint(range_start, range_end) phoneNumber = random_with_N_digits(10) chars = string.ascii_letters rando = random_string_generator_variable_size(6, 12, chars) randoAddy = random_string_generator_variable_size(3, 3, chars) headers = { "content-type": "application/json", "accept": "application/json", "accept-encoding": "gzip, deflate", "accept-language": "en-US,en;q=0.8", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" } email = rando + catchall payload = { "email": email, "product_id": "3906146598960", "challenge_response": recaptcha_answer, } validateEmail = 'https://eb-draw.herokuapp.com/customers/validateEmail' s.post(validateEmail, headers=headers, json=payload) newUserLink = 'https://eb-draw.herokuapp.com/customers/new' newPayload = { "first_name": names.get_first_name(gender='male'), "last_name": names.get_last_name(), "email": email } response = s.post(newUserLink, headers=headers, json=newPayload) json_raffle = json.loads(response.text) customerID = json_raffle["id"] entryPaylod = { "shipping_first_name": names.get_first_name(gender='male'), "shipping_last_name": names.get_last_name(), "customer_id": customerID, "variant_id": varient, "street_address": randoAddy + " " + address + " " + address2, "city": city, "zip": zip, "state": state, "phone": phoneNumber, "country": "United States", "delivery_method": "online" } entryLink = 'https://eb-draw.herokuapp.com/draws/entries/new' raffle_id = s.post(entryLink, headers=headers, json=entryPaylod) json_raffleid = json.loads(raffle_id.text) raffleid = json_raffleid["id"] tokenAPI = "https://api.stripe.com/v1/tokens?card[number]=" + cc + "&card[cvc]=" + cvv + "&card[exp_month]=" + exp_month + "&card[exp_year]=" + exp_year + "&guid=45c139ce-e8db-40b6-949d-a49b8d950216&muid=9fec740c-b7c8-46e1-9367-4a0c09cf6ce1&sid=087a8e05-bf23-4bb3-bf25-0bbb916ef0df&payment_user_agent=stripe.js%2Ff13a0323%3B+stripe-js-v3%2Ff13a0323&referrer=https%3A%2F%2Fshop.extrabutterny.com%2Fproducts%2Fadidas-yeezy-350-v2-citrin-fw3042%3Fvariant%3D29633029046320&key=pk_live_u42h9k3kHDcKpj3DjgyIXjc7" tokenHeaders = { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://js.stripe.com", "Referer": "https://js.stripe.com/v3/controller-c62905a44c003da4daa7d77169f71ef7.html", "Sec-Fetch-Mode": "cors", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" } tokenReq = requests.post(tokenAPI, headers=tokenHeaders) json_tokenReq = json.loads(tokenReq.text) token = json_tokenReq["id"] checkoutlink = 'https://eb-draw.herokuapp.com/draws/entries/checkout' checkoutPayload = { "checkout_token": token, "entry_id": raffleid } s.post(checkoutlink, headers=headers, json=checkoutPayload) webhook = DiscordWebhook(url=webhookURL) embed = DiscordEmbed(title='Raffle Bot - Succes!', description='Succesful entry on extra butter - email ' + email, color=int('009000')) webhook.add_embed(embed) webhook.execute()
def namegen(): global firstname global lastname firstname = names.get_first_name() lastname = names.get_last_name() return firstname + ' ' + lastname