def test_with_tz(self):
        tz = self.tz("US/Central")

        # just want it to work
        start = datetime(2011, 3, 12, tzinfo=pytz.utc)
        dr = bdate_range(start, periods=50, freq=datetools.Hour())
        self.assertIs(dr.tz, pytz.utc)

        # DateRange with naive datetimes
        dr = bdate_range("1/1/2005", "1/1/2009", tz=pytz.utc)
        dr = bdate_range("1/1/2005", "1/1/2009", tz=tz)

        # normalized
        central = dr.tz_convert(tz)
        self.assertIs(central.tz, tz)
        comp = self.localize(tz, central[0].to_pydatetime().replace(tzinfo=None)).tzinfo
        self.assertIs(central[0].tz, comp)

        # compare vs a localized tz
        comp = self.localize(tz, dr[0].to_pydatetime().replace(tzinfo=None)).tzinfo
        self.assertIs(central[0].tz, comp)

        # datetimes with tzinfo set
        dr = bdate_range(datetime(2005, 1, 1, tzinfo=pytz.utc), "1/1/2009", tz=pytz.utc)

        self.assertRaises(Exception, bdate_range, datetime(2005, 1, 1, tzinfo=pytz.utc), "1/1/2009", tz=tz)
    def test_full_hydrate(self):
        basic = BasicRepresentation()

        # Sanity check.
        self.assertEqual(basic.name.value, None)
        self.assertEqual(basic.view_count.value, None)
        self.assertEqual(basic.date_joined.value, None)

        basic = BasicRepresentation(
            data={"name": "Daniel", "view_count": 6, "date_joined": datetime.datetime(2010, 2, 15, 12, 0, 0)}
        )

        # Sanity check.
        self.assertEqual(basic.name.value, "Daniel")
        self.assertEqual(basic.view_count.value, 6)
        self.assertEqual(basic.date_joined.value, datetime.datetime(2010, 2, 15, 12, 0, 0))
        self.assertEqual(basic.instance, None)

        # Now load up the data.
        basic.full_hydrate()

        self.assertEqual(basic.name.value, "Daniel")
        self.assertEqual(basic.view_count.value, 6)
        self.assertEqual(basic.date_joined.value, datetime.datetime(2010, 2, 15, 12, 0, 0))
        self.assertEqual(basic.instance.name, "Daniel")
        self.assertEqual(basic.instance.view_count, 6)
        self.assertEqual(basic.instance.date_joined, datetime.datetime(2010, 2, 15, 12, 0, 0))
Example #3
1
    def testFiltering(self):
        result = ols(y=self.panel_y2, x=self.panel_x2)

        x = result._x
        index = x.index.get_level_values(0)
        index = Index(sorted(set(index)))
        exp_index = Index([datetime(2000, 1, 1), datetime(2000, 1, 3)])
        self.assertTrue
        (exp_index.equals(index))

        index = x.index.get_level_values(1)
        index = Index(sorted(set(index)))
        exp_index = Index(["A", "B"])
        self.assertTrue(exp_index.equals(index))

        x = result._x_filtered
        index = x.index.get_level_values(0)
        index = Index(sorted(set(index)))
        exp_index = Index([datetime(2000, 1, 1), datetime(2000, 1, 3), datetime(2000, 1, 4)])
        self.assertTrue(exp_index.equals(index))

        assert_almost_equal(result._y.values.flat, [1, 4, 5])

        exp_x = [[6, 14, 1], [9, 17, 1], [30, 48, 1]]
        assert_almost_equal(exp_x, result._x.values)

        exp_x_filtered = [[6, 14, 1], [9, 17, 1], [30, 48, 1], [11, 20, 1], [12, 21, 1]]
        assert_almost_equal(exp_x_filtered, result._x_filtered.values)

        self.assertTrue(result._x_filtered.index.levels[0].equals(result.y_fitted.index))
