Example #1
0
 def test_fetch_messages_created_before(self):
     other_user = UserFactory()
     other_dialog = Dialog.objects.create(owner=self.first_user,
                                          opponent=other_user)
     for i in range(40):
         msg = Message.objects.create(dialog=self.dialog,
                                      sender=self.first_user,
                                      text='What the f you mean?',
                                      created=random_datetime())
         Message.objects.create(dialog=other_dialog,
                                sender=self.first_user,
                                text='What huh',
                                created=random_datetime())
     message_count = 5
     expected_result = [
         msg.id
         for msg in Message.objects.filter(dialog=msg.dialog,
                                           created__lt=msg.created).all()
         [:message_count]
     ]
     received_result = [
         msg.id
         for msg in Message.fetch_messages_from_dialog_created_before(
             message=msg, message_count=message_count)
     ]
     self.assertEqual(expected_result, received_result)
Example #2
0
def final_insert_st_groups():
    for x in range(1, NUM_OF_ST_GROUPS):
        group_number = 'group_number' + str(x)
        course_number = randint(1, 6)
        start_study_date = radar.random_datetime(start='2020-03-24T23:59:59',
                                                 stop='2021-05-24T23:59:59')
        end_study_date = radar.random_datetime(start='2020-03-24T23:59:59',
                                               stop='2021-05-24T23:59:59')
        st_groups.append(
            (x, group_number, course_number, start_study_date, end_study_date))
    insert_st_groups(st_groups)
def generateDateKeyFromQuarter(quarter_choice):
    year, quarter = quarter_choice.split("_")
    
    if quarter == "Q1":
        return str(radar.random_datetime(start=str(year + '-01-01'), stop=str(year + '-3-31')).date()).replace("-","")
        #return str(radar.random_datetime(start=str(year + '-01-01'), stop=str(year + '-3-31'))).replace("-","")
    elif quarter == "Q2":
        return str(radar.random_datetime(start=str(year + '-04-01'), stop=str(year + '-6-30')).date()).replace("-","")
        #return str(radar.random_datetime(start=str(year + '-04-01'), stop=str(year + '-6-30'))).replace("-","")
    elif quarter == "Q3":
        return str(radar.random_datetime(start=str(year + '-07-01'), stop=str(year + '-9-30')).date()).replace("-","")
        #return str(radar.random_datetime(start=str(year + '-07-01'), stop=str(year + '-9-30'))).replace("-","")

    return str(radar.random_datetime(start=str(year + '-10-01'), stop=str(year + '-12-31')).date()).replace("-","")
	def make_artists(self):
		import radar
		import datetime

		# Generate random datetime from datetime.datetime values
		radar.random_datetime(
		    start = datetime.datetime(year=1980, month=1, day=1),
		    stop = datetime.datetime(year=2000, month=1, day=1)
  		)
		_artists = ("Justin Bieber", "Anne Curtis", "Eminem", "Tupac", "Loonie")
		self.artists = []
		for name in _artists:
			# print options.get('count')[0]
			uni = mommy.make(Artist, name=name, birth_date=radar.random_datetime())
			self.artists.append(uni)
Example #5
0
def gen_events():
    events = generate_data.gen_event_types()
    names = generate_data.gen_names()
    foods = generate_data.gen_foods()

    output = {}

    for event_name in events:
        random.shuffle(foods)

        output[event_name] = list()
        tpl = tuple(zip(names, foods))
        for name, food in tpl:
            event = {
                'name':
                name,
                'food':
                food,
                'confirmed':
                random.choice([True, False]),
                'signup_date':
                radar.random_datetime(start='2017-06-01',
                                      stop='2017-12-31').strftime('%Y-%m-%d')
            }
            output[event_name].append(event)

    return output
