예제 #1
0
    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)
예제 #2
0
    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)
예제 #3
0
파일: test_names.py 프로젝트: djibson/names
 def test_random_gender(self):
     counts = defaultdict(int)
     rounds = 5000.0
     with patch_file(test_files):
         for i in range(int(rounds)):
             names.get_first_name()
             counts[names.get_first_name()] += 1
     self.assertAlmostEqual(counts['Male'] / rounds, 0.500, delta=0.05)
     self.assertAlmostEqual(counts['Female'] / rounds, 0.500, delta=0.05)
예제 #4
0
파일: test_names.py 프로젝트: djibson/names
 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(), "")
예제 #5
0
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)
예제 #6
0
 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")
예제 #7
0
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
예제 #8
0
def Bfunc():
    global Bnames
    Bnames = ""
    while Bnames == "":
        name = names.get_first_name()
        if name[0] == "B":
            Bnames = name
예제 #9
0
def generate_ledger(num_nodes, num_transactions, max_amount, min_amount):
    max_num_transactions = num_nodes * (num_nodes - 1)
    if num_transactions is None:
        num_transactions = 10
    elif num_transactions == "max":
        num_transactions = max_num_transactions
    elif int(num_transactions) > max_num_transactions:
        print("num transactions is larger than max num transactions ({})".format(max_num_transactions))
        exit(1)
    num_transactions = int(num_transactions)
    ledger = {}
    while len(ledger) < num_nodes:
        name = names.get_first_name()
        if name in ledger:
            continue
        ledger[name] = dict()
    keys = list(ledger.keys())
    for i in range(num_transactions):
        name_from = None
        name_to = None
        while name_to == name_from or name_to in ledger[name_from]:
            name_from = random.choice(keys)
            name_to = random.choice(keys)
        amount = random.randint(min_amount * 100, max_amount * 100) / 100
        # mark entry in ledger
        ledger[name_from][name_to] = amount
    return ledger
예제 #10
0
def Cfunc():
    global Cnames
    Cnames = ""
    while Cnames == "":
        name = names.get_first_name()
        if name[0] == "C":
            Cnames = name
예제 #11
0
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()
예제 #12
0
def available_alias(pubkey):

    name = names.get_first_name().lower()
    if db.save_alias(name, pubkey):
        return name
    else:
        return available_alias(pubkey)
예제 #13
0
 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
예제 #14
0
    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
예제 #15
0
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)
예제 #16
0
파일: people.py 프로젝트: zleach/tradewind
    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')
예제 #17
0
 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()
예제 #18
0
 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()
예제 #19
0
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)
예제 #20
0
def data():
    """Create some fake data in a dataframe"""
    x_size = len(fasta)
    y_size = 10
    numpy.random.seed(0)
    M = numpy.random.randint(0, 1000, (x_size, y_size))
    df = pandas.DataFrame(M, index=[seq.id for seq in fasta], columns=[names.get_first_name() for j in range(y_size)])
    return df
예제 #21
0
    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()
예제 #22
0
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)
예제 #23
0
 def _get_name(self):
     """
     Randomly generate a unique name for this worker
     """
     name = names.get_first_name()
     if name in self.db.get_workers():
         self._get_name()
     else:
         return name
예제 #24
0
파일: main.py 프로젝트: mrketchup/playball
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
예제 #25
0
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
예제 #26
0
파일: utils_tests.py 프로젝트: ico88/jorvik
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
예제 #27
0
def home():
    if 'username' not in session:
        while True:
            name = names.get_first_name()
            if name not in users:
                session['username'] = name
                print name
                users[name] = random.choice(range(00000, 99999))
                break
    return render_template("index.html", myUserName=session['username'], myUserID=users[session['username']])
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())
예제 #29
0
    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"
예제 #30
0
 def post(self):
     token = self.request.get('from')
     user = names.get_first_name()
     db = User(id=token)
     db.user = user
     db.token = token
     db.put()
     announce_to_slack(user)
     to_client = {'user': user}
     channel.send_message(token, jdumps(to_client))