Example #4
1
    def setUp(self, env=None):
        self.extra_knowledge_date = datetime(2015, 1, 27, 0, 0, tzinfo=pytz.utc)
        self.trading_day_before_first_kd = datetime(2015, 1, 23, 0, 0, tzinfo=pytz.utc)

        env.update_asset_finder(clear_metadata=True, identifiers=["BZQ", "URTY", "JFT", "AAPL", "GOOG"])

        setup_logger(self)
    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)

        # Attempt to parse a datetime:
        value = smart_str(value)
        # split usecs, because they are not recognized by strptime.
        if "." in value:
            try:
                value, usecs = value.split(".")
                usecs = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(_("Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."))
        else:
            usecs = 0
        kwargs = {"microsecond": usecs}
        try:  # Seconds are optional, so try converting seconds first.
            return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6], **kwargs)

        except ValueError:
            try:  # Try without seconds.
                return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M")[:5], **kwargs)
            except ValueError:  # Try without hour/minutes/seconds.
                try:
                    return datetime.datetime(*time.strptime(value, "%Y-%m-%d")[:3], **kwargs)
                except ValueError:
                    raise exceptions.ValidationError(
                        _("Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.")
                    )
def main():
    dir = "/mfs/backup/mysql/"
    pattern = os.path.join(dir, "*/snapshots/*")
    # pattern = os.path.join(dir, '*/binlogs/*')
    # pattern = os.path.join('/mfs/user/dba/recovery/*')

    total_size = 0
    for i in glob.glob(pattern):
        info = os.stat(i)
        t1 = time.gmtime(info.st_ctime)
        t2 = time.strftime("%Y-%m-%d", t1)
        year, month, day = t2.split("-")
        time1 = datetime.datetime(int(year), int(month), int(day))

        m1 = time.gmtime()
        m2 = time.strftime("%Y-%m-%d", m1)
        year, month, day = m2.split("-")
        time2 = datetime.datetime(int(year), int(month), int(day))

        days = (time2 - time1).days
        # print  time1, time2, days

        if days > 20:
            total_size = total_size + get_directory_size(i) / 1024 ** 3
            print i, time1, total_size
            try:
                pass
                shutil.rmtree(i)
                # os.remove(i)
            except Exception as exc:
                print i, exc
    def setUp(self):
        self.portal = self.layer["portal"]
        setRoles(self.portal, TEST_USER_ID, ["Manager"])
        self.portal.invokeFactory(id="doc1", Title="Document 1", type_name="Document")
        self.catalog = getToolByName(self.portal, "portal_catalog")
        conversation = IConversation(self.portal.doc1)
        comment1 = createObject("plone.Comment")
        comment1.title = "Comment 1"
        comment1.text = "Comment text"
        comment1.creator = "jim"
        comment1.author_username = "Jim"
        comment1.creation_date = datetime(2006, 9, 17, 14, 18, 12)
        comment1.modification_date = datetime(2006, 9, 17, 14, 18, 12)

        new_comment1_id = conversation.addComment(comment1)
        self.comment_id = new_comment1_id

        brains = self.catalog.searchResults(
            dict(path={"query": "/".join(self.portal.doc1.getPhysicalPath())}, portal_type="Document")
        )
        self.conversation = conversation
        self.brains = brains
        self.doc1_brain = brains[0]
        self.comment1 = comment1
        self.new_comment1_id = new_comment1_id
Example #8
0
    def testNoYearFirstNoDayFirst(self):
        dtstr = "090107"

        # Should be MMDDYY
        self.assertEqual(parse(dtstr), datetime(2007, 9, 1))

        self.assertEqual(parse(dtstr, yearfirst=False, dayfirst=False), datetime(2007, 9, 1))
Example #9
0
    def testYearFirst(self):
        dtstr = "090107"

        # Should be MMDDYY
        self.assertEqual(parse(dtstr, yearfirst=True), datetime(2009, 1, 7))

        self.assertEqual(parse(dtstr, yearfirst=True, dayfirst=False), datetime(2009, 1, 7))
Example #10
0
def _get_datetime(year, month):
    ts = None
    if year and not month:
        ts = datetime(int(year), 1, 1)
    elif year and month:
        ts = datetime(int(year), int(month), 1)
    return ts
Example #11
0
    def time_set(self, args):
        now = datetime.datetime.now()
        year = now.year
        month = now.month
        day = now.day

        if args[1] == "msg":
            if len(args) > 2:
                self.data.msg = " ".join(args[2:])
                self.write_JSON()
        elif args[1] == "target":
            if len(args) == 5:
                day = int(args[2])
                hour = int(args[3])
                minute = int(args[4])

                self.data.target = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute)
                self.write_JSON()
                self.bot.send_message("Ajan rakenne muutettu.")
            if len(args) == 4:
                hour = int(args[2])
                minute = int(args[3])

                self.data.target = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute)
                self.write_JSON()
                self.bot.send_message("Minuutin rakenne muutettu.")
            elif len(args) == 3:
                hour = int(args[2])

                self.data.target = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=0)
                self.write_JSON()
                self.bot.send_message("Tunnin rakenne muutettu.")