Example #6
0
    def produce_msgs(self, source_symbol):
        price_field = random.randint(800, 1400)
        msg_cnt = 0
        category_product = [('furniture', 'cat bed'),
                            ('dog food', 'purina dog biscuits'),
                            ('cat food', 'fancy feast 8oz'),
                            ('cleaning', 'roomba')]

        while True:

            rand_datetime = radar.random_datetime(start=datetime(year=2016,
                                                                 month=5,
                                                                 day=24),
                                                  stop=datetime(year=2017,
                                                                month=2,
                                                                day=1))
            time_field = rand_datetime.strftime("%Y%m%d %H%M%S")
            price_field += random.randint(-10, 10) / 10.0
            product_cat_listid = random.randint(0, 2)
            customer_field = random.randint(1, 10000)
            product_field = category_product[product_cat_listid][1]
            category_field = category_product[product_cat_listid][0]
            volume_field = random.randint(1, 10)
            str_fmt = "{};{};{};{};{};{};{}"
            message_info = str_fmt.format(source_symbol, time_field,
                                          price_field, volume_field,
                                          customer_field, product_field,
                                          category_field)
            print message_info
            self.producer.send_messages('transactiondata', source_symbol,
                                        message_info)
            msg_cnt += 1
Example #7
0
def speed_test(tablename, dbset, logger, timelogger, numtests, **kwargs):
    '''Run a number (numtests) of random row retrievals on table tablename

    Args:
        tablename: the name of the table to access
        dbset: the database connection settings
        logger: logger object for information
        timelogger: logger object to store query timing information
        numtests: the number of queries to perform
        kwargs: additional arguments to pass to the sql query
    Returns:
        None
    '''
    logger.info('Connecting to host:%s database: %s with user %s',
                dbset['host'], dbset['database'], dbset['user'])
    con = connect(database=dbset['database'],
                  host=dbset['host'],
                  user=dbset['user'],
                  password=dbset['password'])
    cur = con.cursor()

    logger.info('Retrieving distinct tmcs from table %s', tablename)
    tmcs = _get_tmcs(cur, tablename)
    logger.info('Retrieving min, max dates from table %s', tablename)
    timerange = _get_timerange(cur, tablename)
    logger.info('Retrieved tmcs and dates from table %s', tablename)

    for i in range(numtests):
        tmc = random.choice(tmcs)[0]
        tx = radar.random_datetime(start=timerange[0], stop=timerange[1])

        time1 = time.time()
        while True:
            try:
                _retrieve_raw_data(cur, tablename, tx, tmc, **kwargs)
            except OperationalError as oe:
                logger.error(oe)

                try:
                    logger.info('Testing Connection')
                    cur.execute('SELECT 1')
                except (OperationalError, InterfaceError) as oe:
                    logger.error(oe)
                    logger.info('Retrying connection in 2 minutes')
                    time.sleep(120)
                    con = connect(database=dbset['database'],
                                  host=dbset['host'],
                                  user=dbset['user'],
                                  password=dbset['password'])
                    cur = con.cursor()
            else:
                break

        timelogger.info('%s,%s,%s,%s', 'random_row_retrieval_index_score30',
                        tablename, i,
                        time.time() - time1)
    cur.close()
    con.close()
    logger.info('Testing complete. Connection to %s database %s closed',
                dbset['host'], dbset['database'])
Example #8
0
    def test_05_random_datetime_with_string_ranges_given(self):
        """
        Test ``radar.random_datetime`` with string ranges given.
        """
        start = '2012-05-24T00:00:00'
        stop = '2013-05-24T23:59:59'

        dt_start = datetime.datetime(year=2012,
                                     month=5,
                                     day=24,
                                     hour=0,
                                     minute=0,
                                     second=0)
        dt_stop = datetime.datetime(year=2013,
                                    month=5,
                                    day=24,
                                    hour=23,
                                    minute=59,
                                    second=59)

        res = radar.random_datetime(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.datetime))
        self.assertTrue(res > dt_start)
        self.assertTrue(res < dt_stop)
        return res
Example #9
0
    def genCmpny(self):

        # Variables
        curRow = []

        # use faker to generate the company info
        srvceId = self.getUniqId()
        cmpnyNme = str(self.faker.company())
        type = 'business'
        # Generate a random starting time
        regTime = radar.random_datetime(start='2017-01-1T00:00:00', stop='2017-01-01T23:59:59')
        regTime = regTime.strftime("%s")
        state = str(choice(self.states))
        srvceZipCode = self.faker.zipcode()

        # compact them into one list
        curRow.append(srvceId)
        curRow.append(cmpnyNme.replace(",", ""))
        curRow.append(type)
        curRow.append(regTime)
        curRow.append(state)
        curRow.append(srvceZipCode)

        # debug statement
        # print "#====================#"
        # print "Current company details: "+str(cmpnyNme)

        # Return statement
        return curRow