예제 #31
0
 def generate(self):
     if len(self.name) == 0: return names.get_first_name()
예제 #32
0
number_of_cities = int(sys.argv[1])
n_o_b = 30
cities = []


class City:
    def __init__(self, x, y, name):
        self.name = name
        self.x = x
        self.y = y


for i in range(number_of_cities):
    x = np.random.random() * 100
    y = np.random.random() * 100
    city = City(x, y, names.get_first_name())
    cities.append(city)


def fact(n):
    res = 1
    for i in range(2, n + 1):
        res *= i
    return res


def swap(array, i, j):
    temp = array[i]
    array[i] = array[j]
    array[j] = temp
    return array
예제 #33
0
        templist.insert(3, 'NA')
        templist.insert(3, 'NA')
        templist.insert(3, 'NA')
        finalresult.append(templist)
    if pepdic.has_key(templist[2].strip()):
        pepdic[templist[2].strip()].append(templist)
    else:
        pepdic[templist[2].strip()] = [templist]
peptidelist = pepdic.keys()
peptidelist = list(set(peptidelist))
# peptidelist=peptidelist[:10]
if len(peptidelist) > 0:
    mydate = datetime.datetime.now()
    for x in range(0, len(peptidelist), 100):
        temppeplist = peptidelist[x:x + 100]
        nameFolder = names.get_first_name()
        folder_name = nameFolder + "_" + mydate.strftime("%B_%d_%Y_%H_%M_%S")
        os.makedirs('./downloadfile/' + folder_name)
        downloadfilepath = curr_dir + '/downloadfile/' + folder_name
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--allow-running-insecure-content")
        # chrome_options.add_argument('--headless')
        preferences = {
            "download.default_directory": downloadfilepath,
            "directory_upgrade": True,
            "safebrowsing.enabled": True
        }
        chrome_options.add_experimental_option("prefs", preferences)
        driverpath = curr_dir + '/driver/chrome/linux/chromedriver'
        driver = webdriver.Chrome(chrome_options=chrome_options,
                                  executable_path=driverpath)