Example #12
0
 def test_get_by_network(self, get):
     info = {
         "address": "1.2.3.4",
         "instance_uuid": "fake-uuid",
         "network_id": 0,
         "vif_id": 1,
         "vif_address": "de:ad:be:ee:f0:00",
         "instance_hostname": "fake-host",
         "instance_updated": datetime.datetime(1955, 11, 5),
         "instance_created": datetime.datetime(1955, 11, 5),
         "allocated": True,
         "leased": True,
         "default_route": True,
     }
     get.return_value = [info]
     fixed_ips = fixed_ip.FixedIPList.get_by_network(self.context, {"id": 0}, host="fake-host")
     get.assert_called_once_with(self.context, 0, host="fake-host")
     self.assertEqual(1, len(fixed_ips))
     fip = fixed_ips[0]
     self.assertEqual("1.2.3.4", str(fip.address))
     self.assertEqual("fake-uuid", fip.instance_uuid)
     self.assertEqual(0, fip.network_id)
     self.assertEqual(1, fip.virtual_interface_id)
     self.assertTrue(fip.allocated)
     self.assertTrue(fip.leased)
     self.assertEqual("fake-uuid", fip.instance.uuid)
     self.assertEqual("fake-host", fip.instance.hostname)
     self.assertIsInstance(fip.instance.created_at, datetime.datetime)
     self.assertIsInstance(fip.instance.updated_at, datetime.datetime)
     self.assertEqual(1, fip.virtual_interface.id)
     self.assertEqual(info["vif_address"], fip.virtual_interface.address)
Example #13
0
def entry_bodyfile(entry, filename=False):
    if filename:
        fn = filename
    else:
        fn = entry.filename()

    try:
        modified = int(time.mktime(entry.modified_time_safe().timetuple()))
    except ValueError:
        modified = int(time.mktime(datetime(1970, 1, 1, 0, 0, 0).timetuple()))

    try:
        accessed = int(time.mktime(entry.accessed_time_safe().timetuple()))
    except ValueError:
        accessed = int(time.mktime(datetime(1970, 1, 1, 0, 0, 0).timetuple()))

    try:
        changed = int(time.mktime(entry.changed_time_safe().timetuple()))
    except ValueError:
        changed = int(time.mktime(datetime(1970, 1, 1, 0, 0, 0).timetuple()))

    try:
        created = int(time.mktime(entry.created_time_safe().timetuple()))
    except ValueError:
        created = int(time.mktime(datetime.min.timetuple()))

    return u"0|%s|0|0|0|0|%s|%s|%s|%s|%s" % (fn, entry.logical_size(), accessed, modified, changed, created)
Example #14
0
def get_bounds(dt, interval):
    """ Returns interval bounds the datetime is in. """

    day = _to_datetime(_to_date(dt))
    dt = _to_datetime(dt)

    if interval == "minute":
        begin = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute)
        end = begin + relativedelta(minutes=1)
    elif interval == "hour":
        begin = datetime.datetime(dt.year, dt.month, dt.day, dt.hour)
        end = begin + relativedelta(hours=1)
    elif interval == "day":
        begin = day
        end = day + relativedelta(days=1)
    elif interval == "week":
        begin = day - relativedelta(weekday=MO(-1))
        end = begin + datetime.timedelta(days=7)
    elif interval == "month":
        begin = datetime.datetime(dt.year, dt.month, 1)
        end = begin + relativedelta(months=1)
    elif interval == "year":
        begin = datetime.datetime(dt.year, 1, 1)
        end = datetime.datetime(dt.year + 1, 1, 1)
    else:
        raise InvalidInterval("Inverval not supported.")
    end = end - relativedelta(microseconds=1)
    return begin, end