Example #10
0
    def genUsr(self):

        # Variables
        curRow = []

        # use faker to get the required attribute
        srvceId = self.getUniqId()
        usrNme = self.faker.name()
        type = 'household'
        # Generate a random starting time
        regTime = radar.random_datetime(start=self.btchStrtTime, stop=self.btchEndTime)
        regTime = regTime.strftime("%s")
        state = str(choice(self.states))
        srvceZipCode = self.faker.zipcode()

        # compact them into one list
        curRow.append(srvceId)
        curRow.append(usrNme.replace(",", ""))
        curRow.append(type)
        curRow.append(regTime)
        curRow.append(state)
        curRow.append(srvceZipCode)

        # debug statement
        # print "#====================#"
        # print "Current user details: "+str(usrNme)

        # Return statement
        return curRow
Example #11
0
    def handle(self, *args, **options):
        words = WORDS[:]
        images = build_image_factory()

        if not len(images):
            images = [None for __img in range(NUM_ITEMS)]

        while len(images):
            item = NewsItem()
            random_name = words[random.randint(0, len(words) - 1)]
            item.title = text_type(random_name).capitalize()
            item.slug = "{0}-{1}".format(slugify(item.title), uuid.uuid4())
            item.image = images.pop()
            item.body = text_type(SENTENCES[random.randint(
                0,
                len(SENTENCES) - 1)])
            item.date_published = radar.random_datetime()

            try:
                item.save()
                words.remove(random_name)

            except Exception as err:
                images.append(item.image)
                logger.debug(err)
Example #12
0
 def test_01_random_datetime(self):
     """
     Test ``radar.random_datetime``.
     """
     res = radar.random_datetime()
     self.assertTrue(isinstance(res, datetime.datetime))
     return res
Example #13
0
 def test_01_random_datetime(self):
     """
     Test ``radar.random_datetime``.
     """
     res = radar.random_datetime()
     self.assertTrue(isinstance(res, datetime.datetime))
     return res
Example #14
0
    def genCmpny(self):

        # Variables
        curRow = {}

        # use faker to generate the company info
        srvceId = self.getUniqId()
        cmpnyNme = str(self.faker.company())
        type = 'business'
        # Generate a random starting time
        regTime = radar.random_datetime(start=self.btchStrtTime, stop=self.btchEndTime)
        regTime = regTime.strftime("%s")
        state = str(choice(self.states))

        # compact them into one list
        curRow['service_id'] = srvceId
        curRow['user_name'] = cmpnyNme.replace(",", "")
        curRow['type'] = type
        curRow['strtTime'] = regTime
        curRow['state'] = state

        # debug statement
        # print "#====================#"
        # print "Current company details: "+str(cmpnyNme)

        # Return statement
        return curRow
    def handle(self, *args, **options):
        words = WORDS[:]
        images = build_image_factory()

        if not len(images):
            images = [None for __img in range(NUM_ITEMS)]

        while len(images):
            item = NewsItem()
            random_name = words[random.randint(0, len(words) - 1)]
            item.title = text_type(random_name).capitalize()
            item.slug = "{0}-{1}".format(slugify(item.title), uuid.uuid4())
            item.image = images.pop()
            item.body = text_type(
                SENTENCES[random.randint(0, len(SENTENCES) - 1)]
            )
            item.date_published = radar.random_datetime()

            try:
                item.save()
                words.remove(random_name)

            except Exception as err:
                images.append(item.image)
                logger.debug(err)
Example #16
0
    def genUsr(self):

        # Variables
        curRow = {}

        # use faker to get the required attribute
        srvceId = self.getUniqId()
        usrNme = self.faker.name()
        type = 'household'
        # Generate a random starting time
        regTime = radar.random_datetime(start=self.btchStrtTime, stop=self.btchEndTime)
        regTime = regTime.strftime("%s")
        state = str(choice(self.states))

        # compact them into one list
        curRow['service_id'] = srvceId
        curRow['user_name'] = usrNme.replace(",", "")
        curRow['type'] = type
        curRow['strtTime'] = regTime
        curRow['state'] = state

        # debug statement
        # print "#====================#"
        # print "Current user details: "+str(usrNme)

        # Return statement
        return curRow