예제 #34
0
def import_mock():
    if not 'event' in request.json:
        return jsonify(success=False, reason="Event is a required parament.")
    event = db.session.query(Event).filter(
        Event.id == request.json['event']).one_or_none()
    if not event:
        return jsonify(success=False,
                       reason="Could not locate event {}".format(
                           request.json['event']))
    badges = db.session.query(Badge).filter(Badge.event_id == event.id).all()
    if badges:
        return jsonify(
            success=False,
            reason=
            "You cannot generate mock data if there are already badges. Please delete the badges first if you really want junk data."
        )
    staff_badge_type = db.session.query(BadgeType).filter(
        BadgeType.name == "Staff").one_or_none()
    if not staff_badge_type:
        staff_badge_type = BadgeType(name="Staff",
                                     description="Helps run the show")
        db.session.add(staff_badge_type)
    attendee_badge_type = db.session.query(BadgeType).filter(
        BadgeType.name == "Attendee").one_or_none()
    if not attendee_badge_type:
        attendee_badge_type = BadgeType(name="Attendee",
                                        description="Come to see the show")
        db.session.add(attendee_badge_type)
    db.session.flush()
    if 'attendees' in request.json:
        print("Generating {} attendees".format(request.json['attendees']))
        for i in range(request.json['attendees']):
            if i % 1000 == 0:
                print("  ...{}/{}".format(i, request.json['attendees']))
            first_name = names.get_first_name()
            last_name = names.get_last_name()
            legal_name = "{} {}".format(first_name, last_name)
            full_name = legal_name
            legal_name_matches = True
            printed_name = legal_name
            if random.random() > 0.95:
                legal_name = names.get_full_name()
                legal_name_matches = False
            if random.random() > 0.75:
                printed_name = names.get_last_name()
            provider = random.choice(
                ["verizon", "gmail", "yahoo", "aol", "magfest"])
            site = random.choice(["net", "com", "org", "co.uk"])
            email = "{}.{}@{}.{}".format(first_name, last_name, provider, site)
            badge = Badge(
                event_id=event.id,
                badge_type=attendee_badge_type.id,
                printed_number=(((i + request.json['staffers']) // 1000 + 1) *
                                1000) if 'staffers' in request.json else i,
                printed_name=printed_name,
                search_name=printed_name.lower(),
                first_name=first_name,
                last_name=last_name,
                legal_name=legal_name,
                legal_name_matches=legal_name_matches,
                email=email)
            db.session.add(badge)

    departments = []
    if 'departments' in request.json:
        print("Generating {} departments...".format(
            request.json['departments']))
        dept_names = {}
        while len(dept_names.keys()) < request.json['departments']:
            name = random.choice([
                "Tech", "Staff", "Arcade", "Game", "Medical", "Hotel", "Cat",
                "Concert", "Music", "Security", "Food", "Rescue", "Warehouse",
                "Logistics", "Truck", "Management"
            ])
            name += random.choice([
                " Ops", " Management", " Wranglers", " Herders", "",
                " Chasers", " Fixers", " Breakers", " Managers", " Destroyers",
                " Cleaners"
            ])
            name = ''.join(
                [x.upper() if random.random() < 0.05 else x for x in name])
            dept_names[name] = None
        for name in dept_names.keys():
            description = "The {} department.".format(name)
            department = Department(name=name,
                                    description=description,
                                    event_id=event.id)
            db.session.add(department)
            departments.append(department)

    staffers = []
    if 'staffers' in request.json:
        print("Generating {} staffers...".format(request.json['staffers']))
        for i in range(request.json['staffers']):
            if i % 1000 == 0:
                print("  ...{}/{}".format(i, request.json['staffers']))
            first_name = names.get_first_name()
            last_name = names.get_last_name()
            legal_name = "{} {}".format(first_name, last_name)
            full_name = legal_name
            legal_name_matches = True
            printed_name = legal_name
            if random.random() > 0.95:
                legal_name = names.get_full_name()
                legal_name_matches = False
            if random.random() > 0.75:
                printed_name = names.get_last_name()
            provider = random.choice(
                ["verizon", "gmail", "yahoo", "aol", "magfest"])
            site = random.choice(["net", "com", "org", "co.uk"])
            email = "{}.{}@{}.{}".format(first_name, last_name, provider, site)
            badge = Badge(event_id=event.id,
                          badge_type=staff_badge_type.id,
                          printed_number=i,
                          printed_name=printed_name,
                          search_name=printed_name.lower(),
                          first_name=first_name,
                          last_name=last_name,
                          legal_name=legal_name,
                          legal_name_matches=legal_name_matches,
                          email=email)
            db.session.add(badge)
            staffers.append(badge)
        print("Flushing database...")
        db.session.flush()
        print("Adding staffers to departments...")
        for staffer in staffers:
            staffer_depts = list(departments)
            hotel_requested = False
            declined = False

            preferred_department = None
            for i in range(int(random.random() / 0.3)):
                staffer_dept = random.choice(staffer_depts)
                staffer_depts.remove(staffer_dept)
                assignment = BadgeToDepartment(badge=staffer.id,
                                               department=staffer_dept.id)
                db.session.add(assignment)
                preferred_department = staffer_dept.id

            if random.random() > 0.3:
                hotel_requested = True
                if random.random() > 0.1:
                    declined = True
                hotel_request = HotelRoomRequest(
                    badge=staffer.id,
                    declined=declined,
                    prefer_department=random.random() > 0.1,
                    preferred_department=preferred_department,
                    notes="Please give room.",
                    prefer_single_gender=random.random() > 0.3,
                    preferred_gender=random.choice(['male', 'female',
                                                    'other']),
                    noise_level=random.choice([
                        'Quiet - I am quiet, and prefer quiet.',
                        "Moderate - I don't make a lot of noise.",
                        "Loud - I'm ok if someone snores or I snore.",
                    ]),
                    smoke_sensitive=random.choice([True, False]),
                    sleep_time=random.choice(
                        ['2am-4am', '4am-6am', '6am-8am', '8am-10am']),
                )
                db.session.add(hotel_request)
    print("Committing...")
    db.session.commit()
    print("Done!")
    return jsonify(success=True)
예제 #35
0
from random import randint
from time import sleep

from email.Header import Header
from email.mime.text import MIMEText

# Open a file for reading

lines = open("/root/MyPythonCode/testdata.txt").read().splitlines()
me = "<<REMOVED>>"  # change to your email
p_reader = open("<<REMOVED>>", "rb")  # edit for your password
cipher = p_reader.read()

while True:
    email = random.choice(lines)
    firstname = names.get_first_name()
    recipients = [email]  # enter recipients here
    fp = open("message.txt", "rb")
    # multipart class is for multiple recipients
    msg = MIMEText(fp.read(), "html", "utf-8")
    fp.close()
    thread_number = random.randint(0, 10000)
    msg["Subject"] = Header("Hi " + firstname + ",  Hi!", "utf-8")
    msg["From"] = me
    msg["To"] = ", ".join(recipients)
    s = smtplib.SMTP(host="smtp.gmail.com", port=587)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(me, cipher)
    s.sendmail(me, recipients, msg.as_string())
예제 #36
0
import unittest
import names
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

NEW_NAME = names.get_first_name()


class EditProfile(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('http://kmg.hcm.pl/testowanie_poprawione')
        self.driver.implicitly_wait(10)

    def test_login_edit_profile(self):
        self.driver.find_element_by_id('userLogin').send_keys('adam442')
        self.driver.find_element_by_id('passwordLogin').send_keys('adam442')
        self.driver.find_element_by_id('login').send_keys(Keys.ENTER)

        wait = WebDriverWait(self.driver, 10)
        self.driver.element = wait.until(EC.title_contains('PSTO webMessenger - Zalogowano'))

        assert 'PSTO webMessenger - Zalogowano' in self.driver.title

        # time.sleep(3)
예제 #37
0
def main():
        
    #how many accounts we need  
    ntimes = 1
        
    for i in range(1,ntimes+1):     
     
        print "starting browser"
        firstname = names.get_first_name()
        #print "firstname", firstname
        lastname = names.get_last_name()
        #print "lastname", lastname
                
        browser = Browser() #Browser(user_agent="Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en)")
        
        
        browser.visit('https://passport.yandex.com/registration/mail')
        
        browser.find_by_id('firstname').fill(firstname)
        browser.find_by_id('lastname').fill(lastname)
        
        testlogin = False
        count = 0
        while (testlogin == False):
            count = count + 1
            login = firstname+lastname+str(randint(10,1000))
            print "login:"******"div.control__error__login_notavailable", wait_time=2)
            if browser.is_text_present("username available"):
                testlogin = True
            else:
                print "login is not available, generate new"
            if (count>3):
                #print "logins in this script is unavailable now, please make new login generator"
                browser.quit()
                sys.exit("logins in this script is unavailable now, please make new login generator")
                
        password = password_generator.generate()
        print "password:"******"hint_question_id").click()
        
        #wait 
        browser.is_element_not_present_by_css("li[role=\"presentation\"]", wait_time=3)
        
        #check first question
        browser.find_by_css("li[role=\"presentation\"]")[1].click()
        
        browser.find_by_id("hint_answer").fill(firstname)
        
        gateimgcode = captcha(browser)
        browser.find_by_id('answer').fill(gateimgcode)
        
        browser.find_by_css("button[type=\"submit\"]").click()
        
        testcaptcha = False
        count = 0
        while (testcaptcha == False):
            count = count + 1
            browser.is_element_not_present_by_css("div.control__error__captcha_incorrect", wait_time=2)          
            if browser.is_text_present("characters were entered incorrectly"):
                print "captcha code is bad, try again"

                browser.find_by_id('password').fill(password)
                browser.find_by_id('password_confirm').fill(password)
                gateimgcode = captcha(browser)
                browser.find_by_id('answer').fill(gateimgcode)
                browser.find_by_css("button[type=\"submit\"]").click()
            else:
                testcaptcha = True
            if (count>3):
                #print "something wrong with captcha"
                browser.quit()
                sys.exit("something wrong with captcha")
                
        browser.is_element_not_present_by_tag("html", wait_time=2)
        
        if browser.is_text_present("Personal information"):        
            today = datetime.date.today()
            filename = 'yandex'+str(today)+'.txt'
            file = open(filename,'a')
            file.write(login+'@yandex.com'+':'+login+':'+password+'\n')
            file.close()
            print str(i)+" accounts saved to "+filename
            browser.quit()
        else:
            #print "something wrong, please start script again"
            browser.quit()
            sys.exit("something wrong, please start script again")