Example #15
0
    def __init__(self, preRange=7, Data=None):
        # Define the data structure properly
        # Income: Dictionary --> The time and amount
        # Transactions: A predified row based data; keep the number of column to 4: Grocery | Entertain | Other | Schedule
        # Prediction Strategy:
        """
                Prediction Strategy:

                1. The prediction class will be called when the use wants to do prediction
                2. Also, the prediction function will also be called when there is new data added. ( Optional )

                INPUT DATA FORMAT

                X --> Number of days \\times Number of Catogories ( A formulation function can be written for this)
                
                preRange --> Set how many days the user wanted to predict. 

                (optionals):
                    We should probably set up a possible confidence settings.
        """
        self.categoryClass = {"Grocery": 0, "Entertain": 1, "Other": 2, "Schedule": 3}
        self.mean_X = None
        self.std_X = None
        if Data is None:
            self.X = self.acquireData(start=datetime(2010, 1, 1), end=datetime(2011, 12, 31))
        else:
            self.X = Data
        self.preRange = preRange
        self.predict = np.zeros((self.preRange, self.X.shape[1]))
        self.predictAll = np.zeros((self.preRange, 1))
Example #16
0
    def testDayFirst(self):
        dtstr = "090107"

        # Should be DDMMYY
        self.assertEqual(parse(dtstr, dayfirst=True), datetime(2007, 1, 9))

        self.assertEqual(parse(dtstr, yearfirst=False, dayfirst=True), datetime(2007, 1, 9))
Example #17
0
def get_date(year=None, month=None, pivot=config.FIRST_DAY):
    now = datetime.datetime.utcnow()
    year = year or now.year
    month = month or now.month

    has_next = int("%04d%02d" % (year, month)) < int("%04d%02d" % (now.year, now.month))

    previous_month, previous_year = (month - 1, year) if not month == 1 else (12, year - 1)
    next_month, next_year = (month + 1, year) if not month == 12 else (1, year + 1)

    start_month, start_year = (month, year) if now.day >= pivot else (previous_month, previous_year)
    if pivot == config.FIRST_DAY:
        end_month, end_year = start_month, start_year
    else:
        end_month, end_year = (start_month + 1, start_year) if not start_month == 12 else (1, start_year + 1)

    start = datetime.datetime(year=start_year, month=start_month, day=pivot)
    end = datetime.datetime(year=end_year, month=end_month, day=pivot)

    start_t = calendar.timegm(start.utctimetuple())
    end_t = calendar.timegm(end.utctimetuple())

    target = datetime.datetime(year=end_year, month=end_month, day=1)
    target = target.strftime("%B %Y")

    return (target, month, year, start_t, end_t, previous_month, previous_year, next_month, next_year, has_next)
Example #18
0
    def testResampleNinjaTraderHour(self):
        # Resample.
        feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE)
        feed.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(feed["spy"], bar.Frequency.HOUR)
        resampledFile = os.path.join(common.get_temp_path(), "hour-nt-spy-minute-2011.csv")
        resample.resample_to_csv(feed, bar.Frequency.HOUR, resampledFile)
        resampledBarDS.pushLast()  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(bar.Frequency.HOUR, marketsession.USEquities.getTimezone())
        feed.addBarsFromCSV("spy", resampledFile)
        feed.loadAll()

        self.assertEqual(len(feed["spy"]), 340)
        self.assertEqual(
            feed["spy"][0].getDateTime(),
            dt.localize(datetime.datetime(2011, 1, 3, 9), marketsession.USEquities.getTimezone()),
        )
        self.assertEqual(
            feed["spy"][-1].getDateTime(),
            dt.localize(datetime.datetime(2011, 2, 1, 1), marketsession.USEquities.getTimezone()),
        )
        self.assertEqual(feed["spy"][0].getOpen(), 126.35)
        self.assertEqual(feed["spy"][0].getHigh(), 126.45)
        self.assertEqual(feed["spy"][0].getLow(), 126.3)
        self.assertEqual(feed["spy"][0].getClose(), 126.4)
        self.assertEqual(feed["spy"][0].getVolume(), 3397.0)
        self.assertEqual(feed["spy"][0].getAdjClose(), None)

        self.assertEqual(len(resampledBarDS), len(feed["spy"]))
        self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(datetime.datetime(2011, 1, 3, 9)))
        self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(datetime.datetime(2011, 2, 1, 1)))