Example #17
0
def random_date():
    # Generate random datetime (parsing dates from str values)
    date = (radar.random_datetime(start='1800-01-01', stop='2199-01-01'))
    print("Birthdate:", date)
    #print (dir(date))
    #date = str(date)
    return date
Example #18
0
    def disburse(loan_account):
        term = loan_account.terms.latest('created_at')

        repayment_period = term.repayment_period
        repayment_period_unit = term.repayment_period_unit

        if repayment_period_unit.code == LP_DAY:
            delta = timedelta(days=repayment_period)
        elif repayment_period_unit.code == LP_WEEK:
            delta = timedelta(days=float(repayment_period * DAYS_IN_A_WEEK))
        elif repayment_period_unit.code == LP_MONTH:
            delta = timedelta(days=float(repayment_period * DAYS_IN_A_MONTH))
        elif repayment_period_unit.code == LP_YEAR:
            delta = timedelta(days=float(repayment_period * DAYS_IN_A_YEAR))
        else:
            delta = timedelta(days=float(repayment_period * DAYS_IN_A_YEAR))

        start_date = (timezone.now() - delta)
        date_disbursed = radar.random_datetime(start=start_date, stop=timezone.now())

        return disburse_loan(
            loan_account, 
            User.objects.get(pk=3), 
            date_disbursed=date_disbursed,
            notes="blah " * 5,
        )
Example #19
0
def _get_random_day(year=2000):
    born_date = radar.random_datetime(start=datetime.datetime(year=year,
                                                              month=1,
                                                              day=10),
                                      stop=datetime.datetime(year=year,
                                                             month=12,
                                                             day=31))
    return born_date.strftime('%m/%d/%Y')
Example #20
0
 def generator_time(self, year=2020, *, month):
     time = radar.random_datetime(start=datetime.datetime(year=year,
                                                          month=month,
                                                          day=1),
                                  stop=datetime.datetime(year=year,
                                                         month=month,
                                                         day=28))
     return time
Example #21
0
def generate_datetime():

    date = radar.random_datetime(start=datetime(year=2019, month=5, day=1),
                                 stop=datetime(year=2019, month=12, day=31))

    if date.hour == 0:
        date = generate_datetime()

    return date
Example #22
0
 def form_url(self):
     today = strftime("%Y-%m-%d", gmtime())
     date = random_datetime(start='2012-08-06',
                            stop=today)  # 2012-08-06  - landing date
     return 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?{query}'.format(
         query=urlencode({
             'api_key': NASA_API_KEY,
             'earth_date': date
         }))
Example #23
0
def final_insert_teachers():
    for x in range(1, NUM_OF_TEACHERS):
        name = 'teacherName' + str(x)
        surname = 'teacherSurname' + str(x)
        patronymic = 'teacherPatronymic' + str(x)
        date_of_birth = radar.random_datetime(start='1910-03-24T23:59:59',
                                              stop='2021-05-24T23:59:59')
        country_of_birth = 'teacherCountry_of_birth' + str(x)
        city_of_birth = 'teacherCity_of_birth' + str(x)
        faculty_id = randint(1, NUM_OF_FACULTIES - 1)
        person_job_id = randint(1, NUM_OF_PER_JOBS - 1)
        start_date = radar.random_datetime(start='2021-03-24T23:59:59',
                                           stop='2021-05-24T23:59:59')
        end_date = radar.random_datetime(start='2021-03-24T23:59:59',
                                         stop='2021-05-24T23:59:59')
        teachers.append(
            (x, name, surname, patronymic, date_of_birth, country_of_birth,
             city_of_birth, faculty_id, person_job_id, start_date, end_date))
    insert_teachers(teachers)
Example #24
0
def issue_invoice_timed():
    headers = {'Content-type': 'application/json',
               'Accept': 'application/json'}
    url = 'http://localhost:8000/api/facturar'
    fecha = radar.random_datetime(
        start='2017-01-01', stop='2017-01-30').date().strftime('%d-%m-%Y')
    invoice = receipt_json("2033", fecha)
    a = requests.post(url, data=json.dumps(invoice), headers=headers)
    print("\033[94m"+fecha, "\033[94m"+"2033", "\033[94m"+repr(a))
    print("Finalizado.")