예제 #38
0
user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=100)

# Get list of user agents.
user_agents = user_agent_rotator.get_user_agents()

# Get Random User Agent String.
# user_agent = user_agent_rotator.get_random_user_agent()

p = KinesisProducer('EventStream', flush_callback=on_flush)
for i in range(10):
    _generated = coolname.generate()
    p.put_record(i,
        metadata={
            'request_id': uuid4(),
            'request_timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S.000000"),
            'cookie_id': uuid4(),
            'topic': '.'.join(_generated[:3]),
            "message": "{\"isAffiliate\":false,\"language\":\"es\",\"isRecommendedPalette\":true,\"color\":\"#6d8d79\",\"paletteIndex\":\"0\",\"workspaceId\":\"" +  f"{uuid4()}" + "\"}",
            'message':  "{}.{}".format(names.get_first_name(),names.get_last_name()),
            'environment': _generated[0],
            "website_id": None,
            'user_account_id':  uuid4(),
            "location": "https://cms.jimdo.com/wizard/color-palette/",
            'user_agent': user_agent_rotator.get_random_user_agent(),
            "referrer": "https://register.jimdo.com/es/product"
            },
        partition_key=f"{i % 2}")

p.close()
예제 #39
0
    def genName():
        firstname = names.get_first_name()
        lastname = names.get_last_name()

        return firstname + " " + lastname