Example #19
0
def blog_month(request, blog_slug, year, month, page_no=1, blog_root=None):

    page_no = int(page_no)

    year = int(year)
    month = int(month)

    blog = get_channel_or_blog(blog_slug)
    blog_root = blog_root or blog.get_absolute_url()

    try:
        start_date = datetime(year, month, 1)
        year_end = year
        next_month = month + 1
        if next_month == 13:
            next_month = 1
            year_end += 1
        end_date = datetime(year_end, next_month, 1)
    except ValueError:
        raise Http404

    title = blog.title

    posts = blog.posts().filter(display_time__gte=start_date, display_time__lt=end_date).select_related()

    if not posts.count():
        raise Http404

    archives = tools.collate_archives(blog, blog_root)

    def get_page_url(page_no, num_pages):
        if page_no < 1 or page_no > num_pages:
            return ""
        if page_no == 1:
            return "%s%i/%i/" % (blog_root, year, month)
            # return reverse("blog_month", kwargs = dict(blog_slug=blog_slug, year=year, month=month, blog_root=blog_root))
        else:
            return "%s%i/%i/page/%i/" % (blog_root, year, month, page_no)

    td = get_blog_list_data(request, posts, get_page_url, page_no)

    sections = blog.description_data.get("sections", None)

    td.update(
        dict(
            blog_root=blog_root,
            blog=blog,
            sections=sections,
            title=title,
            page_title=title,
            tagline=blog.tagline,
            archives=archives,
            archive_month=month,
            archive_year=year,
        )
    )

    sections = extendedmarkup.process(sections, td)

    return render_to_response(blog.get_template_names("month.html"), td, context_instance=RequestContext(request))
Example #20
0
    def testResampleNinjaTraderDay(self):
        # Resample.
        feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE)
        feed.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(feed["spy"], bar.Frequency.DAY)
        resampledFile = os.path.join(common.get_temp_path(), "day-nt-spy-minute-2011.csv")
        resample.resample_to_csv(feed, bar.Frequency.DAY, resampledFile)
        resampledBarDS.pushLast()  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
        feed.addBarsFromCSV("spy", resampledFile, marketsession.USEquities.getTimezone())
        feed.loadAll()

        self.assertEqual(len(feed["spy"]), 25)
        self.assertEqual(
            feed["spy"][0].getDateTime(),
            dt.localize(datetime.datetime(2011, 1, 3), marketsession.USEquities.getTimezone()),
        )
        self.assertEqual(
            feed["spy"][-1].getDateTime(),
            dt.localize(datetime.datetime(2011, 2, 1), marketsession.USEquities.getTimezone()),
        )

        self.assertEqual(len(resampledBarDS), len(feed["spy"]))
        self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(datetime.datetime(2011, 1, 3)))
        self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(datetime.datetime(2011, 2, 1)))
Example #21
0
        def instance_create(context, inst):
            inst_type = flavors.get_flavor_by_flavor_id(3)
            image_uuid = "76fa36fc-c930-4bf3-8c8a-ea2a2420deb6"
            def_image_ref = "http://localhost/images/%s" % image_uuid
            self.instance_cache_num += 1
            instance = fake_instance.fake_db_instance(
                **{
                    "id": self.instance_cache_num,
                    "display_name": inst["display_name"] or "test",
                    "uuid": fakes.FAKE_UUID,
                    "instance_type": inst_type,
                    "access_ip_v4": "1.2.3.4",
                    "access_ip_v6": "fead::1234",
                    "image_ref": inst.get("image_ref", def_image_ref),
                    "user_id": "fake",
                    "project_id": "fake",
                    "reservation_id": inst["reservation_id"],
                    "created_at": datetime.datetime(2010, 10, 10, 12, 0, 0),
                    "updated_at": datetime.datetime(2010, 11, 11, 11, 0, 0),
                    "progress": 0,
                    "fixed_ips": [],
                    "task_state": "",
                    "vm_state": "",
                    "root_device_name": inst.get("root_device_name", "vda"),
                }
            )

            return instance