Example #25
0
class Constants:
    TODAY = datetime.today().strftime("%Y-%m-%d")
    TOMORROW = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
    YESTERDAY = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
    RANDOM_DATE_VALID_1 = radar.random_datetime(
        start='1995-06-16', stop='1997-12-31').strftime("%Y-%m-%d")
    RANDOM_DATE_VALID_2 = (datetime.strptime(RANDOM_DATE_VALID_1, "%Y-%m-%d") \
                           + timedelta(days=random.randint(1, 400))).strftime("%Y-%m-%d")
    RANDOM_DATE_FUTURE = radar.random_datetime(start=TOMORROW, \
                                stop=((datetime.strptime(TOMORROW, "%Y-%m-%d")+ \
                                      timedelta(days=random.randint(1, 400))).strftime("%Y-%m-%d"))).strftime("%Y-%m-%d")
    RANDOM_DATE_FUTURE_2 = (datetime.strptime(RANDOM_DATE_FUTURE, "%Y-%m-%d") \
                            + timedelta(days=random.randint(1, 400))).strftime("%Y-%m-%d")
    RANDOM_DATE_PAST = radar.random_datetime(
        stop='1995-06-15').strftime("%Y-%m-%d")
    RANDOM_DATE_PAST_2 = (datetime.strptime(RANDOM_DATE_PAST, "%Y-%m-%d") \
                          + timedelta(days=random.randint(1, 400))).strftime("%Y-%m-%d")
    RANDOM_NUMBER = random.randint(1, 100)
    RANDOM_NUMBER_INVALID = random.randint(101, 200)
    RANDOM_NUMBER_INVALID_NEG = random.randint(-100, 0)
Example #26
0
def final_insert_timetables():
    for x in range(1, NUM_OF_TIMETABLES):
        time_slot = radar.random_datetime(start='1910-03-24T23:59:59',
                                          stop='2021-05-24T23:59:59')
        room_number = randint(100, 300)
        teacher_id = randint(1, NUM_OF_TEACHERS - 1)
        subject_id = randint(1, NUM_OF_SUBJECTS - 1)
        study_group_id = randint(1, NUM_OF_ST_GROUPS - 1)
        timetables.append((x, time_slot, room_number, teacher_id, subject_id,
                           study_group_id))
    insert_timetables(timetables)
Example #27
0
def randomDateGen():
    randdate = radar.random_datetime(start=datetime.datetime(year=2000,
                                                             month=5,
                                                             day=24),
                                     stop=datetime.datetime(year=2020,
                                                            month=5,
                                                            day=24))
    randdate = str(randdate)
    size = len(randdate)
    mod_randdate = randdate[:size - 9]
    return mod_randdate
Example #28
0
def write_cvs(data):
    f_ = open(sys.argv[1], "w")
    wr = csv.writer(f_, encoding="utf-8", quoting=csv.QUOTE_ALL)
    for d in data:
        items = d["items"]
        for i in [dict(t) for t in set([tuple(f.items()) for f in items])]:
            random_date = radar.random_datetime(start=FROM_DATE, stop=TO_DATE)
            date_ = random_date.strftime("%x")
            time_ = random_date.strftime("%X")
            tran = random.randint(0,1)
            wr.writerow((i["item_name"], d['cat_name'], i['item_price'], date_, time_, tran))
    f_.close()
Example #29
0
def final_insert_rec_books():
    for x in range(1, NUM_OF_REC_BOOKS):
        student_id = x
        subject_id = x
        mark = randint(2, 5)
        mark_letters = ['a', 'b', 'c', 'd', 'e']
        mark_letter = random.choice(mark_letters)
        exam_date = radar.random_datetime(start='1910-03-24T23:59:59',
                                          stop='2021-05-24T23:59:59')
        rec_books.append(
            (student_id, subject_id, mark, mark_letter, exam_date))
    insert_rec_books(rec_books)