예제 #40
0
    def run(self):
        for i in range(config['max_entries_per_thread']):
            if config['use_proxies']:
                self.curr_proxy = Presto.proxy_queue.get()
                self.sess = Presto.sessions[self.curr_proxy]
            self.sess.headers.update(
                {'User-Agent': generate_user_agent(device_type='desktop')})
            try:
                # get form
                resp = self.sess.get(url)
                if resp.status_code != 200:
                    logging.error(
                        f'{self.name} - error retrieving raffle page ({resp.status_code})'
                    )
                    continue
                # find unique id
                resid = re.search('name="fbzx" value="(.*?)">',
                                  resp.text).group(1)
                # create randomized data
                first = names.get_first_name()
                last = names.get_last_name()
                email = f'{first}.{last}@{config["catchall"]}'

                data = {
                    "emailAddress":
                    email,
                    "entry.1884265043":
                    first,
                    "entry.1938400468":
                    last,
                    "entry.1450673532_year":
                    str(randint(1975, 1995)),
                    "entry.1450673532_month":
                    '{:02}'.format(randint(1, 12)),
                    "entry.1450673532_day":
                    '{:02}'.format(randint(1, 27)),
                    "entry.71493440":
                    profile['address'] % rand_chars() +
                    choice(profile.get('endings'))
                    if profile.get('endings') else '',
                    "entry.1981412943":
                    profile['zip'],
                    "entry.950259558":
                    profile['city'],
                    "entry.1622497152":
                    choice([
                        'United States', 'US', 'USA',
                        'United States of America', 'U.S.A', 'U.S'
                    ]),
                    "entry.1850033056":
                    "",
                    "entry.769447175":
                    profile['ig_username'],
                    "entry.256744251_sentinel":
                    "",
                    "entry.256744251":
                    "Autorizzo il trattamento dei miei dati personali, ai sensi del D.lgs. 196 del 30 giugno 2003",
                    "entry.715796591":
                    str(randint(4, 12)),
                    "fvv":
                    "1",
                    "draftResponse":
                    f'[null,null,"{resid}"]',
                    "pageHistory":
                    "0",
                    "fbzx":
                    f'{resid}'
                }
                headers = {
                    "Upgrade-Insecure-Requests": "1",
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Accept":
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                    "X-Client-Data":
                    "CJG2yQEIorbJAQjEtskBCKmdygEI153KAQioo8oB",
                    "X-Chrome-Connected":
                    "id=113292259032357480973,mode=0,enable_account_consistency=false",
                    "Referer": f'{url}?fbzx={resid}',
                    "Accept-Encoding": "gzip, deflate, br1",
                    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8"
                }
                # submit post request
                self.sess.post(post_url,
                               headers=headers,
                               data=data,
                               hooks={'response': partial(handle_post, email)})
            except Exception as e:
                logging.error(f'{self.name} - exception caught:\n{e}')
                time.sleep(config['exception_timeout'])
            finally:
                self.sess.cookies.clear()
                if self.curr_proxy:
                    Presto.proxy_queue.put_nowait(self.curr_proxy)
                    self.curr_proxy = None