Example #22
0
    def testResample(self):
        barDs = bards.BarDataSeries()
        resampledBarDS = resampled.ResampledBarDataSeries(barDs, bar.Frequency.MINUTE)

        barDs.append(bar.BasicBar(datetime.datetime(2011, 1, 1, 1, 1, 1), 2.1, 3, 1, 2, 10, 1, bar.Frequency.SECOND))
        barDs.append(bar.BasicBar(datetime.datetime(2011, 1, 1, 1, 1, 2), 2, 3, 1, 2.3, 10, 2, bar.Frequency.SECOND))
        barDs.append(bar.BasicBar(datetime.datetime(2011, 1, 1, 1, 2, 1), 2, 3, 1, 2, 10, 2, bar.Frequency.SECOND))

        self.assertEqual(len(resampledBarDS), 1)
        self.assertEqual(resampledBarDS[0].getDateTime(), datetime.datetime(2011, 1, 1, 1, 1))
        self.assertEqual(resampledBarDS[0].getOpen(), 2.1)
        self.assertEqual(resampledBarDS[0].getHigh(), 3)
        self.assertEqual(resampledBarDS[0].getLow(), 1)
        self.assertEqual(resampledBarDS[0].getClose(), 2.3)
        self.assertEqual(resampledBarDS[0].getVolume(), 20)
        self.assertEqual(resampledBarDS[0].getAdjClose(), 2)

        resampledBarDS.pushLast()
        self.assertEqual(len(resampledBarDS), 2)
        self.assertEqual(resampledBarDS[1].getDateTime(), datetime.datetime(2011, 1, 1, 1, 2))
        self.assertEqual(resampledBarDS[1].getOpen(), 2)
        self.assertEqual(resampledBarDS[1].getHigh(), 3)
        self.assertEqual(resampledBarDS[1].getLow(), 1)
        self.assertEqual(resampledBarDS[1].getClose(), 2)
        self.assertEqual(resampledBarDS[1].getVolume(), 10)
        self.assertEqual(resampledBarDS[1].getAdjClose(), 2)
Example #23
0
    def events(self, uuid):
        user = self.get_user_data(cherrypy.config["google.calendar.ownerid"], True)
        http = user["credentials"].authorize(httplib2.Http())
        calendar_service = build("calendar", "v3", http=http)
        now = datetime.datetime.now()
        events = (
            calendar_service.events()
            .list(
                **{
                    "calendarId": cherrypy.config["google.calendar.id"],
                    "timeMin": datetime.datetime(now.year, now.month, now.day).isoformat() + ".0z",
                    "timeMax": datetime.datetime(now.year, now.month, now.day, 23, 59, 59).isoformat() + ".0z",
                    "singleEvents": True,
                    "orderBy": "startTime",
                }
            )
            .execute()
        )

        items = events["items"]

        c = cherrypy.thread_data.db.cursor()
        c.execute('select * from device where uuid="%s"' % uuid)
        device = c.fetchone()
        if device:
            items = [
                i
                for i in items
                if i.get("location") == device[1]
                and dateutil.parser.parse(i["end"]["dateTime"]).replace(tzinfo=None) > now.replace(tzinfo=None)
            ]

        return json.dumps(items)
    def test_september_1752(self):
        "Assure September 3 - 13, 1752 exist."
        # September 5, 1752 is a Sunday
        # Weeks
        dlong = -11330L
        assert_equal(p.long_to_datetime(dlong, "W"), d.datetime(1752, 11, 5))
        dlong = -11329L
        assert_equal(p.long_to_datetime(dlong, "W"), d.datetime(1752, 11, 12))

        # Days
        dlong = -79316L
        assert_equal(p.long_to_datetime(dlong, "D"), d.datetime(1752, 11, 3))
        dlong = -79315L
        assert_equal(p.long_to_datetime(dlong, "D"), d.datetime(1752, 11, 4))
        dlong = -79309L
        assert_equal(p.long_to_datetime(dlong, "D"), d.datetime(1752, 11, 10))
        dlong = -79308L
        assert_equal(p.long_to_datetime(dlong, "D"), d.datetime(1752, 11, 11))
        dlong = -79306L
        assert_equal(p.long_to_datetime(dlong, "D"), d.datetime(1752, 11, 13))

        # Business Days
        dlong = -56654L
        assert_equal(p.long_to_datetime(dlong, "B"), d.datetime(1752, 11, 3))
        dlong = -56653L
        assert_equal(p.long_to_datetime(dlong, "B"), d.datetime(1752, 11, 6))
        dlong = -56648L
        assert_equal(p.long_to_datetime(dlong, "B"), d.datetime(1752, 11, 13))
 def test_time_ordering_preserved(self):
     # Passing a subunit stream through TestResultFilter preserves the
     # relative ordering of 'time' directives and any other subunit
     # directives that are still included.
     date_a = datetime(year=2000, month=1, day=1, tzinfo=iso8601.UTC)
     date_b = datetime(year=2000, month=1, day=2, tzinfo=iso8601.UTC)
     date_c = datetime(year=2000, month=1, day=3, tzinfo=iso8601.UTC)
     subunit_stream = _b(
         "\n".join(["time: %s", "test: foo", "time: %s", "error: foo", "time: %s", ""]) % (date_a, date_b, date_c)
     )
     result = ExtendedTestResult()
     result_filter = TestResultFilter(result)
     self.run_tests(result_filter, subunit_stream)
     foo = subunit.RemotedTestCase("foo")
     self.maxDiff = None
     self.assertEqual(
         [
             ("time", date_a),
             ("time", date_b),
             ("startTest", foo),
             ("addError", foo, {}),
             ("stopTest", foo),
             ("time", date_c),
         ],
         result._events,
     )
