text:
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

from openerp.addons.resource.tests.common import TestResourceCommon

class TestResource(TestResourceCommon):

    def test_00_intervals(self):
        intervals = [
            (
                datetime.strptime('2013-02-04 09:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-04 11:00:00', '%Y-%m-%d %H:%M:%S')
            ), (
                datetime.strptime('2013-02-04 08:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-04 12:00:00', '%Y-%m-%d %H:%M:%S')
            ), (
                datetime.strptime('2013-02-04 11:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-04 14:00:00', '%Y-%m-%d %H:%M:%S')
            ), (
                datetime.strptime('2013-02-04 17:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-04 21:00:00', '%Y-%m-%d %H:%M:%S')
            ), (
                datetime.strptime('2013-02-03 08:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-03 10:00:00', '%Y-%m-%d %H:%M:%S')
            ), (
                datetime.strptime('2013-02-04 18:00:00', '%Y-%m-%d %H:%M:%S'),
                datetime.strptime('2013-02-04 19:00:00', '%Y-%m-%d %H:%M:%S')
            )
        ]

        # Test: interval cleaning
        cleaned_intervals = self.resource_calendar.interval_clean(intervals)
        self.assertEqual(len(cleaned_intervals), 3, 'resource_calendar: wrong interval cleaning')
        # First interval: 03, unchanged
        self.assertEqual(cleaned_intervals[0][0], datetime.strptime('2013-02-03 08:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')
        self.assertEqual(cleaned_intervals[0][1], datetime.strptime('2013-02-03 10:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')
        # Second intreval: 04, 08-14, combining 08-12 and 11-14, 09-11 being inside 08-12
        self.assertEqual(cleaned_intervals[1][0], datetime.strptime('2013-02-04 08:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')
        self.assertEqual(cleaned_intervals[1][1], datetime.strptime('2013-02-04 14:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')
        # Third interval: 04, 17-21, 18-19 being inside 17-21
        self.assertEqual(cleaned_intervals[2][0], datetime.strptime('2013-02-04 17:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')
        self.assertEqual(cleaned_intervals[2][1], datetime.strptime('2013-02-04 21:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong interval cleaning')

        # Test: disjoint removal
        working_interval = (datetime.strptime('2013-02-04 08:00:00', '%Y-%m-%d %H:%M:%S'), datetime.strptime('2013-02-04 18:00:00', '%Y-%m-%d %H:%M:%S'))
        result = self.resource_calendar.interval_remove_leaves(working_interval, intervals)
        self.assertEqual(len(result), 1, 'resource_calendar: wrong leave removal from interval')
        # First interval: 04, 14-17
        self.assertEqual(result[0][0], datetime.strptime('2013-02-04 14:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        self.assertEqual(result[0][1], datetime.strptime('2013-02-04 17:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')

        # Test: schedule hours on intervals
        result = self.resource_calendar.interval_schedule_hours(cleaned_intervals, 5.5)
        self.assertEqual(len(result), 2, 'resource_calendar: wrong hours scheduling in interval')
        # First interval: 03, 8-10 untouches
        self.assertEqual(result[0][0], datetime.strptime('2013-02-03 08:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        self.assertEqual(result[0][1], datetime.strptime('2013-02-03 10:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        # First interval: 04, 08-11:30
        self.assertEqual(result[1][0], datetime.strptime('2013-02-04 08:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        self.assertEqual(result[1][1], datetime.strptime('2013-02-04 11:30:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')

        # Test: schedule hours on intervals, backwards
        cleaned_intervals.reverse()
        result = self.resource_calendar.interval_schedule_hours(cleaned_intervals, 5.5, remove_at_end=False)
        self.assertEqual(len(result), 2, 'resource_calendar: wrong hours scheduling in interval')
        # First interval: 03, 8-10 untouches
        self.assertEqual(result[0][0], datetime.strptime('2013-02-04 17:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        self.assertEqual(result[0][1], datetime.strptime('2013-02-04 21:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        # First interval: 04, 08-11:30
        self.assertEqual(result[1][0], datetime.strptime('2013-02-04 12:30:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')
        self.assertEqual(result[1][1], datetime.strptime('2013-02-04 14:00:00', '%Y-%m-%d %H:%M:%S'), 'resource_calendar: wrong leave removal from interval')

    def test_10_calendar_basics(self):
        """ Testing basic method of resource.calendar """
        cr, uid = self.cr, self.uid

        # --------------------------------------------------
        # Test1: get_next_day
        # --------------------------------------------------

        # Test: next day: next day after day1 is day4
        date = self.resource_calendar.get_next_day(cr, uid, self.calendar_id, day_date=self.date1.date())
        self.assertEqual(date, self.date2.date(), 'resource_calendar: wrong next day computing')

        # Test: next day: next day after day4 is (day1+7)
        date = self.resource_calendar.get_next_day(cr, uid, self.calendar_id, day_date=self.date2.date())
        self.assertEqual(date, self.date1.date() + relativedelta(days=7), 'resource_calendar: wrong next day computing')

        # Test: next day: next day after day4+1 is (day1+7)
        date = self.resource_calendar.get_next_day(cr, uid, self.calendar_id, day_date=self.date2.date() + relativedelta(days=1))
        self.assertEqual(date, self.date1.date() + relativedelta(days=7), 'resource_calendar: wrong next day computing')

        # Test: next day: next day after day1-1 is day1
        date = self.resource_calendar.get_next_day(cr, uid, self.calendar_id, day_date=self.date1.date() + relativedelta(days=-1))
        self.assertEqual(date, self.date1.date(), 'resource_calendar: wrong next day computing')

        # --------------------------------------------------
        # Test2: get_previous_day
        # --------------------------------------------------

        # Test: previous day: previous day before day1 is (day4-7)
        date = self.resource_calendar.get_previous_day(cr, uid, self.calendar_id, day_date=self.date1.date())
        self.assertEqual(date, self.date2.date() + relativedelta(days=-7), 'resource_calendar: wrong previous day computing')

        # Test: previous day: previous day before day4 is day1
        date = self.resource_calendar.get_previous_day(cr, uid, self.calendar_id, day_date=self.date2.date())
        self.assertEqual(date, self.date1.date(), 'resource_calendar: wrong previous day computing')

        # Test: previous day: previous day before day4+1 is day4
        date = self.resource_calendar.get_previous_day(cr, uid, self.calendar_id, day_date=self.date2.date() + relativedelta(days=1))
        self.assertEqual(date, self.date2.date(), 'resource_calendar: wrong previous day computing')

        # Test: previous day: previous day before day1-1 is (day4-7)
        date = self.resource_calendar.get_previous_day(cr, uid, self.calendar_id, day_date=self.date1.date() + relativedelta(days=-1))
        self.assertEqual(date, self.date2.date() + relativedelta(days=-7), 'resource_calendar: wrong previous day computing')

        # --------------------------------------------------
        # Test3: misc
        # --------------------------------------------------

        weekdays = self.resource_calendar.get_weekdays(cr, uid, self.calendar_id)
        self.assertEqual(weekdays, [1, 4], 'resource_calendar: wrong weekdays computing')

        attendances = self.resource_calendar.get_attendances_for_weekdays(cr, uid, self.calendar_id, [2, 3, 4, 5])
        self.assertEqual(set([att.id for att in attendances]), set([self.att2_id, self.att3_id]),
                         'resource_calendar: wrong attendances filtering by weekdays computing')

    def test_20_calendar_working_intervals(self):
        """ Testing working intervals computing method of resource.calendar """
        cr, uid = self.cr, self.uid
        _format = '%Y-%m-%d %H:%M:%S'

        # Test: day0 without leaves: 1 interval
        intervals = self.resource_calendar.get_working_intervals_of_day(cr, uid, self.calendar_id, start_dt=self.date1)
        self.assertEqual(len(intervals), 1, 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-12 09:08:07', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-12 16:00:00', _format), 'resource_calendar: wrong working intervals')

        # Test: day3 without leaves: 2 interval
        intervals = self.resource_calendar.get_working_intervals_of_day(cr, uid, self.calendar_id, start_dt=self.date2)
        self.assertEqual(len(intervals), 2, 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-15 10:11:12', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-15 13:00:00', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[1][0], datetime.strptime('2013-02-15 16:00:00', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[1][1], datetime.strptime('2013-02-15 23:00:00', _format), 'resource_calendar: wrong working intervals')

        # Test: day0 with leaves outside range: 1 interval
        intervals = self.resource_calendar.get_working_intervals_of_day(cr, uid, self.calendar_id, start_dt=self.date1.replace(hour=0), compute_leaves=True)
        self.assertEqual(len(intervals), 1, 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-12 08:00:00', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-12 16:00:00', _format), 'resource_calendar: wrong working intervals')

        # Test: day0 with leaves: 2 intervals because of leave between 9 ans 12, ending at 15:45:30
        intervals = self.resource_calendar.get_working_intervals_of_day(cr, uid, self.calendar_id,
                                                                        start_dt=self.date1.replace(hour=8) + relativedelta(days=7),
                                                                        end_dt=self.date1.replace(hour=15, minute=45, second=30) + relativedelta(days=7),
                                                                        compute_leaves=True)
        self.assertEqual(len(intervals), 2, 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-19 08:08:07', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-19 09:00:00', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[1][0], datetime.strptime('2013-02-19 12:00:00', _format), 'resource_calendar: wrong working intervals')
        self.assertEqual(intervals[1][1], datetime.strptime('2013-02-19 15:45:30', _format), 'resource_calendar: wrong working intervals')

    def test_30_calendar_working_days(self):
        """ Testing calendar hours computation on a working day """
        cr, uid = self.cr, self.uid
        _format = '%Y-%m-%d %H:%M:%S'

        # Test: day1, beginning at 10:30 -> work from 10:30 (arrival) until 16:00
        intervals = self.resource_calendar.get_working_intervals_of_day(cr, uid, self.calendar_id, start_dt=self.date1.replace(hour=10, minute=30, second=0))
        self.assertEqual(len(intervals), 1, 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-12 10:30:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-12 16:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        # Test: hour computation for same interval, should give 5.5
        wh = self.resource_calendar.get_working_hours_of_date(cr, uid, self.calendar_id, start_dt=self.date1.replace(hour=10, minute=30, second=0))
        self.assertEqual(wh, 5.5, 'resource_calendar: wrong working interval / day time computing')

        # Test: day1+7 on leave, without leave computation
        intervals = self.resource_calendar.get_working_intervals_of_day(
            cr, uid, self.calendar_id,
            start_dt=self.date1.replace(hour=7, minute=0, second=0) + relativedelta(days=7)
        )
        # Result: day1 (08->16)
        self.assertEqual(len(intervals), 1, 'resource_calendar: wrong working interval/day computing')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-19 08:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-19 16:00:00', _format), 'resource_calendar: wrong working interval / day computing')

        # Test: day1+7 on leave, with generic leave computation
        intervals = self.resource_calendar.get_working_intervals_of_day(
            cr, uid, self.calendar_id,
            start_dt=self.date1.replace(hour=7, minute=0, second=0) + relativedelta(days=7),
            compute_leaves=True
        )
        # Result: day1 (08->09 + 12->16)
        self.assertEqual(len(intervals), 2, 'resource_calendar: wrong working interval/day computing')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-19 08:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-19 09:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[1][0], datetime.strptime('2013-02-19 12:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[1][1], datetime.strptime('2013-02-19 16:00:00', _format), 'resource_calendar: wrong working interval / day computing')

        # Test: day1+14 on leave, with generic leave computation
        intervals = self.resource_calendar.get_working_intervals_of_day(
            cr, uid, self.calendar_id,
            start_dt=self.date1.replace(hour=7, minute=0, second=0) + relativedelta(days=14),
            compute_leaves=True
        )
        # Result: day1 (08->16)
        self.assertEqual(len(intervals), 1, 'resource_calendar: wrong working interval/day computing')
        self.assertEqual(intervals[0][0], datetime.strptime('2013-02-26 08:00:00', _format), 'resource_calendar: wrong working interval / day computing')
        self.assertEqual(intervals[0][1], datetime.strptime('2013-02-26 16:00:00', _format), 'resource_calendar: wrong working interval / day computing')

        # Test: day1+14 on leave, with resource leave computation
        intervals = self.resource_calendar.get_working_intervals_of_day(
            cr, uid, self.calendar_id,
            start_dt=self.date1.replace(hour=7, minute=0, second=0) + relativedelta(days=14),
            compute_leaves=True,
            resource_id=self.resource1_id
        )
        # Result: nothing, because on leave
        self.assertEqual(len(intervals), 0, 'resource_calendar: wrong working interval/day computing')

    def test_40_calendar_hours_scheduling(self):
        """ Testing calendar hours scheduling """
        cr, uid = self.cr, self.uid
        _format = '%Y-%m-%d %H:%M:%S'

        # --------------------------------------------------
        # Test0: schedule hours backwards (old interval_min_get)
        #   Done without calendar
        # --------------------------------------------------

        # Done without calendar
        # res = self.resource_calendar.interval_min_get(cr, uid, None, self.date1, 40, resource=False)
        # res: (datetime.datetime(2013, 2, 7, 9, 8, 7), datetime.datetime(2013, 2, 12, 9, 8, 7))

        # --------------------------------------------------
        # Test1: schedule hours backwards (old interval_min_get)
        # --------------------------------------------------

        # res = self.resource_calendar.interval_min_get(cr, uid, self.calendar_id, self.date1, 40, resource=False)
        #   (datetime.datetime(2013, 1, 29, 9, 0), datetime.datetime(2013, 1, 29, 16, 0))
        #   (datetime.datetime(2013, 2, 1, 8, 0), datetime.datetime(2013, 2, 1, 13, 0))
        #   (datetime.datetime(2013, 2, 1, 16, 0), datetime.datetime(2013, 2, 1, 23, 0))
        #   (datetime.datetime(2013, 2, 5, 8, 0), datetime.datetime(2013, 2, 5, 16, 0))
        #   (datetime.datetime(2013, 2, 8, 8, 0), datetime.datetime(2013, 2, 8, 13, 0))
        #   (datetime.datetime(2013, 2, 8, 16, 0), datetime.datetime(2013, 2, 8, 23, 0))
        #   (datetime.datetime(2013, 2, 12, 8, 0), datetime.datetime(2013, 2, 12, 9, 0))

        res = self.resource_calendar.schedule_hours(cr, uid, self.calendar_id, -40, day_dt=self.date1.replace(minute=0, second=0))
        # current day, limited at 09:00 because of day_dt specified -> 1 hour
        self.assertEqual(res[-1][0], datetime.strptime('2013-02-12 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-1][1], datetime.strptime('2013-02-12 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        # previous days: 5+7 hours / 8 hours / 5+7 hours -> 32 hours
        self.assertEqual(res[-2][0], datetime.strptime('2013-02-08 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-2][1], datetime.strptime('2013-02-08 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-3][0], datetime.strptime('2013-02-08 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-3][1], datetime.strptime('2013-02-08 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-4][0], datetime.strptime('2013-02-05 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-4][1], datetime.strptime('2013-02-05 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-5][0], datetime.strptime('2013-02-01 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-5][1], datetime.strptime('2013-02-01 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-6][0], datetime.strptime('2013-02-01 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-6][1], datetime.strptime('2013-02-01 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        # 7 hours remaining
        self.assertEqual(res[-7][0], datetime.strptime('2013-01-29 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[-7][1], datetime.strptime('2013-01-29 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        # Compute scheduled hours
        td = timedelta()
        for item in res:
            td += item[1] - item[0]
        self.assertEqual(seconds(td) / 3600.0, 40.0, 'resource_calendar: wrong hours scheduling')

        # --------------------------------------------------
        # Test2: schedule hours forward (old interval_get)
        # --------------------------------------------------

        # res = self.resource_calendar.interval_get(cr, uid, self.calendar_id, self.date1, 40, resource=False, byday=True)
        #   (datetime.datetime(2013, 2, 12, 9, 0), datetime.datetime(2013, 2, 12, 16, 0))
        #   (datetime.datetime(2013, 2, 15, 8, 0), datetime.datetime(2013, 2, 15, 13, 0))
        #   (datetime.datetime(2013, 2, 15, 16, 0), datetime.datetime(2013, 2, 15, 23, 0))
        #   (datetime.datetime(2013, 2, 22, 8, 0), datetime.datetime(2013, 2, 22, 13, 0))
        #   (datetime.datetime(2013, 2, 22, 16, 0), datetime.datetime(2013, 2, 22, 23, 0))
        #   (datetime.datetime(2013, 2, 26, 8, 0), datetime.datetime(2013, 2, 26, 16, 0))
        #   (datetime.datetime(2013, 3, 1, 8, 0), datetime.datetime(2013, 3, 1, 9, 0))

        res = self.resource_calendar.schedule_hours(
            cr, uid, self.calendar_id, 40,
            day_dt=self.date1.replace(minute=0, second=0)
        )
        self.assertEqual(res[0][0], datetime.strptime('2013-02-12 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[0][1], datetime.strptime('2013-02-12 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[1][0], datetime.strptime('2013-02-15 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[1][1], datetime.strptime('2013-02-15 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[2][0], datetime.strptime('2013-02-15 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[2][1], datetime.strptime('2013-02-15 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[3][0], datetime.strptime('2013-02-19 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[3][1], datetime.strptime('2013-02-19 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[4][0], datetime.strptime('2013-02-22 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[4][1], datetime.strptime('2013-02-22 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[5][0], datetime.strptime('2013-02-22 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[5][1], datetime.strptime('2013-02-22 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[6][0], datetime.strptime('2013-02-26 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[6][1], datetime.strptime('2013-02-26 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        td = timedelta()
        for item in res:
            td += item[1] - item[0]
        self.assertEqual(seconds(td) / 3600.0, 40.0, 'resource_calendar: wrong hours scheduling')

        # res = self.resource_calendar.interval_get(cr, uid, self.calendar_id, self.date1, 40, resource=self.resource1_id, byday=True)
        #   (datetime.datetime(2013, 2, 12, 9, 0), datetime.datetime(2013, 2, 12, 16, 0))
        #   (datetime.datetime(2013, 2, 15, 8, 0), datetime.datetime(2013, 2, 15, 13, 0))
        #   (datetime.datetime(2013, 2, 15, 16, 0), datetime.datetime(2013, 2, 15, 23, 0))
        #   (datetime.datetime(2013, 3, 1, 8, 0), datetime.datetime(2013, 3, 1, 13, 0))
        #   (datetime.datetime(2013, 3, 1, 16, 0), datetime.datetime(2013, 3, 1, 23, 0))
        #   (datetime.datetime(2013, 3, 5, 8, 0), datetime.datetime(2013, 3, 5, 16, 0))
        #   (datetime.datetime(2013, 3, 8, 8, 0), datetime.datetime(2013, 3, 8, 9, 0))

        res = self.resource_calendar.schedule_hours(
            cr, uid, self.calendar_id, 40,
            day_dt=self.date1.replace(minute=0, second=0),
            compute_leaves=True,
            resource_id=self.resource1_id
        )
        self.assertEqual(res[0][0], datetime.strptime('2013-02-12 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[0][1], datetime.strptime('2013-02-12 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[1][0], datetime.strptime('2013-02-15 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[1][1], datetime.strptime('2013-02-15 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[2][0], datetime.strptime('2013-02-15 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[2][1], datetime.strptime('2013-02-15 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[3][0], datetime.strptime('2013-02-19 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[3][1], datetime.strptime('2013-02-19 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[4][0], datetime.strptime('2013-02-19 12:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[4][1], datetime.strptime('2013-02-19 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[5][0], datetime.strptime('2013-02-22 08:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[5][1], datetime.strptime('2013-02-22 09:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[6][0], datetime.strptime('2013-02-22 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[6][1], datetime.strptime('2013-02-22 23:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[7][0], datetime.strptime('2013-03-01 11:30:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[7][1], datetime.strptime('2013-03-01 13:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[8][0], datetime.strptime('2013-03-01 16:00:00', _format), 'resource_calendar: wrong hours scheduling')
        self.assertEqual(res[8][1], datetime.strptime('2013-03-01 22:30:00', _format), 'resource_calendar: wrong hours scheduling')
        td = timedelta()
        for item in res:
            td += item[1] - item[0]
        self.assertEqual(seconds(td) / 3600.0, 40.0, 'resource_calendar: wrong hours scheduling')

        # --------------------------------------------------
        # Test3: working hours (old _interval_hours_get)
        # --------------------------------------------------

        # old API: resource without leaves
        # res: 2 weeks -> 40 hours
        res = self.resource_calendar._interval_hours_get(
            cr, uid, self.calendar_id,
            self.date1.replace(hour=6, minute=0),
            self.date2.replace(hour=23, minute=0) + relativedelta(days=7),
            resource_id=self.resource1_id, exclude_leaves=True)
        self.assertEqual(res, 40.0, 'resource_calendar: wrong _interval_hours_get compatibility computation')

        # new API: resource without leaves
        # res: 2 weeks -> 40 hours
        res = self.resource_calendar.get_working_hours(
            cr, uid, self.calendar_id,
            self.date1.replace(hour=6, minute=0),
            self.date2.replace(hour=23, minute=0) + relativedelta(days=7),
            compute_leaves=False, resource_id=self.resource1_id)
        self.assertEqual(res, 40.0, 'resource_calendar: wrong get_working_hours computation')

        # old API: resource and leaves
        # res: 2 weeks -> 40 hours - (3+4) leave hours
        res = self.resource_calendar._interval_hours_get(
            cr, uid, self.calendar_id,
            self.date1.replace(hour=6, minute=0),
            self.date2.replace(hour=23, minute=0) + relativedelta(days=7),
            resource_id=self.resource1_id, exclude_leaves=False)
        self.assertEqual(res, 33.0, 'resource_calendar: wrong _interval_hours_get compatibility computation')

        # new API: resource and leaves
        # res: 2 weeks -> 40 hours - (3+4) leave hours
        res = self.resource_calendar.get_working_hours(
            cr, uid, self.calendar_id,
            self.date1.replace(hour=6, minute=0),
            self.date2.replace(hour=23, minute=0) + relativedelta(days=7),
            compute_leaves=True, resource_id=self.resource1_id)
        self.assertEqual(res, 33.0, 'resource_calendar: wrong get_working_hours computation')

        # --------------------------------------------------
        # Test4: misc
        # --------------------------------------------------

        # Test without calendar and default_interval
        res = self.resource_calendar.get_working_hours(
            cr, uid, None,
            self.date1.replace(hour=6, minute=0),
            self.date2.replace(hour=23, minute=0),
            compute_leaves=True, resource_id=self.resource1_id,
            default_interval=(8, 16))
        self.assertEqual(res, 32.0, 'resource_calendar: wrong get_working_hours computation')

    def test_50_calendar_schedule_days(self):
        """ Testing calendar days scheduling """
        cr, uid = self.cr, self.uid
        _format = '%Y-%m-%d %H:%M:%S'

        # --------------------------------------------------
        # Test1: with calendar
        # --------------------------------------------------

        res = self.resource_calendar.schedule_days_get_date(cr, uid, self.calendar_id, 5, day_date=self.date1)
        self.assertEqual(res.date(), datetime.strptime('2013-02-26 00:0:00', _format).date(), 'resource_calendar: wrong days scheduling')

        res = self.resource_calendar.schedule_days_get_date(
            cr, uid, self.calendar_id, 5, day_date=self.date1,
            compute_leaves=True, resource_id=self.resource1_id)
        self.assertEqual(res.date(), datetime.strptime('2013-03-01 00:0:00', _format).date(), 'resource_calendar: wrong days scheduling')

        # --------------------------------------------------
        # Test2: misc
        # --------------------------------------------------

        # Without calendar, should only count days -> 12 -> 16, 5 days with default intervals
        res = self.resource_calendar.schedule_days_get_date(cr, uid, None, 5, day_date=self.date1, default_interval=(8, 16))
        self.assertEqual(res, datetime.strptime('2013-02-16 16:00:00', _format), 'resource_calendar: wrong days scheduling')

def seconds(td):
    assert isinstance(td, timedelta)

    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10.**6


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>RegExp Download Organizer</title>

    <link rel="stylesheet" href="css/bootstrap.min.css">

Download rules

                    <button id="add-rule-btn" type="button" class="btn btn-success">
                         New rule
                    </button>
                    <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">

                        Toggle Dropdown
                    </button>

New rule from text...

                <button type="button" class="close" data-dismiss="alert">×</button>
                Please note that some rules are disabled and will not apply until you enable them. Tick a checkbox on the right side of a rule to enable it.

                    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">

                        Export rules

                    </button>

Save to file

Sync to cloud

                    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">

                        Import rules

                    </button>

Load from file...

Sync from cloud

                <button id="reset-rules-btn" type="button" class="btn btn-danger pull-right">Reset rules...</button>

Help

Changelog New!

About

Download rules

The download rules are applied one by one whenever you start downloading a file. Each rule
                        consists of matchers and a download path pattern.
                        The matchers are actually a set of regular expressions that applied to the
                        filetype, URL,
                        referrer URL and filename of the download item.
                        If all of the non-empty mathers succeed for some rule, the file is renamed according to the
                        download path pattern of this rule, the other rules are skipped.

                        All the regular expressions are case-insensitive.

Matchers

You can use any RegExp constructions in the matchers (even the capturing groups).

MIME types

                    MIME filetype is a text string that describes a format of a file. Check the following list of the most common MIME types:

application/pdf

PDF documents

application/zip

Compressed archives

application/x-bittorrent

Torrent files

application/exe

Windows executable

audio/mpeg

MP3 and other MPEG audio

image/gif

GIF images

image/jpeg

JPEG images

image/png

PNG images

video/x-msvideo

AVI video

There is also a more detailed list of common MIME types for reference.

Don't forget that you can always use a wildcard to match a group of filetypes (e.g. image/.* or audio/.*)

Destination path pattern

This part of a rule defines a destination path where the downloaded file will be stored.

You can access the captured groups from the matchers using special
                        placeholders in the following format — ${matcher:num}, where
                        matcher is an id of the matcher and num is a number of the capturing
                        group starting from 1. For example placeholder ${referrer:1} will be substituted
                        with the contents of the capturing group #1 from the Referrer matcher.

                        To access a whole field use a placeholder with no index (e.g. ${filename}).

There is a list of the available placeholders: mime, url, finalUrl, referrer, filename.

The result path is forced by Chrome within the default download folder. You can use
                        symbolic links to circumvent this limitation.

RegExp cheatsheet

                        "|" is an OR operator. E.g. facebook|google matches any string
                        with either facebook or google in it.

                        "." is a single-character wildcard. E.g. a.b matches
                        a-b, acb, a b, etc.

                        ".*" is a multi-character wildcard (can match zero characters)

                        ".+" is a multi-character wildcard (cannot match zero characters, requires at
                        least one character to match)

                        "\" is used to escape special symbols. E.g. dots in
                        www\.google\.com are not single-character wildcards.

                        Capturing groups are regular expressions surrounded by round brackets "( )".
                        E.g. www\.(.+)\.com will match .com-domain names and store domain name
                        without
                        "www." prefix and ".com" suffix in group 1.

More info about regular expressions:
                        Wikipedia,
                        Mozilla Developer Network

Date formatter

                        You can add a special date placeholder into destination path to organize downloads by date and/or time.
                        There are some most useful examples:

${date} → 2018-11-18

${date:YYYY} → 2018

${date:YYYY, MMMM} → 2018, November

${date:YYYY.MM.DD} → 2018.11.18

${date:YYYY.MM.DD_HH-mm-ss} → 2018.11.18_16-38-08

More info about date formatters in moment.js documentation.

Overriding file extensions

                        It's not possible to override extensions for known MIME-types because of the Chrome API limitations.
                        However, as a workaround you can use 3rd-party extensions to modify the response headers for the urls you download,
                        changing the Content-Type header to some unexpected MIME-type, e.g. application/x-unknown-mime-type.
                        Then you will be able to create a rule with a custom file extension in destination path.

Version 0.3.2

Support export to/from the cloud storage

Version 0.3.1

Added support for name conflict action

Version 0.3

Added support for Final URL (file download url after all redirects) field and corresponding finalUrl placeholder

Version 0.2.5

Fixed typo in predefined referrer rule (reset the rules if your referrer rule doesn't work)

Version 0.2.4.2

Fixed issue with multiple matchers in destination

Version 0.2.4

Added date/time formatter for destination

Added human-friendly descriptions for rules

Now it's possible to disable rules instead of deleting them

More predefined rules

Version 0.2.3

Fixed issue with escaped URLs

Version 0.2.2

Lots of bugfixes

Rule title redesign

Version 0.2

Added import and export of rulesets

Added "Share rule" button

Small bugfixes and UI improvements

Version 0.1

Initial version, basic functionality

♥ Made with love to humans by robots~

Feel free to report any issues and feature requests or to join the development via our GitHub page

Issue tracker

GitHub repository

Chrome web store (for likes)

License

                <button type="button" class="close" data-dismiss="modal">×Close
                </button>

Share rule

You can copy the text below and share your rule to a friend.

                    To import a rule use "New rule from text..." button

                <textarea class="form-control " rows="4" readonly></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                <button type="button" class="close" data-dismiss="modal">×Close
                </button>

New rule

                <textarea class="form-control" rows="10"></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Create rule</button>

                <button type="button" class="close" data-dismiss="modal">×Close
                </button>

Import rules

                    Load from file:
                    <input id="importRulesFromTextModalFileInput" type="file" accept="text/plain,application/json,.json,.txt" />

                <textarea class="form-control" rows="15"></textarea>

                        <input type="checkbox" id="import-rules-replace-existing-ckbx"> Replace existing rules (use with care)

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Import</button>

redpajama_set_name: RedPajamaGithub


text:
class Group implements IRule {

	public name: string = 'group';
	public method: string;
	public option: string;
	public params: string[] = [];
	public priority: number = 10000;
	public dependence: string[] = [];
	public when: any;

	constructor (methods: string[]) {
	}

}


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>vueupload-files</title>


text:
import GameSprite from './GameSprite'
import Arrow from './Arrow'

export default class Bow extends GameSprite {
  constructor (game, arrowGroup, obstacleGroup, meteorGroup, fireGroup, player, powersManager) {
    super(game, 0, 0, 'pre-bow')

    this.player = player

    this.powersManager = powersManager

    this.game = game

    this.arrowGroup = arrowGroup
    this.obstacleGroup = obstacleGroup
    this.meteorGroup = meteorGroup
    this.fireGroup = fireGroup

    this.bowTime = 0;

    this.anchor.setTo(0, 0.5);

    this.ARROW_SPEED = 600;
    this.MAX_TIME = 1000;

    this.kill();

  }

  shootArrow() {
    let arrow = this.arrow;
    this.arrow = null;
    let speed = this.ARROW_SPEED;
    let rate = (this.bowTime > this.MAX_TIME) ? 1 : this.bowTime / this.MAX_TIME;
    this.bowTime = 0;

    if (rate < 0.5) {
      return;
    }
    arrow.anchor.setTo(0.5, 0.5);
    this.game.physics.enable(arrow, Phaser.Physics.ARCADE);

    arrow.checkWorldBounds = true;
    arrow.outOfBoundsKill = true;

    speed *= rate;

    console.log(speed)

    arrow.body.velocity.x = Math.cos(arrow.rotation) * speed;
    arrow.body.velocity.y = Math.sin(arrow.rotation) * speed;

    this.arrowGroup.add(arrow);
  }

  updateIndependent() {
    if (this.game.gameEnded) {
      return
    }
    if (this.game.input.activePointer.duration != -1) {
      this.bowTime = this.game.input.activePointer.duration;

      if (! this.alive) {
        this.revive();

      }

      this.position.setTo(
        this.player.body.center.x,
        this.player.body.center.y
      );

      this.anchor.setTo(-0.5, 0.5);
      if (this.bowTime < this.MAX_TIME / 2) {
        this.rotation = Math.PI/2;
      } else {
        if (! this.arrow) {
          this.anchor.setTo(-0.5, 0.5);
          this.arrow = new Arrow(this.game, null, this.obstacleGroup, this.meteorGroup, this.fireGroup);
          this.arrow.anchor.setTo(-0.23, 0.5);
        }
        this.rotation = this.game.physics.arcade.angleToPointer(this.player);
        this.arrow.reset(this.x, this.y);
        this.arrow.rotation = this.rotation;
        if (this.arrow.power === -1 && this.powersManager.currentPower !== -1) {
          this.arrow.enchant(this.powersManager.popPower())
        }
      }

    } else if (this.bowTime) {
      this.shootArrow();
      this.kill();
    }
  }

}


text:
Probe.Store = DS.Store.extend({
  adapter: "Probe.ApplicationAdapter"
});


text:
package com.yammer.backups.error;

import com.google.common.base.Optional;
import com.yammer.backups.api.Node;
import com.yammer.backups.storage.metadata.MetadataStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.net.URI;
import java.net.URISyntaxException;

public class IncorrectNodeExceptionMapper implements ExceptionMapper<IncorrectNodeException>{

    private static final Logger LOG = LoggerFactory.getLogger(IncorrectNodeExceptionMapper.class);

    private final MetadataStorage<Node> nodeStorage;

    public IncorrectNodeExceptionMapper(MetadataStorage<Node> nodeStorage) {
        this.nodeStorage = nodeStorage;
    }

    @Override
    public Response toResponse(IncorrectNodeException exception) {
        final Optional<Node> node = nodeStorage.get(exception.getCorrectNode(), exception.getCorrectNode());
        if (!node.isPresent()) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }

        try {
            final URI location = node.get().getUrl().toURI();
            return Response.temporaryRedirect(location).build();
        }
        catch (URISyntaxException e) {
            LOG.warn("Failed to redirect to correct node", e);
            throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}


text:
/*
Package main implements an example integration with Current.

https://current.sh

To use with syslog, run ./syslog.bash <org>.

To use with the current cli tool, run using ./stdout.bash <org>.

To output the debug messages, set the LOG_LEVEL environment variable to DEBUG.
*/
package main

import (
	"fmt"
	"os"

	"go.pedge.io/lion/env"
	"go.pedge.io/lion/proto"
)

func main() {
	if err := do(); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	os.Exit(0)
}

func do() error {
	if err := envlion.Setup(); err != nil {
		return err
	}
	for i := 1; i < 5; i++ {
		protolion.Info(
			&Foo{
				Bar: &Bar{
					One: "one",
				},
				Two:   fmt.Sprintf("two%d", i),
				Three: uint64(i),
			},
		)
		protolion.Debugf("hello%d", i*i*i)
	}
	return nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Harvard Pap. Bot. 9:144. 2004

#### Original name
Oxytheca parishii var. goodmaniana Ertter

### Remarks
null


text:
package org.osgeo.proj4j.util;

import java.util.HashMap;
import java.util.Map;
import org.osgeo.proj4j.*;

public class CRSCache
{
  private static Map<String, CoordinateReferenceSystem> projCache = new HashMap<String, CoordinateReferenceSystem>();
  private static CRSFactory crsFactory = new CRSFactory();

// TODO: provide limit on number of items in cache (LRU)

  public CRSCache() {
    super();
  }

  public CoordinateReferenceSystem createFromName(String name)
  throws UnsupportedParameterException, InvalidValueException, UnknownAuthorityCodeException
  {
    CoordinateReferenceSystem proj = (CoordinateReferenceSystem) projCache.get(name);
    if (proj == null) {
      proj = crsFactory.createFromName(name);
      projCache.put(name, proj);
    }
    return proj;
  }

}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class PoliceStation extends CI_Controller {

    /**
     * Index page for Magazine controller.
     */
    public function index() {
        $this->load->view('addpolicestation');
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        $policeStation->name = $this->input->post('name');
        $policeStation->province = $this->input->post('province');
        $policeStation->district = $this->input->post('district');
        $policeStation->save();
    }

    public function add() {
        $this->load->view('addpolicestation');
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        $policeStation->name = $this->input->post('name');
        $policeStation->province = $this->input->post('province');
        $policeStation->district = $this->input->post('district');
        $policeStation->save();
    }

    public function getByProvince($value) {
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        echo json_encode($policeStation->loadByColumn('province', $value));
    }

    public function getByDistrict($value) {
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        echo json_encode($policeStation->loadByColumn('district', $value));
    }

    public function getByName($value) {
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        echo json_encode($policeStation->loadByColumn('name', $value));
    }
    public function getById($id) {
        $data = array();
        $this->load->model('PoliceStation_m');
        $policeStation = new PoliceStation_m();
        $policeStation->load($id);
        $data['policestation'] = $policeStation;
        echo json_encode($data);
    }

}


text:
'use strict'

const localShortcut = require('electron-localshortcut');

module.exports = (win) => {

  if (process.env.NODE_ENV === 'development') {
    localShortcut.register(win, 'CommandOrControl+Alt+I', () => {
      win.toggleDevTools();
    });
  }

  localShortcut.register(win, 'CommandOrControl+S', () => {
    win.webContents.send('saveFile');
  });

  localShortcut.register(win, 'CommandOrControl+Backspace', () => {
    win.webContents.send('delete');
  });
}


text:
namespace Microsoft.Samples.Kinect.ControlsBasics
{
    using System.Globalization;
    using System.Windows.Controls;

    /// <summary>
    /// Interaction logic
    /// </summary>
    public partial class SelectionDisplay : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectionDisplay"/> class.
        /// </summary>
        /// <param name="itemId">ID of the item that was selected</param>
        public SelectionDisplay()
        {
            this.InitializeComponent();

            //this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture, Properties.SelectedMessage, itemId);
            //this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture, "Empty content", itemId);
        }

        public void printMessage(string itemId, string message)
        {
            this.messageTextBlock.Text = string.Format(CultureInfo.CurrentCulture, message, itemId);
        }

        /// <summary>
        /// Called when the OnLoaded storyboard completes.
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void OnLoadedStoryboardCompleted(object sender, System.EventArgs e)
        {
            var parent = (Panel)this.Parent;
            parent.Children.Remove(this);
        }
    }
}


text:
(function() {
  LMVUI.AnimationPlayer = Polymer({
    is: "lmv-animation-player",

    properties: {
      time: {
        type: Number,
        value: 0,
        reflectToAttribute: true,
        observer: "_timeChanged",
      }
    },

    attached: function() {
      if (!LMVUI._getViewerReference(this))
        return;

      this._onPlay = this._onPlay.bind(this);

      this.reset();

      if (this.viewer.model && this.viewer.model.myData.animations) {
        this.loadAnimation();
      }

      var self = this;
      LMVUI._addViewerListener(this, Autodesk.Viewing.OBJECT_TREE_CREATED_EVENT, function() {
        self.unloadAnimation();
      });
      LMVUI._addViewerListener(this, Autodesk.Viewing.ANIMATION_READY_EVENT, function() {
        self.loadAnimation();
      });
    },
    loadAnimation: function() {
      this.animator = this.viewer.impl.keyFrameAnimator;
      this.$.timeline.max = this.animator.duration;
    },
    unloadAnimation: function() {
      this.reset();
      this.animator = undefined;
    },
    _timeChanged: function(value) {
      this.timeStr =
        LMVUI.formatInt(value / 60, 2) + ":" +
        LMVUI.formatInt(value % 60, 2) + ":" +
        LMVUI.formatInt(value * 100, 2);
    },
    _onSliderChange: function() {
      this.play(false);
      if (!this.animator)
        return;
      this.animator.goto(this.time);
    },
    reset: function() {
      this.play(false);
      this.time = 0;
    },
    prev: function() {
      this.play(false);
      if (!this.animator)
        return;
      this.animator.prev();
      this.time = this.animator.currentTime;
    },
    next: function() {
      this.play(false);
      if (!this.animator)
        return;
      this.animator.next();
      this.time = this.animator.currentTime;
    },
    play: function(play) {
      if (typeof(play) !== "boolean")
        this.playing = !this.playing;
      else if (play === this.playing)
        return;
      else
        this.playing = play;

      this.playIcon = this.playing ? "pause" : "play";

      if (!this.animator)
        return;

      if (this.playing)
        this.animator.play(0, this._onPlay);
      else
        this.animator.pause();
    },
    _onPlay: function() {
      this.time = this.animator.currentTime;
      if (this.time >= this.animator.duration)
        this.play(false);
    },

    detached: function() {
      LMVUI._cleanupListeners(this);
    },
  });
})();


text:
'use strict';

const encode = require('./encode');

const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;

/**
 * Efficient builder for base64 VLQ mappings strings.
 *
 * This class uses a buffer that is preallocated with one megabyte and is
 * reallocated dynamically as needed, doubling its size.
 *
 * Encoding never creates any complex value types (strings, objects), and only
 * writes character values to the buffer.
 *
 * For details about source map terminology and specification, check
 * https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
 */
class B64Builder {
  buffer: Buffer;
  pos: number;
  hasSegment: boolean;

  constructor() {
    this.buffer = new Buffer(ONE_MEG);
    this.pos = 0;
    this.hasSegment = false;
  }

  /**
   * Adds `n` markers for generated lines to the mappings.
   */
  markLines(n: number) {
    this.hasSegment = false;
    if (this.pos + n >= this.buffer.length) {
      this._realloc();
    }
    while (n--) {
      this.buffer[this.pos++] = SEMICOLON;
    }
    return this;
  }

  /**
   * Starts a segment at the specified column offset in the current line.
   */
  startSegment(column: number) {
    if (this.hasSegment) {
      this._writeByte(COMMA);
    } else {
      this.hasSegment = true;
    }

    this.append(column);
    return this;
  }

  /**
   * Appends a single number to the mappings.
   */
  append(value: number) {
    if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
      this._realloc();
    }

    this.pos = encode(value, this.buffer, this.pos);
    return this;
  }

  /**
   * Returns the string representation of the mappings.
   */
  toString() {
    return this.buffer.toString('ascii', 0, this.pos);
  }

  _writeByte(byte) {
    if (this.pos === this.buffer.length) {
      this._realloc();
    }
    this.buffer[this.pos++] = byte;
  }

  _realloc() {
    const {buffer} = this;
    this.buffer = new Buffer(buffer.length * 2);
    buffer.copy(this.buffer);
  }
}

module.exports = B64Builder;


text:
package android.database;

public class CharArrayBuffer
{
    protected CharArrayBuffer() {}
    public CharArrayBuffer(char[] p0){}
    public CharArrayBuffer(int p0){}
    public char[] data = null;
    public int sizeCopied = 0;
}


text:
package share.core.objects;

import share.core.utils.Shareable;

public class Task extends Shareable
{
	private static final long serialVersionUID = -3644821978306587322L;

	public final int id;
	public final String name;
	public final String path;

	public Task(int id, String name, String path)
	{
		this.id = id;
		this.name = name;
		this.path = path;
	}
}


text:
const util = require('util');
const stdin = process.stdin;
const Readable = require('stream').Readable;

const es = require('event-stream');

stdin.setRawMode(true);

stdin.resume();

stdin.setEncoding( 'utf8' );

stdin.on('data', function (key) {
  if (key === '\u0003') {
    process.exit();
  }
});

var arrowKeys = {
  '\u001bOD': {move: 'left'},
  '\u001bOA': {move: 'up'},
  '\u001bOC': {move: 'right'},
  '\u001bOB': {move: 'down'}
};

function MovementSource() {
  Readable.call(this, {objectMode: true});
  var self = this;
  this.shouldWrite = true;
  stdin.on('data', function (key) {
    // console.log(JSON.stringify(key));
    if (self.shouldWrite) {
      // TODO Filter
      if (arrowKeys[key]) {
        self.shouldWrite = self.push(arrowKeys[key]);
      }
    }
  });
}

util.inherits(MovementSource, Readable);

MovementSource.prototype._read = function (bytes) {
  this.shouldWrite = true;
};

module.exports = MovementSource;

if (require.main === module) {
  (new MovementSource())
    .pipe(es.stringify())
    .pipe(process.stdout);
}


text:
package jodd.json.model.cat;

import java.util.List;
import java.util.Map;

public class Catalog {

	private Map<Long, String> areaNames;
	private Map<Long, String> audienceSubCategoryNames;
	private Map<Long, Event> events;
	private List<Performance> performances;
	private Map<Long, String> seatCategoryNames;
	private Map<Long, String> subTopicNames;
	private Map<Long, String> topicNames;
	private Map<Long, Long[]> topicSubTopics;
	private Map<String, String> venueNames;

	public Map<Long, String> getAreaNames() {
		return areaNames;
	}

	public void setAreaNames(Map<Long, String> areaNames) {
		this.areaNames = areaNames;
	}

	public Map<Long, String> getAudienceSubCategoryNames() {
		return audienceSubCategoryNames;
	}

	public void setAudienceSubCategoryNames(Map<Long, String> audienceSubCategoryNames) {
		this.audienceSubCategoryNames = audienceSubCategoryNames;
	}

	public Map<Long, Event> getEvents() {
		return events;
	}

	public void setEvents(Map<Long, Event> events) {
		this.events = events;
	}

	public List<Performance> getPerformances() {
		return performances;
	}

	public void setPerformances(List<Performance> performances) {
		this.performances = performances;
	}

	public Map<Long, String> getSeatCategoryNames() {
		return seatCategoryNames;
	}

	public void setSeatCategoryNames(Map<Long, String> seatCategoryNames) {
		this.seatCategoryNames = seatCategoryNames;
	}

	public Map<Long, String> getSubTopicNames() {
		return subTopicNames;
	}

	public void setSubTopicNames(Map<Long, String> subTopicNames) {
		this.subTopicNames = subTopicNames;
	}

	public Map<Long, String> getTopicNames() {
		return topicNames;
	}

	public void setTopicNames(Map<Long, String> topicNames) {
		this.topicNames = topicNames;
	}

	public Map<Long, Long[]> getTopicSubTopics() {
		return topicSubTopics;
	}

	public void setTopicSubTopics(Map<Long, Long[]> topicSubTopics) {
		this.topicSubTopics = topicSubTopics;
	}

	public Map<String, String> getVenueNames() {
		return venueNames;
	}

	public void setVenueNames(Map<String, String> venueNames) {
		this.venueNames = venueNames;
	}
}


text:
deepr
=====

An R package to streamline the training, fine-tuning and predicting processes for deep learning.
It aims to further simplify the functions in packages such as 'h2o' and 'deepnet'.

### Installation
```
library(devtools)
install_github("woobe/deepr")
```

### Example 1

Extracting hidden features from original predictors (x) and creating new predictors (x_new).

#### 1.1 Load Library
```
library(deepr)
```

#### 1.2 Generate random numbers as original predictors (x)
```
x <- matrix(rnorm(1000000), nrow = 5000)
dim(x)
```
```
[1] 5000  200
```

#### 1.3 Train a RBM model with 100 hidden features
```
model_rbm <- train_rbm(x, n_features = 100)
```
```
=====================================================================
[deepr]: Training a Restricted Boltzmann Machine
=====================================================================
[deepr]: Removing variables with near zero variance ...
[deepr]: Normalising x to values between 0 and 1 ...
[deepr]: Training a RBM Layer of 10 Hidden Features ...
[deepr]: Returning the RBM Model ...
[deepr]: All Done! Total Duration: 474 sec.
=====================================================================
```

#### 1.4 Transform original x into new x
```
x_new <- transform_x(model_rbm, x)
```
```
=====================================================================
[deepr]: Transforming Predictors Using a Trained RBM
=====================================================================
[deepr]: Pre-processing predictors (x) based on the RBM object ...
[deepr]: Converting original predictors (x) into new ones (x_new) ...
[deepr]: Returning new predictors (x_new) ...
[deepr]: All Done! Total Duration: 1 sec.
=====================================================================
```
```
dim(x_new)
```
```
[1] 5000   100
```

#### 1.5 Install or upgrade H2O's R package quickly
```
## Automatically install the latest version
install_h2o()
```

```
## Install a specific version
install_h2o(h2o_ver = "1500")
```

```
## Overwrite the current R package
install_h2o(force = TRUE)
```


text:
package org.synyx.urlaubsverwaltung.restapi.availability;

import java.math.BigDecimal;

/**
 * Represents the availability for a person on a given day. Also contains the reason for being absent.
 *
 * @author  Marc Kannegiesser - kannegiesser@synyx.de
 * @author  Timo Eifler - eifler@synyx.de
 */
class DayAvailability {

    private final String date;
    private final BigDecimal availabilityRatio;
    private final TimedAbsenceSpans timedAbsenceSpans;

    public DayAvailability(BigDecimal availabilityRatio, String date, TimedAbsenceSpans timedAbsenceSpans) {

        this.availabilityRatio = availabilityRatio;
        this.date = date;
        this.timedAbsenceSpans = timedAbsenceSpans;
    }

    public String getDate() {

        return date;
    }

    public TimedAbsenceSpans getTimedAbsenceSpans() {

        return timedAbsenceSpans;
    }

    public BigDecimal getAvailabilityRatio() {

        return availabilityRatio;
    }
}


text:
//
// DocumentViewContent.cs
//
// Author:
//       Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2015 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using Pinta.Core;
using Pinta.Docking.Gui;

namespace Pinta
{
    class DocumentViewContent : IViewContent
    {
        private CanvasWindow canvas_window;

        public Document Document { get; private set; }

        public DocumentViewContent (Document document, CanvasWindow canvasWindow)
        {
            this.Document = document;
            this.canvas_window = canvasWindow;

            document.IsDirtyChanged += (o, e) => IsDirty = document.IsDirty;
            document.Renamed += (o, e) => { if (ContentNameChanged != null) ContentNameChanged (this, EventArgs.Empty); };
        }

        #region IViewContent Members
        public event EventHandler ContentNameChanged;
        public event EventHandler ContentChanged;
        public event EventHandler DirtyChanged;
        public event EventHandler BeforeSave;

        public string ContentName {
            get { return Document.Filename; }
            set { Document.Filename = value; }
        }

        public string UntitledName { get; set; }

        // We don't put icons on the tabs
        public string StockIconId {
            get { return string.Empty; }
        }

        public bool IsUntitled {
            get { return false; }
        }

        public bool IsViewOnly {
            get { return false; }
        }

        public bool IsFile {
            get { return true; }
        }

        public bool IsDirty {
            get { return Document.IsDirty; }
            set {
                if (DirtyChanged != null)
                    DirtyChanged (this, EventArgs.Empty);
            }
        }

        // can remove?
        public bool IsReadOnly {
            get { return false; }
        }

        public void Load (string fileName)
        {
        }

        public void LoadNew (System.IO.Stream content, string mimeType)
        {
        }

        public void Save (string fileName)
        {
        }

        public void Save ()
        {
        }

        public void DiscardChanges ()
        {
        }
        #endregion

        #region IBaseViewContent Members
        public IWorkbenchWindow WorkbenchWindow { get; set; }

        public Gtk.Widget Control {
            get { return canvas_window; }
        }

        public string TabPageLabel {
            get { return string.Empty; }
        }

        public object GetContent (Type type)
        {
            return null;
        }

        public bool CanReuseView (string fileName)
        {
            return false;
        }

        public void RedrawContent ()
        {
        }
        #endregion

        #region IDisposable Members
        public void Dispose ()
        {
            if (canvas_window != null)
                canvas_window.Dispose ();
        }
        #endregion
    }
}


text:
import {expect} from "chai"

import {LinearScale} from "@bokehjs/models/scales/linear_scale"
import {Range1d} from "@bokehjs/models/ranges/range1d"

describe("linear_scale module", () => {

  function mkscale(): LinearScale {
    return new LinearScale({
      source_range: new Range1d({start: 0, end: 10}),
      target_range: new Range1d({start: 20, end: 80}),
    })
  }

  describe("creation with Range1d ranges", () => {
    const scale = mkscale()

    it("should compute scale state", () => {
      expect(scale._compute_state()).to.be.deep.equal([6, 20])
    })

    it("should map values linearly", () => {
      expect(scale.compute(-1)).to.be.equal(14)
      expect(scale.compute(0)).to.be.equal(20)
      expect(scale.compute(5)).to.be.equal(50)
      expect(scale.compute(10)).to.be.equal(80)
      expect(scale.compute(11)).to.be.equal(86)
    })

    it("should vector map values linearly", () => {
      expect(scale.v_compute([-1,0,5,10,11])).to.be.deep.equal(new Float64Array([14,20,50,80,86]))
    })

    it("should map to a Float64Array", () => {
      expect(scale.v_compute([-1,0,5,10,11])).to.be.instanceof(Float64Array)
    })

    it("should inverse map values linearly", () => {
      expect(scale.invert(14)).to.be.equal(-1)
      expect(scale.invert(20)).to.be.equal(0)
      expect(scale.invert(50)).to.be.equal(5)
      expect(scale.invert(80)).to.be.equal(10)
      expect(scale.invert(86)).to.be.equal(11)
    })

    it("should vector in inverse map values linearly", () => {
      expect(scale.v_invert([14,20,50,80,86])).to.be.deep.equal(new Float64Array([-1,0,5,10,11]))
    })

    it("should inverse map to a Float64Array", () => {
      expect(scale.v_invert([-1,0,5,10,11])).to.be.instanceof(Float64Array)
    })
  })
})


text:
from datetime import datetime

from django.test import TestCase

from django.db import IntegrityError

from sendinel import settings
from sendinel.backend.models import Hospital

class HospitalTest(TestCase):
    fixtures = ['backend_test']

    def test_get_hospital_no_hospital(self):
        Hospital.objects.all().delete()
        hospital = Hospital.get_current_hospital()
        self.assertTrue(1, Hospital.objects.all().count())
        self.assertEquals(Hospital.objects.all()[0].name, settings.DEFAULT_HOSPITAL_NAME)
        self.assertEquals(hospital.name, settings.DEFAULT_HOSPITAL_NAME)

    def test_get_hospital_with_hospital(self):
        hospital = Hospital.objects.get(current_hospital = True)
        self.assertEquals(Hospital.get_current_hospital(), hospital)


text:
package com.jamesmorrisstudios.appbaselibrary;

import android.content.res.Configuration;
import android.support.annotation.NonNull;

import com.jamesmorrisstudios.appbaselibrary.app.AppBase;

import java.util.Locale;

/**
 * User Locale functions
 * <p/>
 * Created by James on 12/8/2015.
 */
public final class UtilsLocale {
    private static Locale backupLocale = null;

    /**
     * Restores to the previous locale if one is set
     */
    public static void restoreLocale() {
        if (backupLocale != null) {
            setLocale(backupLocale);
        }
    }

    /**
     * @param localeName Locale name to set to
     */
    public static void setLocale(@NonNull final String localeName) {
        Locale locale = new Locale(localeName);
        setLocale(locale);
    }

    /**
     * @return The current locale
     */
    @NonNull
    public static Locale getLocale() {
        return Locale.getDefault();
    }

    /**
     * @param locale Locale to set to
     */
    public static void setLocale(@NonNull final Locale locale) {
        if (backupLocale == null) {
            backupLocale = Locale.getDefault();
        }
        Locale.setDefault(locale);
        Configuration config2 = new Configuration();
        config2.locale = locale;
        AppBase.getContext().getResources().updateConfiguration(config2, AppBase.getContext().getResources().getDisplayMetrics());
    }

}


text:
<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;
/**
 * This is the model class for table "docs".
 *
 * @property string $doc_id
 * @property string $title
 * @property integer $topic_id
 * @property string $file
 * @property integer $country_id
 * @property integer $session_id
 * @property string $date_council
 *
 * @property Audits[] $audits
 * @property Sessions $session
 * @property Countries $country
 * @property Topics $topic
 */
class Docs extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'docs';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'topic_id', 'country_id', 'session_id','date_council'], 'required'],
            ['file','required', 'on'=>'create'],
            [['topic_id', 'country_id', 'session_id'], 'integer'],
            [['file'], 'file', 'extensions' => 'doc, docx, pdf'],
            [['title'], 'string', 'max' => 255]
        ];
    }

    public function scenarios() {
        $scenarios = parent::scenarios();
        $scenarios['update'] = ['title', 'topic_id', 'country_id', 'session_id','date_council'];
        return $scenarios;
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'doc_id' => 'Doc ID',
            'title' => 'Title',
            'topic_id' => 'Topic',
            'file' => 'File',
            'country_id' => 'Country',
            'session_id' => 'Session',
            'date_council' => 'Date',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAudits()
    {
        return $this->hasMany(Audits::className(), ['doc_id' => 'doc_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSessions()
    {
        return $this->hasOne(Sessions::className(), ['session_id' => 'session_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCountries()
    {
        return $this->hasOne(Countries::className(), ['country_id' => 'country_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTopics()
    {
        return $this->hasOne(Topics::className(), ['topic_id' => 'topic_id']);
    }
}


text:
using System;
using TrueCraft.Client.Input;
using Microsoft.Xna.Framework;

namespace TrueCraft.Client.Modules
{
    public abstract class InputModule : IInputModule
    {
        public virtual bool KeyDown(GameTime gameTime, KeyboardKeyEventArgs e)
        {
            return false;
        }

        public virtual bool KeyUp(GameTime gameTime, KeyboardKeyEventArgs e)
        {
            return false;
        }

        public virtual bool MouseMove(GameTime gameTime, MouseMoveEventArgs e)
        {
            return false;
        }

        public virtual bool MouseButtonDown(GameTime gameTime, MouseButtonEventArgs e)
        {
            return false;
        }

        public virtual bool MouseButtonUp(GameTime gameTime, MouseButtonEventArgs e)
        {
            return false;
        }

        public virtual bool MouseScroll(GameTime gameTime, MouseScrollEventArgs e)
        {
            return false;
        }

        public virtual bool GamePadButtonDown(GameTime gameTime, GamePadButtonEventArgs e)
        {
            return false;
        }

        public virtual bool GamePadButtonUp(GameTime gameTime, GamePadButtonEventArgs e)
        {
            return false;
        }

        public virtual void Update(GameTime gameTime)
        {
        }
    }
}


text:
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/

(function (Drupal, Backbone) {
  Drupal.contextualToolbar.StateModel = Backbone.Model.extend({
    defaults: {
      isViewing: true,
      isVisible: false,
      contextualCount: 0,
      tabbingContext: null
    },
    initialize: function initialize(attrs, options) {
      this.listenTo(options.contextualCollection, 'reset remove add', this.countContextualLinks);
      this.listenTo(options.contextualCollection, 'add', this.lockNewContextualLinks);
      this.listenTo(this, 'change:contextualCount', this.updateVisibility);
      this.listenTo(this, 'change:isViewing', function (model, isViewing) {
        options.contextualCollection.each(function (contextualModel) {
          contextualModel.set('isLocked', !isViewing);
        });
      });
    },
    countContextualLinks: function countContextualLinks(contextualModel, contextualCollection) {
      this.set('contextualCount', contextualCollection.length);
    },
    lockNewContextualLinks: function lockNewContextualLinks(contextualModel, contextualCollection) {
      if (!this.get('isViewing')) {
        contextualModel.set('isLocked', true);
      }
    },
    updateVisibility: function updateVisibility() {
      this.set('isVisible', this.get('contextualCount') > 0);
    }
  });
})(Drupal, Backbone);


text:
package java7.autoclose;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class AutocloseDemo {

    String readFirstLine_priorToJava7(String path) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            return br.readLine();
        } finally {
            if (br != null) br.close();
        }
    }

    String readFirstLine_java7(String path) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        }
    }

    public void writeToFileZipFileContents(String src, String out) throws IOException {
        Charset charset = java.nio.charset.StandardCharsets.US_ASCII;
        Path outputFilePath = java.nio.file.Paths.get(out);

        try (
                ZipFile zf = new ZipFile(src);
                BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset)
        ) {
            for (Enumeration entries = zf.entries(); entries.hasMoreElements(); ) {
                String newLine = System.getProperty("line.separator");
                String zipEntryName = ((ZipEntry) entries.nextElement()).getName() + newLine;
                writer.write(zipEntryName, 0, zipEntryName.length());
            }
        }
    }

    public void custom1() {
//        try(String str = "abc") {}

        try (MyResource res1 = new MyResource()) {
            System.out.println(res1);
        }
    }

    public void custom() {
        System.out.println("001");
        try (MyResource res = new MyResource()) {
            System.out.println(res);
        } catch (Exception e) {
            System.out.println("002");
            e.printStackTrace();
        } finally {
            System.out.println("003");
        }
        System.out.println("004");
    }
    /*
    001
    java7.autoclose.MyResource@66d3c617
    MyResource close()
    003
    004
     */

    public static void main(String[] args) {
        AutocloseDemo obj = new AutocloseDemo();
        obj.custom();
    }

}

class MyResource implements AutoCloseable {
    String member = "xxx";

    @Override
    public void close() {
        member = null;
        System.out.println("MyResource close()");
    }

    // 另一可能 public void close() throws Exception {
}


text:
package com.tinkerpop.blueprints.impls.orient;

import com.tinkerpop.blueprints.Graph;
import org.hamcrest.core.AnyOf;
import org.hamcrest.core.IsEqual;
import org.junit.Assume;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * @author Andrey Lomakin (a.lomakin-at-orientechnologies.com)
 * @since 2/6/14
 */
@RunWith(JUnit4.class)
public class OrientGraphDefaultRemoteTest extends OrientGraphRemoteTest {
  @Before
  public void setUp() throws Exception {
    Assume.assumeThat(getEnvironment(), AnyOf.anyOf(IsEqual.equalTo(ENV.CI), IsEqual.equalTo(ENV.RELEASE)));
    super.setUp();
  }

  public Graph generateGraph(final String graphDirectoryName) {
    OrientGraph graph = (OrientGraph) super.generateGraph(graphDirectoryName);
    graph.setUseLightweightEdges(true);

    if (graph.getEdgeType("friend") == null)
      graph.createEdgeType("friend");
    if (graph.getEdgeType("test") == null)
      graph.createEdgeType("test");
    if (graph.getEdgeType("knows") == null)
      graph.createEdgeType("knows");
    if (graph.getEdgeType("created") == null)
      graph.createEdgeType("created");
    if (graph.getEdgeType("collaborator") == null)
      graph.createEdgeType("collaborator");
    if (graph.getEdgeType("hate") == null)
      graph.createEdgeType("hate");
    if (graph.getEdgeType("hates") == null)
      graph.createEdgeType("hates");
    if (graph.getEdgeType("test-edge") == null)
      graph.createEdgeType("test-edge");
    if (graph.getEdgeType("self") == null)
      graph.createEdgeType("self");
    if (graph.getEdgeType("x") == null)
      graph.createEdgeType("x");
    if (graph.getEdgeType("y") == null)
      graph.createEdgeType("y");
    if (graph.getEdgeType("test1") == null)
      graph.createEdgeType("test1");
    if (graph.getEdgeType("test2") == null)
      graph.createEdgeType("test2");
    if (graph.getEdgeType("test3") == null)
      graph.createEdgeType("test3");

    return graph;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="24"
    android:viewportWidth="24">
    <path
        android:fillColor="#ff000000"
        android:pathData="M20,9H4v2h16V9zM4,15h16v-2H4v2z"/>

</vector>


text:
author: Ruiwen
categories:
  - Chatter
comments: true
date: 2009-09-02T00:00:00.000Z
title: '[Poll] Trouble FLOSSing in NUS?'
url: /2009/09/trouble-flossing-in-nus/
aliases:
  - /2009/09/02/trouble-flossing-in-nus/
---

All right, I'll cut right to the chase with this one, and won't pull any punches. Let me be the first to say, It can be a pain trying to use only Free and open source software.

There. I've said it. Now I await the pitchforks.

Before you toss me into the vat of boiling oil for heresy, however, hear me out. We've all been in this fix before. We really, really, want to use only open source software, but there are just so many things that stand in our way.  That YouTube video your friends are laughing over? That's proprietary Flash all right. That cool new game everyone's been playing? Chances are (but not quite),  that it runs only on Windows.

Things get worse when you're put into situations that are completely out of your control. In NUS, we most often run into such situations in the courses that we take. Perhaps the lecturer wants the class to use some software that only available on a closed platform. Or he wants you to develop code in a proprietary language. Or perhaps he just insists on sending out .pptx files. Every. Single. Time.

What's an open source geek to do? Good question, we're stumped too!

So here's the deal, if you'd ever faced a dilemma like that in NUS, we want to know! What situation were you put in, by whom, and how (if at all) you managed to get around that. Drop us a note in the comments, and we'll collate the results for a nice fancy table in a follow-up.

Oh, and general comments welcome too, of course.


text:
import {action, comparer, computed, Lambda, observable, reaction, runInAction} from "mobx";
import {Component, ReactElement} from "react";
import {v4} from "uuid";

import {classAutorun, messageStore} from "@focus4/core";
import {
    AutocompleteProps,
    AutocompleteResult,
    DisplayProps,
    fieldFor,
    FieldOptions,
    Form,
    InputProps,
    LabelProps,
    PanelProps,
    SelectProps
} from "@focus4/forms";
import {
    BaseAutocompleteProps,
    BaseDisplayProps,
    BaseInputProps,
    BaseLabelProps,
    BaseSelectProps,
    DomainType,
    EntityField,
    FieldEntry,
    fromField,
    isStoreListNode,
    Metadata,
    ReferenceList,
    StoreListNode,
    StoreNode,
    toFlatValues
} from "@focus4/stores";

import {fieldWrapperFor} from "./field-wrapper";
import {createViewModel, ViewModel} from "./view-model";

/** Options additionnelles de l'AutoForm. */
export interface AutoFormOptions<ST extends StoreNode | StoreListNode> {
    /** Pour ajouter une classe particulière sur le formulaire. */
    className?: string;

    /** ViewModel externe de `storeData`, s'il y a besoin d'externaliser le state interne du formulaire. */
    entity?: ST & ViewModel;

    /** Par défaut: true */
    hasForm?: boolean;

    /** Préfixe i18n pour les messages du formulaire (par défaut: "focus") */
    i18nPrefix?: string;

    /** Par défaut: false */
    initiallyEditing?: boolean;
}

/** Config de services à fournir à AutoForm. */
export interface ServiceConfig<T, LP> {
    /** Service de suppression. */
    delete?: (entity: T) => Promise<void | number | boolean>;

    /** Fonction pour récupérer la liste des paramètres pour le service de chargement. Si le résultat contient des observables, le service de chargement sera rappelé à chaque modification. */
    getLoadParams?: () => LP[] | undefined;

    /** Service de chargement. */
    load?: (...args: LP[]) => Promise<T>;

    /** Service de sauvegarde. Obligatoire. */
    save: (entity: T) => Promise<T>;
}

/** Classe de base pour un créer un composant avec un formulaire. A n'utiliser QUE pour des formulaires (avec de la sauvegarde). */
export abstract class AutoForm<P, ST extends StoreNode | StoreListNode> extends Component<P> {
    /** Map de tous les formulaires actuellement affichés avec leur état en édition */
    static readonly editingMap = observable.map<string, boolean>();

    /** Précise si au moins un formulaire de l'application est en édition. */
    @computed
    static get isOneEdit() {
        return Array.from(AutoForm.editingMap.values()).some(x => x);
    }

    /** Identifiant unique du formulaire. */
    formId = v4();

    /** Etat courant du formulaire, copié depuis `storeData`. Sera réinitialisé à chaque modification de ce dernier. */
    entity!: ST & ViewModel;

    /** Services. */
    services!: ServiceConfig<any, any>;

    /** Noeud de store à partir du quel le formulaire a été créé. */
    storeData!: ST;

    /** Erreurs sur les champs. */
    readonly errors = new Map<string, string | undefined>();

    /** Force l'affichage des erreurs. */
    @observable forceErrorDisplay = false;

    /** Formulaire en édition. */
    @observable isEdit!: boolean;

    /** Formulaire en chargement. */
    @observable isLoading = false;

    /** Classe CSS additionnelle (passée en options). */
    private className!: string;

    /** Insère ou non un formulaire HTML. */
    private hasForm!: boolean;

    /** Préfixe i18n pour les messages du formulaire */
    private i18nPrefix!: string;

    /** Utilise ou non un ViewModel personnalisé, passé en options. */
    private isCustomEntity!: boolean;

    /** Disposer de la réaction de chargement. */
    private loadDisposer?: Lambda;

    /**
     * A implémenter pour initialiser le formulaire. Il faut appeler `this.formInit` à l'intérieur.
     *
     * Sera appelé pendant `componentWillMount` avant le chargement.
     */
    abstract init(): void;

    /**
     * Initialise le formulaire.
     * @param storeData L'EntityStoreData de base du formulaire.
     * @param services La config de services pour le formulaire ({delete?, getLoadParams, load, save}).
     * @param options Options additionnelles.
     */
    formInit(
        storeData: ST,
        services: ServiceConfig<any, any>,
        {entity, className, hasForm, i18nPrefix, initiallyEditing}: AutoFormOptions<ST> = {}
    ) {
        this.storeData = storeData;
        this.services = services;
        this.entity = entity || createViewModel(storeData);
        this.isCustomEntity = entity !== undefined;
        this.isEdit = initiallyEditing || false;
        this.hasForm = hasForm ?? true;
        this.className = className || "";
        this.i18nPrefix = i18nPrefix || "focus";

        // On met en place la réaction de chargement.
        if (services.getLoadParams) {
            this.loadDisposer = reaction(services.getLoadParams, () => this.load(), {equals: comparer.structural});
        }
    }

    componentWillMount() {
        this.init();
        AutoForm.editingMap.set(this.formId, this.isEdit);
        this.entity.subscribe(); // On force l'abonnement à `this.storeData` au cas-où.
        this.load();
    }

    componentWillUnmount() {
        AutoForm.editingMap.delete(this.formId);
        if (!this.isCustomEntity) {
            this.entity.unsubscribe();
        }
        if (this.loadDisposer) {
            this.loadDisposer();
        }
    }

    /** Change le mode du formulaire. */
    @action
    toggleEdit(isEdit: boolean) {
        this.isEdit = isEdit;
        if (!isEdit) {
            this.entity.reset();
        }
    }

    @classAutorun protected updateApplicationStore() {
        AutoForm.editingMap.set(this.formId, this.isEdit);
    }

    /** Appelle le service de suppression. */
    @action
    async delete() {
        if (this.services.delete) {
            this.isLoading = true;
            await this.services.delete(toFlatValues(this.entity));
            runInAction(() => {
                this.isLoading = false;
                this.storeData.clear();
            });
            this.onFormDeleted();
        }
    }

    /** Appelle le service de chargement (appelé par la réaction de chargement). */
    @action
    async load() {
        const {getLoadParams, load} = this.services;

        // On n'effectue le chargement que si on a un service de chargement et des paramètres pour le service.
        if (getLoadParams && load) {
            const params = getLoadParams();
            if (params) {
                this.isLoading = true;
                this.storeData.clear();
                const data = await load(...params);
                runInAction(() => {
                    if (isStoreListNode(this.storeData)) {
                        this.storeData.replaceNodes(data || []);
                    } else {
                        this.storeData.replace(data || {});
                    }
                    this.isLoading = false;
                });
                this.onFormLoaded();
            }
        }
    }

    /** Appelle le service de sauvegarde. */
    @action
    async save() {
        // On ne sauvegarde que si la validation est en succès.
        if (this.validate()) {
            this.isLoading = true;
            try {
                const data = await this.services.save(toFlatValues(this.entity));
                runInAction(() => {
                    this.isLoading = false;
                    this.isEdit = false;
                    // En sauvegardant le retour du serveur dans le noeud de store, l'état du formulaire va se réinitialiser.
                    if (isStoreListNode(this.storeData)) {
                        this.storeData.replaceNodes(data);
                    } else {
                        this.storeData.replace(data);
                    }
                });
                this.onFormSaved();
            } catch (e) {
                runInAction(() => {
                    this.isLoading = false;
                });
            }
        }
    }

    /** Est appelé après la suppression. */
    onFormDeleted() {
        messageStore.addSuccessMessage(`${this.i18nPrefix}.detail.deleted`);
    }

    /** Est appelé après le chargement. */
    onFormLoaded() {
        // A éventuellement surcharger.
    }

    /** Est appelé après la sauvegarde. */
    onFormSaved() {
        messageStore.addSuccessMessage(`${this.i18nPrefix}.detail.saved`);
    }

    /**
     * Valide les différents champs du formulaire.
     *
     * Surcharger la méthode pour ajouter une validation personnalisée.
     */
    @action
    validate() {
        // On force en premier lieu l'affichage des erreurs sur tous les champs.
        this.forceErrorDisplay = true;

        // La validation est en succès si chaque champ n'est pas en erreur.
        return !Array.from(this.errors.values()).some(e => !!e);
    }

    /** Récupère les props à fournir à un Panel pour relier ses boutons au formulaire. */
    getPanelProps(): PanelProps {
        return {
            editing: this.isEdit,
            loading: this.isLoading,
            save: () => this.save(),
            onClickCancel: () => this.toggleEdit(false),
            onClickEdit: () => this.toggleEdit(true)
        };
    }

    /** Fonction de rendu du formulaire à préciser. */
    abstract renderContent(): ReactElement | null;
    render() {
        return (
            <Form
                forceErrorDisplay={this.forceErrorDisplay}
                noForm={!this.hasForm}
                theme={{form: this.className}}
                save={() => this.save()}
            >
                {this.renderContent()}
            </Form>
        );
    }

    /**
     * Crée un champ standard en lecture seule.
     * @param field La définition de champ.
     * @param options Les options du champ.
     */
    displayFor<
        DT extends "string" | "number" | "boolean" | "object",
        T extends DomainType<DT>,
        DCDProps extends BaseDisplayProps = DisplayProps,
        LCDProps extends BaseLabelProps = LabelProps,
        DCProps extends BaseDisplayProps = DCDProps,
        LCProps extends BaseLabelProps = LCDProps
    >(
        field: EntityField<FieldEntry<DT, T, any, any, any, DCDProps, LCDProps>>,
        options: FieldOptions<FieldEntry<DT, T, any, any, any, DCDProps, LCDProps>> &
            Metadata<T, any, any, any, DCProps, LCProps> = {}
    ): JSX.Element {
        const {
            AutocompleteComponent,
            DisplayComponent,
            InputComponent,
            LabelComponent,
            SelectComponent,
            displayFormatter,
            label,
            validator,
            ...fieldOptions
        } = options;
        return fieldFor(
            fromField(field, {
                DisplayComponent: DisplayComponent ?? (field.$field.domain.DisplayComponent as any),
                displayFormatter: displayFormatter ?? field.$field.domain.displayFormatter,
                label: label ?? field.$field.label
            }),
            fieldOptions as any
        );
    }

    /**
     * Crée un champ autocomplete.
     * @param field La définition de champ.
     * @param options Les options du champ.
     */
    autocompleteFor<
        DT extends "string" | "number" | "boolean" | "object",
        T extends DomainType<DT>,
        ACDProps extends BaseAutocompleteProps = AutocompleteProps<DT extends "number" ? "number" : "string">,
        DCDProps extends BaseDisplayProps = DisplayProps,
        LCDProps extends BaseLabelProps = LabelProps,
        ACProps extends BaseAutocompleteProps = ACDProps,
        DCProps extends BaseDisplayProps = DCDProps,
        LCProps extends BaseLabelProps = LCDProps
    >(
        field: EntityField<FieldEntry<DT, T, any, any, ACDProps, DCDProps, LCDProps>>,
        options: FieldOptions<FieldEntry<DT, T, any, any, ACDProps, DCDProps, LCDProps>> &
            Metadata<T, any, any, ACProps, DCProps, LCProps> & {
                error?: string;
                isEdit?: boolean;
                name?: string;
                keyResolver?: (key: number | string) => Promise<string | undefined>;
                querySearcher?: (text: string) => Promise<AutocompleteResult | undefined>;
            } = {}
    ): JSX.Element {
        const {name, ...o} = options;
        return fieldWrapperFor(
            "autocomplete",
            field,
            this.isEdit,
            e => this.errors.set(name ?? field.$field.name, e),
            o as any
        );
    }

    /**
     * Crée un champ standard.
     * @param field La définition de champ.
     * @param options Les options du champ.
     */
    fieldFor<
        DT extends "string" | "number" | "boolean" | "object",
        T extends DomainType<DT>,
        ICDProps extends BaseInputProps = InputProps<DT extends number ? "number" : "string">,
        DCDProps extends BaseDisplayProps = DisplayProps,
        LCDProps extends BaseLabelProps = LabelProps,
        ICProps extends BaseInputProps = ICDProps,
        DCProps extends BaseDisplayProps = DCDProps,
        LCProps extends BaseLabelProps = LCDProps
    >(
        field: EntityField<FieldEntry<DT, T, ICDProps, any, any, DCDProps, LCDProps>>,
        options: FieldOptions<FieldEntry<DT, T, ICDProps, any, any, DCDProps, LCDProps>> &
            Metadata<T, ICProps, any, any, DCProps, LCProps> & {
                error?: string;
                isEdit?: boolean;
                name?: string;
            } = {}
    ): JSX.Element {
        const {name, ...o} = options;
        return fieldWrapperFor(
            "input",
            field,
            this.isEdit,
            e => this.errors.set(name ?? field.$field.name, e),
            o as any
        );
    }

    /**
     * Crée un champ select.
     * @param field La définition de champ.
     * @param values Liste de référence.
     * @param options Les options du champ.
     */
    selectFor<
        DT extends "string" | "number" | "boolean" | "object",
        T extends DomainType<DT>,
        SCDProps extends BaseSelectProps = SelectProps<DT extends "number" ? "number" : "string">,
        DCDProps extends BaseDisplayProps = DisplayProps,
        LCDProps extends BaseLabelProps = LabelProps,
        SCProps extends BaseSelectProps = SCDProps,
        DCProps extends BaseDisplayProps = DCDProps,
        LCProps extends BaseLabelProps = LCDProps
    >(
        field: EntityField<FieldEntry<DT, T, any, SCDProps, any, DCDProps, LCDProps>>,
        values: ReferenceList,
        options: FieldOptions<FieldEntry<DT, T, any, SCDProps, any, DCDProps, LCDProps>> &
            Metadata<T, any, SCProps, any, DCProps, LCProps> & {
                error?: string;
                isEdit?: boolean;
                name?: string;
            } = {}
    ): JSX.Element {
        const {name, ...o} = options;
        return fieldWrapperFor(
            "select",
            field,
            this.isEdit,
            e => this.errors.set(name ?? field.$field.name, e),
            o as any,
            values
        );
    }
}


text:
Controller::Controller()
{
}

void Controller::setup()
{
  EventController::event_controller.setup();

  // Pin Setup
  for (uint8_t relay=0; relay<constants::RELAY_COUNT; ++relay)
  {
    pinMode(constants::relay_pins[relay],OUTPUT);
    openRelay(relay);
  }
  setAllPwmStatusStopped();

  // Setup Streams
  Serial.begin(constants::baudrate);

}

void Controller::update()
{
  // Check if message is available
  while (Serial.available() > 0)
  {
    serial_receiver_.process(Serial.read());
    if (serial_receiver_.messageReady())
    {
      processMessage();
      serial_receiver_.reset();
    }
  }
}

SerialReceiver& Controller::getSerialReceiver()
{
  return serial_receiver_;
}

void Controller::closeRelay(int relay)
{
  digitalWrite(constants::relay_pins[relay],HIGH);
  power_[relay] = constants::power_max;
}

void Controller::openRelay(int relay)
{
  digitalWrite(constants::relay_pins[relay],LOW);
  power_[relay] = constants::power_min;
}

void Controller::setRelayPower(int relay, int power)
{
  if (power >= constants::power_max)
  {
    closeRelay(relay);
  }
  else
  {
    analogWrite(constants::relay_pins[relay],power);
    power_[relay] = power;
  }
}

void Controller::openAllRelays()
{
  for (uint8_t relay=0; relay<constants::RELAY_COUNT; ++relay)
  {
    openRelay(relay);
  }
}

void Controller::setPwmStatusRunning(int relay, int level)
{
  pwm_status_[relay][level] = constants::PWM_RUNNING;
}

void Controller::setPwmStatusStopped(int relay, int level)
{
  pwm_status_[relay][level] = constants::PWM_STOPPED;
}

void Controller::setAllPwmStatusStopped()
{
  for (uint8_t relay=0; relay<constants::RELAY_COUNT; ++relay)
  {
    for (uint8_t level=0; level<=constants::PWM_LEVEL_COUNT_MAX; ++level)
    {
      setPwmStatusStopped(relay,level);
    }
  }
}

int Controller::getPower(int relay)
{
  return power_[relay];
}

constants::PwmStatus Controller::getPwmStatus(int relay, int level)
{
  return pwm_status_[relay][level];
}

void Controller::processMessage()
{
  int method_id;

  method_id = serial_receiver_.readInt(0);

  switch (method_id)
  {
    case constants::METHOD_ID_START_PWM:
      callbacks::startPwmCallback();
      break;
    case constants::METHOD_ID_STOP_ALL_PULSES:
      callbacks::stopAllPwmCallback();
      break;
    case constants::METHOD_ID_GET_POWER:
      callbacks::getPowerCallback();
      break;
    case constants::METHOD_ID_GET_PWM_STATUS:
      callbacks::getPwmStatusCallback();
      break;
    default:
      break;
  }
}

Controller controller;