예제 #41
0
# execfile('management/bulk_user_gen.py') in python manage.py shell

from django.contrib.auth.models import User
import names
users = []

number = raw_input("How many users should be generated? ")

print "Generating users...."

for i in range(int(number)):
    user = User(first_name=names.get_first_name(), 
                last_name=names.get_last_name(),
                username=names.get_first_name() + '%d' % int(random.randrange(1000)),
                email='*****@*****.**' % names.get_first_name(),
                password='******',
                is_active=True, )
    users.append(user)
 
User.objects.bulk_create(users)
예제 #42
0
def nmes():
    full_names = names.get_full_name()

    gender = choice(['male', 'female'])
    firstname = names.get_first_name(gender=gender)
    lastname = names.get_last_name()
    email = (firstname + choice("-_.") + lastname).lower() + "".join(
        [str(randint(0, 10)) for x in range(randint(1, 5))]) + '@' + catchall

    #ABC=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    char = 3
    prefix = string.ascii_uppercase + string.digits

    prefix1 = ''.join(random.choice(prefix) for _ in range(char))

    num1 = randint(100, 999)
    num2 = randint(1000, 9999)
    '''if answer = str(y):
        print :
    if answer = str(n):
        print:
    else:
        print('that is not a valid answer, please pick y/n!!')
    print(full_names)
    '''
    address1 = (prefix1 + ' ' + address)
    address2 = ('apt ' + str(num2))
    phone = area + '-' + str(num1) + '-' + str(num2)
    phone1 = area + str(randint(2345532, 9864567))
    address3 = ' '
    cardNumber = input('cardNumber: ')
    cardMonth = input('cardmonth: ')
    cardYear = input('cardyear(####): ')
    cardCVV = input('cardcvv: ')
    astro_file = ("astro.csv")
    eve_file = ("eve.csv")
    kickmoji_file = ("kickmoji.csv")
    bnb_file = ("bnb.csv")
    numb = str(randint(1, 100))
    cardtype = 'cardtype'

    astro = (firstname + ',' + full_names + ',' + phone + ',' + email + ',' +
             address + ',' + address2 + ',' + city + ',' + state + ',' +
             zipcode + ',' + country + ',' + cardNumber + ',' + cardMonth +
             ',' + cardYear + ',' + cardCVV)
    astro1 = (firstname + ',' + full_names + ',' + phone + ',' + email + ',' +
              address1 + ',' + address3 + ',' + city + ',' + state + ',' +
              zipcode + ',' + country + ',' + cardNumber + ',' + cardMonth +
              ',' + cardYear + ',' + cardCVV)
    #cyber=
    kickmoji = (numb + ',' + firstname + ',' + firstname + ',' + lastname +
                ',' + address3 + ',' + address3 + ',' + phone1 + ',' +
                cardtype + ',' + cardNumber + ',' + cardCVV + ',' + ',' +
                cardMonth + ',' + cardYear + ',' + address + ',' + address2 +
                ',' + address3 + ',' + city + ',' + state + ',' + country +
                ',' + zipcode)
    eve = 'trial'
    bnb = (firstname + ',' + firstname + ',' + lastname + ',' + address + ',' +
           address2 + ',' + ',' + zipcode + ',' + phone1 + ',' + city + ',' +
           state)
    if bot_names == 'astro':
        f = open(astro_file, 'a')
        f.write(astro + '\n')
        print("[" + (time.strftime("%H:%M:%S")) + "]" + " loading............")
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " Profile successfully created............")

        print('                  ')
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " please enter your new card information............")
    elif bot_names == 'eve':
        f = open(eve_file, 'a')
        f.write(eve + '\n')
        print("[" + (time.strftime("%H:%M:%S")) + "]" + " loading............")
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " Profile successfully created............")

        print('                  ')
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " please enter your new card information............")

    elif bot_names == 'kickmoji':
        f = open(kickmoji_file, 'a')
        f.write(kickmoji + '\n')
        print("[" + (time.strftime("%H:%M:%S")) + "]" + " loading............")
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " Profile successfully created............")
        print('                  ')
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " please enter your new card information............")

    elif bot_names == 'bnb':
        f = open(bnb_file, 'a')
        f.write(kickmoji + '\n')
        print("[" + (time.strftime("%H:%M:%S")) + "]" + " loading............")
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " Profile successfully created............")
        print('                  ')
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              " please enter your new card information............")

    else:
        print("[" + (time.strftime("%H:%M:%S")) + "]" +
              "we are working on a template for" + bot_names)