Example #26
0
    def _test_usage_cinder(self, cinder_enabled):
        now = timezone.now()
        usage_obj = api.nova.NovaUsage(self.usages.first())
        self.mox.StubOutWithMock(api.base, "is_service_enabled")
        self._stub_nova_api_calls(True)
        api.nova.extension_supported("SimpleTenantUsage", IsA(http.HttpRequest)).AndReturn(True)

        start = datetime.datetime(now.year, now.month, 1, 0, 0, 0, 0)
        end = datetime.datetime(now.year, now.month, now.day, 23, 59, 59, 0)
        api.nova.usage_get(IsA(http.HttpRequest), self.tenant.id, start, end).AndReturn(usage_obj)
        api.nova.tenant_absolute_limits(IsA(http.HttpRequest)).AndReturn(self.limits["absolute"])

        if cinder_enabled:
            self._stub_cinder_api_calls()

        api.base.is_service_enabled(IsA(http.HttpRequest), "network").MultipleTimes().AndReturn(False)
        api.base.is_service_enabled(IsA(http.HttpRequest), "volume").MultipleTimes().AndReturn(cinder_enabled)
        self.mox.ReplayAll()

        res = self.client.get(reverse("horizon:project:overview:index"))
        usages = res.context["usage"]
        self.assertTemplateUsed(res, "project/overview/usage.html")
        self.assertTrue(isinstance(usages, usage.ProjectUsage))
        if cinder_enabled:
            self.assertEqual(usages.limits["totalVolumesUsed"], 1)
            self.assertEqual(usages.limits["maxTotalVolumes"], 10)
            self.assertEqual(usages.limits["totalGigabytesUsed"], 5)
            self.assertEqual(usages.limits["maxTotalVolumeGigabytes"], 1000)
        else:
            self.assertNotIn("totalVolumesUsed", usages.limits)
    def test_get(self):
        note = NoteRepresentation()
        note.get(pk=1)
        self.assertEqual(note.content.value, u"This is my very first post using my shiny new API. Pretty sweet, huh?")
        self.assertEqual(note.created.value, datetime.datetime(2010, 3, 30, 20, 5))
        self.assertEqual(note.is_active.value, True)
        self.assertEqual(note.slug.value, u"first-post")
        self.assertEqual(note.title.value, u"First Post!")
        self.assertEqual(note.updated.value, datetime.datetime(2010, 3, 30, 20, 5))

        custom = CustomNoteRepresentation()
        custom.get(pk=1)
        self.assertEqual(custom.content.value, u"This is my very first post using my shiny new API. Pretty sweet, huh?")
        self.assertEqual(custom.created.value, datetime.datetime(2010, 3, 30, 20, 5))
        self.assertEqual(custom.is_active.value, True)
        self.assertEqual(custom.author.value, u"johndoe")
        self.assertEqual(custom.title.value, u"First Post!")
        self.assertEqual(custom.constant.value, 20)

        related = RelatedNoteRepresentation(api_name="v1", resource_name="notes")
        related.get(pk=1)
        self.assertEqual(
            related.content.value, u"This is my very first post using my shiny new API. Pretty sweet, huh?"
        )
        self.assertEqual(related.created.value, datetime.datetime(2010, 3, 30, 20, 5))
        self.assertEqual(related.is_active.value, True)
        self.assertEqual(related.author.value, "/api/v1/users/1/")
        self.assertEqual(related.title.value, u"First Post!")
        self.assertEqual(related.subjects.value, ["/api/v1/subjects/1/", "/api/v1/subjects/2/"])