def create_crisis():
    Crisis.objects.all().delete()

    print "Now working on creating Crisis objects from Dheeraj's Last.Fm Band History. Crises represent situations requiring remediation, so they are drawn from albums. This, of course, makes sense. \n"

    album = pd.read_csv('games/source_data/lastfm_scrobbles.csv',
                        error_bad_lines=False,
                        encoding='utf_8_sig')['album'].dropna()
    albums = sorted(set(album))

    for al in albums:

        print "Now working on %s" % (al)
        crisis_name = al
        begins = radar.random_datetime(start=datetime(year=2000,
                                                      month=5,
                                                      day=24,
                                                      tzinfo=pytz.utc),
                                       stop=datetime(year=2017,
                                                     month=1,
                                                     day=1,
                                                     tzinfo=pytz.utc))
        ends = begins + timedelta(days=random.uniform(5, 365))

        country = Country.objects.order_by('?').first()
        radius = random.uniform(0.0, 50.0)

        for random_point in generate_random_points(country.geom.extent):
            if country.geom.contains(random_point):
                break

        origin = random_point

        coverage = origin.buffer(radius)

        try:
            c = Crisis(name=crisis_name,
                       start_date=begins,
                       end_date=ends,
                       country=country,
                       origin=origin,
                       radius=radius,
                       zone=coverage)
            c.save()
            print "Worked! %s" % c

        except Exception as ex:

            print "The error was : %s " % (ex)
            continue

    print "Success! There are now %s Crisis objects!" % (
        Crisis.objects.count())
Example #31
0
    def test_03_random_datetime_with_ranges_given(self):
        """
        Test ``radar.random_datetime`` with ranges given.
        """
        start = datetime.datetime(year=2000, month=5, day=24)
        stop = datetime.datetime(year=2013, month=5, day=24)

        res = radar.random_datetime(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.datetime))
        self.assertTrue(res > start)
        self.assertTrue(res < stop)
        return res
Example #32
0
    def test_03_random_datetime_with_ranges_given(self):
        """
        Test ``radar.random_datetime`` with ranges given.
        """
        start = datetime.datetime(year=2000, month=5, day=24)
        stop = datetime.datetime(year=2013, month=5, day=24)

        res = radar.random_datetime(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.datetime))
        self.assertTrue(res > start)
        self.assertTrue(res < stop)
        return res
Example #33
0
 def generate_time(self, interval, current):
     value = interval.split()
     delta = None
     if value[1] == "days":
         delta = timedelta(days=int(value[0]))
     elif value[1] == "hours":
         delta = timedelta(hours=int(value[0]))
     if delta:
         start = current - delta
         stop = current
         return radar.random_datetime(start, stop)
     else:
         print "NO DELTA VALUE"
Example #34
0
def generateData(n):
  listdata = []
  start = datetime.datetime(2019, 8, 1)
  end = datetime.datetime(2019, 8, 30)
  delta = end - start
  for _ in range(n):
    date = radar.random_datetime(start='2019-08-1', stop='2019-08-30').strftime("%Y-%m-%d")
    price = round(random.uniform(900, 1000), 4)
    listdata.append([date, price])
  df = pd.DataFrame(listdata, columns = ['Date', 'Price'])
  df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
  df = df.groupby(by='Date').mean()

  return df
Example #35
0
def generateRandomDate(startstr, stopstr):
    '''
	start='2000-05-24', stop='2013-05-24T23:59:59'
	start = datetime.datetime(year=2000, month=5, day=24),
    stop = datetime.datetime(year=2013, month=5, day=24)
    "now" -> datetime.datetime.now()
    return a date string
	'''
    startdate = startstr
    if stopstr == 'now':
        stopdate = datetime.datetime.now()
    else:
        stopdate = stopstr
    return radar.random_datetime(start=startdate, stop=stopdate).isoformat()
def create_crisis_instance(**kwargs):
    """Creates a Crisis instance, saves it and returns it"""

    if 'name' not in kwargs:
        kwargs.update({'name': random.sample(albums, 1)[0]})

    if 'start_date' not in kwargs:
        begins = radar.random_datetime(start=datetime(year=2000,
                                                      month=5,
                                                      day=24,
                                                      tzinfo=pytz.utc),
                                       stop=datetime(year=2017,
                                                     month=1,
                                                     day=1,
                                                     tzinfo=pytz.utc))
        kwargs.update({'start_date': begins})

    if 'end_date' not in kwargs:
        ends = kwargs['start_date'] + timedelta(days=random.uniform(5, 365))
        kwargs.update({'end_date': ends})

    if 'country' not in kwargs:
        kwargs.update({'country': Country.objects.order_by('?').first()})

    if 'radius' not in kwargs:
        kwargs.update({'radius': random.uniform(0.0, 5.0)})

    if 'origin' not in kwargs:

        for random_point in generate_random_points(
                kwargs['country'].geom.extent):
            if kwargs['country'].geom.contains(random_point):
                break

        kwargs.update({'origin': random_point})
        kwargs.update({'zone': random_point.buffer(kwargs['radius'])})

    if 'zone' not in kwargs:
        kwargs.update({'zone': kwargs['origin'].buffer(kwargs['radius'])})

    try:
        new_crisis = Crisis(**kwargs)
        new_crisis.save()
        return new_crisis

    except Exception as ex:

        print "There was a problem creating the crisis object. It was {0}".format(
            ex)