예제 #43
0
파일: app.py 프로젝트: moopiing/xDeFiBot
    login_email.location_once_scrolled_into_view
    login_email.click()

    input_full_name = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((
            By.XPATH,
            '/html/body/div[1]/div/div/div[1]/div/div[1]/div[1]/div[6]/div[2]/div[2]/div/form/fieldset[2]/div[2]/div/div/div[1]/label/div[2]/input'
        )))
    input_full_name.send_keys(names.get_full_name())

    input_email = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((
            By.XPATH,
            '/html/body/div[1]/div/div/div[1]/div/div[1]/div[1]/div[6]/div[2]/div[2]/div/form/fieldset[2]/div[2]/div/div/div[2]/label/div[2]/input'
        )))
    input_email.send_keys(names.get_first_name().lower() + "_" +
                          names.get_last_name().lower() + "@gmail.com")

    btn_cont = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((
            By.XPATH,
            '/html/body/div[1]/div/div/div[1]/div/div[1]/div[1]/div[6]/div[2]/div[2]/div/form/div/span[1]/button/span[2]'
        )))
    btn_cont.click()

    subs = ["em5433464", "em5433785", "em5433793", "em5433809"]
    rand_sub = random.choice(subs)
    btn_subs = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located(
            (By.XPATH, '//*[@id="' + rand_sub + '"]/a')))
    driver.execute_script("arguments[0].click();", btn_subs)
예제 #44
0
db_adapter = SQLAlchemyAdapter(db, User)  # Register the User model
user_manager = UserManager(db_adapter, app)  # Initialize Flask-User

from datetime import date
today = date.today()

import random

n_users = 50
import names

from app import forms

for i in xrange(0, n_users):
    print i
    ns = [names.get_first_name(), names.get_last_name()]
    u = User(email='*****@*****.**' % (ns[0], ns[1]),
             affiliation=forms.unis[random.randint(1,
                                                   len(forms.unis) - 1)],
             first_name=ns[0],
             last_name=ns[1],
             active=True,
             password=user_manager.hash_password('a'),
             confirmed_at=today,
             is_admin=False)

    u.is_attending = bool(random.randint(0, 1))
    u.intends_workshop = bool(random.randint(0, 1))
    u.intends_poster = bool(random.randint(0, 1))
    u.intends_talk = bool(random.randint(0, 1))
    u.intends_dinner = bool(random.randint(0, 1))
예제 #45
0
def random_name():
    """
    Generating a name for bot.
    """
    return get_first_name(gender="male")
예제 #46
0
 def __init__(self, num_applicants):  #это конструктор для класса.
     self.applicants = {
         names.get_first_name(): randint(0, 100)
         for _ in range(num_applicants)
     }