Example #28
0
    def _test_usage_nova_network(self, nova_stu_enabled):
        now = timezone.now()
        usage_obj = api.nova.NovaUsage(self.usages.first())
        self.mox.StubOutWithMock(api.base, "is_service_enabled")
        self._stub_nova_api_calls(nova_stu_enabled)
        api.nova.extension_supported("SimpleTenantUsage", IsA(http.HttpRequest)).AndReturn(nova_stu_enabled)
        if nova_stu_enabled:
            api.nova.usage_get(
                IsA(http.HttpRequest),
                self.tenant.id,
                datetime.datetime(now.year, now.month, 1, 0, 0, 0, 0),
                datetime.datetime(now.year, now.month, now.day, 23, 59, 59, 0),
            ).AndReturn(usage_obj)
        api.nova.tenant_absolute_limits(IsA(http.HttpRequest)).AndReturn(self.limits["absolute"])
        api.base.is_service_enabled(IsA(http.HttpRequest), "network").MultipleTimes().AndReturn(False)
        api.base.is_service_enabled(IsA(http.HttpRequest), "volume").MultipleTimes().AndReturn(False)

        self.mox.ReplayAll()

        res = self.client.get(reverse("horizon:project:overview:index"))
        usages = res.context["usage"]
        self.assertTemplateUsed(res, "project/overview/usage.html")
        self.assertTrue(isinstance(usages, usage.ProjectUsage))
        self.assertEqual(nova_stu_enabled, res.context["simple_tenant_usage_enabled"])
        if nova_stu_enabled:
            self.assertContains(res, "form-inline")
        else:
            self.assertNotContains(res, "form-inline")
        self.assertEqual(usages.limits["maxTotalFloatingIps"], 10)
Example #29
0
 def _date_validate(self, date_str):
     # try this as a iso8601 date format, aka, 2012-12-25
     try:
         date = datetime.datetime(*(time.strptime(date_str, "%Y-%m-%d")[0:6]))
         self._date = datetime.datetime(date.year, date.month, date.day, tzinfo=tzlocal())
     except ValueError:
         raise
Example #30
0
    def test_user(self):
        condition_set = "gargoyle.builtins.UserConditionSet(auth.user)"

        # we need a better API for this (model dict isnt cutting it)
        switch = Switch.objects.create(key="test", status=SELECTIVE)
        switch = self.gargoyle["test"]

        switch.add_condition(condition_set=condition_set, field_name="percent", condition="0-50")

        user = User(pk=5)
        self.assertTrue(self.gargoyle.is_active("test", user))

        user = User(pk=8771)
        self.assertFalse(self.gargoyle.is_active("test", user))

        switch.add_condition(condition_set=condition_set, field_name="is_staff", condition="1")

        user = User(pk=8771, is_staff=True)
        self.assertTrue(self.gargoyle.is_active("test", user))

        user = User(pk=8771, is_superuser=True)
        self.assertFalse(self.gargoyle.is_active("test", user))

        switch.add_condition(condition_set=condition_set, field_name="is_superuser", condition="1")

        user = User(pk=8771, is_superuser=True)
        self.assertTrue(self.gargoyle.is_active("test", user))

        # test with mock request
        self.assertTrue(self.gargoyle.is_active("test", self.gargoyle.as_request(user=user)))

        # test date joined condition
        user = User(pk=8771)
        self.assertFalse(self.gargoyle.is_active("test", user))

        switch.add_condition(condition_set=condition_set, field_name="date_joined", condition="2011-07-01")

        user = User(pk=8771, date_joined=datetime.datetime(2011, 07, 02))
        self.assertTrue(self.gargoyle.is_active("test", user))

        user = User(pk=8771, date_joined=datetime.datetime(2012, 07, 02))
        self.assertTrue(self.gargoyle.is_active("test", user))

        user = User(pk=8771, date_joined=datetime.datetime(2011, 06, 02))
        self.assertFalse(self.gargoyle.is_active("test", user))

        user = User(pk=8771, date_joined=datetime.datetime(2011, 07, 01))
        self.assertTrue(self.gargoyle.is_active("test", user))

        switch.clear_conditions(condition_set=condition_set)
        switch.add_condition(condition_set=condition_set, field_name="email", condition="bob@example.com")

        user = User(pk=8771, email="bob@example.com")
        self.assertTrue(self.gargoyle.is_active("test", user))

        user = User(pk=8771, email="bob2@example.com")
        self.assertFalse(self.gargoyle.is_active("test", user))

        user = User(pk=8771)
        self.assertFalse(self.gargoyle.is_active("test", user))