Example #37
0
    def test_05_random_datetime_with_string_ranges_given(self):
        """
        Test ``radar.random_datetime`` with string ranges given.
        """
        start = '2012-05-24T00:00:00'
        stop='2013-05-24T23:59:59'

        dt_start = datetime.datetime(year=2012, month=5, day=24, hour=0, minute=0, second=0)
        dt_stop = datetime.datetime(year=2013, month=5, day=24, hour=23, minute=59, second=59)

        res = radar.random_datetime(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.datetime))
        self.assertTrue(res > dt_start)
        self.assertTrue(res < dt_stop)
        return res
    def handle(self, *args, **options):
        words = WORDS[:]
        images = IMAGE_FACTORY[:]
        url_parts = list(range(0, NUM_ITEMS))

        for index in range(NUM_ITEMS):
            i = FooItem()
            random_name = words[random.randint(0, len(words) - 1)]
            random_image = images[random.randint(0, len(images) - 1)]

            if PY2:
                i.title = unicode(random_name).capitalize()
                i.body = unicode(SENTENCES[random.randint(0, len(SENTENCES) - 1)])
            else:
                i.title = str(random_name).capitalize()
                i.body = str(SENTENCES[random.randint(0, len(SENTENCES) - 1)])

            i.slug = slugify(i.title)
            i.date_published = radar.random_datetime()
            i.image = random_image
            i.alternative_url = 'http://en-us.example.com/%s/' % url_parts.pop(0)

            try:
                i.save()
                words.remove(random_name)
                images.remove(random_image)

                if 0 == len(images):
                    images = IMAGE_FACTORY

                if 0 == len(words):
                    words = WORDS

                if 0 == len(url_parts):
                    url_parts = random.randrange(0, NUM_ITEMS)

            except Exception as e:
                print_(e)
                pass
Example #39
0
def _random_time():
    return radar.random_datetime(
        start = datetime.datetime(year=2013, month=5, day=24),
        stop = datetime.datetime(year=2016, month=3, day=15)
    )
    def generate_data(num_items=NUM_ITEMS):
        create_users()

        class CustomLogEntry(models.Model):
            """Custom log entry."""

            action_time = models.DateTimeField(_('action time'))
            user = models.ForeignKey(settings.AUTH_USER_MODEL,
                                     on_delete=models.CASCADE)
            content_type = models.ForeignKey(ContentType,
                                             blank=True,
                                             null=True,
                                             on_delete=models.CASCADE)
            object_id = models.TextField(_('object id'),
                                         blank=True,
                                         null=True)
            object_repr = models.CharField(_('object repr'), max_length=200)
            action_flag = models.PositiveSmallIntegerField(_('action flag'))
            change_message = models.TextField(_('change message'), blank=True)

            class Meta(object):
                """Class meta."""

                db_table = LogEntry._meta.db_table

        words = WORDS[:]

        users = User.objects.all()[:]

        random_date = radar.random_datetime()

        for index in range(num_items):
            # Saving an item to database
            foo_item_model_cls = MODEL_FACTORY[
                random.randint(0, len(MODEL_FACTORY) - 1)
            ]
            item = foo_item_model_cls()
            random_name = words[random.randint(0, len(words) - 1)]

            item.title = text_type(random_name).capitalize()
            item.body = text_type(
                SENTENCES[random.randint(0, len(SENTENCES) - 1)]
            )

            item.slug = slugify(item.title)
            random_date = radar.random_datetime() \
                if change_date() \
                else random_date
            item.date_published = random_date

            try:
                item.save()
                words.remove(random_name)

                if 0 == len(words):
                    words = WORDS[:]

            except Exception as err:
                logger.debug(err)

            # Create an item with content type
            try:
                # Creating a ``LogEntry`` for the item created.
                log_entry = CustomLogEntry()
                log_entry.action_time = item.date_published
                log_entry.user = users[random.randint(0, len(users) - 1)]
                log_entry.content_type = ContentType._default_manager \
                                                    .get_for_model(
                                                        foo_item_model_cls
                                                    )
                log_entry.object_id = item.pk
                log_entry.object_repr = text_type(item)

                log_entry.action_flag = ADDITION
                log_entry.save()
            except Exception as err:
                logger.debug(err)

            # Create an item without content type
            try:
                # Creating a ``LogEntry`` for the item created.
                log_entry = CustomLogEntry()
                log_entry.action_time = item.date_published
                log_entry.user = users[random.randint(0, len(users) - 1)]
                log_entry.object_repr = text_type(item)

                log_entry.action_flag = ADDITION
                log_entry.save()
            except Exception as err:
                logger.debug(err)
Example #41
0
from __future__ import print_function

from dateutil.parser import parse as dateuitil_parser
import radar

print(radar.random_date(start='2013-05-24', stop='2013-07-01', parse=dateuitil_parser))

print(radar.random_datetime(start='2013-05-24T00:00:00', stop='2013-05-24T23:59:59', parse=radar.utils.parse))

start = radar.utils.parse('2012-01-01')

stop = radar.utils.parse('2013-01-01')

print(radar.random_datetime(start=start, stop=stop))

print(radar.random_datetime(start=start))

print(radar.random_datetime(stop=stop))

print(radar.random_time(start='2012-01-01T00:00:00', stop='2012-01-01T23:59:59'))
Example #42
0
def add_a_datetime():
    start = timezone.datetime(year=2000, month=1, day=1, tzinfo=timezone.utc)
    stop = timezone.datetime(year=2016, month=12, day=31, tzinfo=timezone.utc)
    return radar.random_datetime(start=start, stop=stop)
Example #43
0
    def generate_data(num_items=NUM_ITEMS):
        create_users()

        class CustomLogEntry(models.Model):
            action_time = models.DateTimeField(_('action time'))
            user = models.ForeignKey(User)
            content_type = models.ForeignKey(ContentType, blank=True, null=True)
            object_id = models.TextField(_('object id'), blank=True, null=True)
            object_repr = models.CharField(_('object repr'), max_length=200)
            action_flag = models.PositiveSmallIntegerField(_('action flag'))
            change_message = models.TextField(_('change message'), blank=True)

            class Meta:
                db_table = LogEntry._meta.db_table

        words = WORDS

        users = User.objects.all()[:]

        random_date = radar.random_datetime()

        for index in range(num_items):
            # Saving an item to database
            FooItemModel = MODEL_FACTORY[random.randint(0, len(MODEL_FACTORY) - 1)]
            i = FooItemModel()
            random_name = words[random.randint(0, len(words) - 1)]

            if PY3:
                i.title = str(random_name).capitalize()
                i.body = str(SENTENCES[random.randint(0, len(SENTENCES) - 1)])
            else:
                i.title = unicode(random_name).capitalize()
                i.body = unicode(SENTENCES[random.randint(0, len(SENTENCES) - 1)])

            i.slug = slugify(i.title)
            random_date = radar.random_datetime() if change_date() else random_date
            i.date_published = random_date

            try:
                i.save()
                words.remove(random_name)

                if 0 == len(words):
                    words = WORDS

            except Exception as e:
                print(e)

            try:
                # Creating a ``LogEntry`` for the item created.
                l = CustomLogEntry()
                l.action_time = i.date_published
                l.user = users[random.randint(0, len(users) - 1)]
                l.content_type = ContentType._default_manager.get_for_model(FooItemModel)
                l.object_id = i.pk

                if PY3:
                    l.object_repr = str(i)
                else:
                    l.object_repr = unicode(i)

                l.action_flag = ADDITION
                #l.change_message = CHANGE_MESSAGE_FACTORY[random.randint(0, len(CHANGE_MESSAGE_FACTORY) - 1)]
                l.save()
            except Exception as e:
                print(e)