text:
import datetime

from exchangelib.errors import (
    ErrorInvalidOperation,
    ErrorInvalidRecipients,
    ErrorItemNotFound,
    ErrorMissingInformationReferenceItemId,
)
from exchangelib.ewsdatetime import UTC
from exchangelib.fields import MONDAY, NOVEMBER, THIRD, WEDNESDAY, WEEK_DAY, WEEKEND_DAY
from exchangelib.folders import Calendar
from exchangelib.items import BulkCreateResult, CalendarItem
from exchangelib.items.calendar_item import EXCEPTION, OCCURRENCE, RECURRING_MASTER, SINGLE, AcceptItem, MeetingRequest
from exchangelib.recurrence import (
    AbsoluteMonthlyPattern,
    AbsoluteYearlyPattern,
    DailyPattern,
    DeletedOccurrence,
    FirstOccurrence,
    LastOccurrence,
    Occurrence,
    Recurrence,
    RelativeMonthlyPattern,
    RelativeYearlyPattern,
    WeeklyPattern,
)
from exchangelib.version import EXCHANGE_2007, Version

from ..common import get_random_date, get_random_datetime_range, get_random_string
from .test_basics import CommonItemTest

class CalendarTest(CommonItemTest):
    TEST_FOLDER = "calendar"
    FOLDER_CLASS = Calendar
    ITEM_CLASS = CalendarItem

    def match_cat(self, i):
        if isinstance(i, Exception):
            return False
        return set(i.categories or []) == set(self.categories)

    def test_cancel(self):
        item = self.get_test_item().save()
        try:
            res = item.cancel()  # Returns (id, changekey) of cancelled item
        except ErrorInvalidRecipients:
            # Does not always work in a single-account setup
            pass
        else:
            self.assertIsInstance(res, BulkCreateResult)
            with self.assertRaises(ErrorItemNotFound):
                # Item is already cancelled
                item.cancel()

    def test_updating_timestamps(self):
        # Test that we can update an item without changing anything, and maintain the hidden timezone fields as local
        # timezones, and that returned timestamps are in UTC.
        item = self.get_test_item()
        item.reminder_is_set = True
        item.is_all_day = False
        item.recurrence = None
        item.save()
        item.refresh()
        self.assertEqual(item.type, SINGLE)
        for i in self.account.calendar.filter(categories__contains=self.categories).only("start", "end", "categories"):
            self.assertEqual(i.start, item.start)
            self.assertEqual(i.start.tzinfo, UTC)
            self.assertEqual(i.end, item.end)
            self.assertEqual(i.end.tzinfo, UTC)
            self.assertEqual(i._start_timezone, self.account.default_timezone)
            self.assertEqual(i._end_timezone, self.account.default_timezone)
            i.save(update_fields=["start", "end"])
            self.assertEqual(i.start, item.start)
            self.assertEqual(i.start.tzinfo, UTC)
            self.assertEqual(i.end, item.end)
            self.assertEqual(i.end.tzinfo, UTC)
            self.assertEqual(i._start_timezone, self.account.default_timezone)
            self.assertEqual(i._end_timezone, self.account.default_timezone)
        for i in self.account.calendar.filter(categories__contains=self.categories).only("start", "end", "categories"):
            self.assertEqual(i.start, item.start)
            self.assertEqual(i.start.tzinfo, UTC)
            self.assertEqual(i.end, item.end)
            self.assertEqual(i.end.tzinfo, UTC)
            self.assertEqual(i._start_timezone, self.account.default_timezone)
            self.assertEqual(i._end_timezone, self.account.default_timezone)
            i.delete()

    def test_update_to_non_utc_datetime(self):
        # Test updating with non-UTC datetime values. This is a separate code path in UpdateItem code
        item = self.get_test_item()
        item.reminder_is_set = True
        item.is_all_day = False
        item.save()
        # Update start, end and recurrence with timezoned datetimes. For some reason, EWS throws
        # 'ErrorOccurrenceTimeSpanTooBig' is we go back in time.
        start = get_random_date(start_date=item.start.date() + datetime.timedelta(days=1))
        dt_start, dt_end = [
            dt.astimezone(self.account.default_timezone)
            for dt in get_random_datetime_range(start_date=start, end_date=start, tz=self.account.default_timezone)
        ]
        item.start, item.end = dt_start, dt_end
        item.recurrence.boundary.start = dt_start.date()
        item.save()
        item.refresh()
        self.assertEqual(item.start, dt_start)
        self.assertEqual(item.end, dt_end)

    def test_all_day_datetimes(self):
        # Test that we can use plain dates for start and end values for all-day items
        start = get_random_date()
        start_dt, end_dt = get_random_datetime_range(
            start_date=start, end_date=start + datetime.timedelta(days=365), tz=self.account.default_timezone
        )
        # Assign datetimes for start and end
        item = self.ITEM_CLASS(
            folder=self.test_folder, start=start_dt, end=end_dt, is_all_day=True, categories=self.categories
        ).save()

        # Returned item start and end values should be EWSDate instances
        item = self.test_folder.all().only("is_all_day", "start", "end").get(id=item.id, changekey=item.changekey)
        self.assertEqual(item.is_all_day, True)
        self.assertEqual(item.start, start_dt.date())
        self.assertEqual(item.end, end_dt.date())
        item.save()  # Make sure we can update
        item.delete()

        # We are also allowed to assign plain dates as values for all-day items
        item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start_dt.date(),
            end=end_dt.date(),
            is_all_day=True,
            categories=self.categories,
        ).save()

        # Returned item start and end values should be EWSDate instances
        item = self.test_folder.all().only("is_all_day", "start", "end").get(id=item.id, changekey=item.changekey)
        self.assertEqual(item.is_all_day, True)
        self.assertEqual(item.start, start_dt.date())
        self.assertEqual(item.end, end_dt.date())
        item.save()  # Make sure we can update

    def test_view(self):
        item1 = self.ITEM_CLASS(
            account=self.account,
            folder=self.test_folder,
            subject=get_random_string(16),
            start=datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone),
            end=datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone),
            categories=self.categories,
        )
        item2 = self.ITEM_CLASS(
            account=self.account,
            folder=self.test_folder,
            subject=get_random_string(16),
            start=datetime.datetime(2016, 2, 1, 8, tzinfo=self.account.default_timezone),
            end=datetime.datetime(2016, 2, 1, 10, tzinfo=self.account.default_timezone),
            categories=self.categories,
        )
        self.test_folder.bulk_create(items=[item1, item2])
        qs = self.test_folder.view(start=item1.start, end=item2.end)

        # Test missing args
        with self.assertRaises(TypeError):
            self.test_folder.view()
        # Test bad args
        with self.assertRaises(ValueError):
            list(self.test_folder.view(start=item1.end, end=item1.start))
        with self.assertRaises(TypeError):
            list(self.test_folder.view(start="xxx", end=item1.end))
        with self.assertRaises(ValueError):
            list(self.test_folder.view(start=item1.start, end=item1.end, max_items=0))

        # Test dates
        self.assertEqual(
            len([i for i in self.test_folder.view(start=item1.start, end=item1.end) if self.match_cat(i)]), 1
        )
        self.assertEqual(
            len([i for i in self.test_folder.view(start=item1.start, end=item2.end) if self.match_cat(i)]), 2
        )
        # Edge cases. Get view from end of item1 to start of item2. Should logically return 0 items, but Exchange wants
        # it differently and returns item1 even though there is no overlap.
        self.assertEqual(
            len([i for i in self.test_folder.view(start=item1.end, end=item2.start) if self.match_cat(i)]), 1
        )
        self.assertEqual(
            len([i for i in self.test_folder.view(start=item1.start, end=item2.start) if self.match_cat(i)]), 1
        )

        # Test max_items
        self.assertEqual(
            len(
                [
                    i
                    for i in self.test_folder.view(start=item1.start, end=item2.end, max_items=9999)
                    if self.match_cat(i)
                ]
            ),
            2,
        )
        self.assertEqual(self.test_folder.view(start=item1.start, end=item2.end, max_items=1).count(), 1)

        # Test client-side ordering
        self.assertListEqual(
            [i.subject for i in qs.order_by("subject") if self.match_cat(i)], sorted([item1.subject, item2.subject])
        )
        # Test client-side ordering on a field with no default value and no default value_cls value
        self.assertListEqual([i.start for i in qs.order_by("-start") if self.match_cat(i)], [item2.start, item1.start])
        # Test client-side ordering on multiple fields. Intentionally sort first on a field where values are equal,
        # to see that we can sort on the 2nd field.
        self.assertListEqual(
            [i.start for i in qs.order_by("categories", "-start") if self.match_cat(i)], [item2.start, item1.start]
        )

        # Test chaining
        self.assertTrue(qs.count() >= 2)
        with self.assertRaises(ErrorInvalidOperation):
            qs.filter(subject=item1.subject).count()  # EWS does not allow restrictions
        self.assertListEqual(
            [i for i in qs.order_by("subject").values("subject") if i["subject"] in (item1.subject, item2.subject)],
            [{"subject": s} for s in sorted([item1.subject, item2.subject])],
        )

    def test_client_side_ordering_on_mixed_all_day_and_normal(self):
        # Test that client-side ordering on start and end fields works for items that are a mix of normal an all-day
        # items. This requires us to compare datetime.datetime -> EWSDate values which is not allowed by default
        # (EWSDate -> datetime.datetime *is* allowed).
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        all_day_date = (start - datetime.timedelta(days=1)).date()
        item1 = self.ITEM_CLASS(
            account=self.account,
            folder=self.test_folder,
            subject=get_random_string(16),
            start=all_day_date,
            end=all_day_date,
            is_all_day=True,
            categories=self.categories,
        )
        item2 = self.ITEM_CLASS(
            account=self.account,
            folder=self.test_folder,
            subject=get_random_string(16),
            start=start,
            end=end,
            categories=self.categories,
        )
        self.test_folder.bulk_create(items=[item1, item2])
        list(self.test_folder.view(start=start - datetime.timedelta(days=1), end=end).order_by("start"))
        list(self.test_folder.view(start=start - datetime.timedelta(days=1), end=end).order_by("-start"))

        # Test that client-side ordering on non-selected fields works
        list(self.test_folder.view(start=start - datetime.timedelta(days=1), end=end).only("end").order_by("start"))
        list(self.test_folder.view(start=start - datetime.timedelta(days=1), end=end).only("end").order_by("-start"))

    def test_all_recurring_pattern_types(self):
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)

        for pattern in (
            AbsoluteYearlyPattern(day_of_month=13, month=NOVEMBER),
            RelativeYearlyPattern(weekday=1, week_number=THIRD, month=11),
            RelativeYearlyPattern(weekday=WEEKEND_DAY, week_number=3, month=11),
            AbsoluteMonthlyPattern(interval=3, day_of_month=13),
            RelativeMonthlyPattern(interval=3, weekday=2, week_number=3),
            RelativeMonthlyPattern(interval=3, weekday=WEEK_DAY, week_number=3),
            WeeklyPattern(interval=3, weekdays=[MONDAY, WEDNESDAY], first_day_of_week=1),
            DailyPattern(interval=1),
        ):
            master_item = self.ITEM_CLASS(
                folder=self.test_folder,
                start=start,
                end=end,
                recurrence=Recurrence(pattern=pattern, start=start.date(), number=4),
                categories=self.categories,
            ).save()
            master_item.refresh()
            self.assertEqual(pattern, master_item.recurrence.pattern)
            master_item.delete()

    def test_recurring_item(self):
        # Create a recurring calendar item. Test that occurrence fields are correct on the master item

        # Create a master item with 4 daily occurrences from 8:00 to 10:00. 'start' and 'end' are values for the first
        # occurrence.
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            recurrence=Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4),
            categories=self.categories,
        ).save()

        master_item.refresh()
        self.assertEqual(master_item.is_recurring, False)
        self.assertEqual(master_item.type, RECURRING_MASTER)
        self.assertIsInstance(master_item.first_occurrence, FirstOccurrence)
        self.assertEqual(master_item.first_occurrence.start, start)
        self.assertEqual(master_item.first_occurrence.end, end)
        self.assertIsInstance(master_item.last_occurrence, LastOccurrence)
        self.assertEqual(master_item.last_occurrence.start, start + datetime.timedelta(days=3))
        self.assertEqual(master_item.last_occurrence.end, end + datetime.timedelta(days=3))
        self.assertEqual(master_item.modified_occurrences, None)
        self.assertEqual(master_item.deleted_occurrences, None)

        # Test occurrences as full calendar items, unfolded from the master
        range_start, range_end = start, end + datetime.timedelta(days=3)
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]
        self.assertEqual(len(unfolded), 4)
        for item in unfolded:
            self.assertEqual(item.type, OCCURRENCE)
            self.assertEqual(item.is_recurring, True)

        first_occurrence = unfolded[0]
        self.assertEqual(first_occurrence.id, master_item.first_occurrence.id)
        self.assertEqual(first_occurrence.start, master_item.first_occurrence.start)
        self.assertEqual(first_occurrence.end, master_item.first_occurrence.end)

        second_occurrence = unfolded[1]
        self.assertEqual(second_occurrence.start, master_item.start + datetime.timedelta(days=1))
        self.assertEqual(second_occurrence.end, master_item.end + datetime.timedelta(days=1))

        third_occurrence = unfolded[2]
        self.assertEqual(third_occurrence.start, master_item.start + datetime.timedelta(days=2))
        self.assertEqual(third_occurrence.end, master_item.end + datetime.timedelta(days=2))

        last_occurrence = unfolded[3]
        self.assertEqual(last_occurrence.id, master_item.last_occurrence.id)
        self.assertEqual(last_occurrence.start, master_item.last_occurrence.start)
        self.assertEqual(last_occurrence.end, master_item.last_occurrence.end)

    def test_change_occurrence(self):
        # Test that we can make changes to individual occurrences and see the effect on the master item.
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            recurrence=Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4),
            categories=self.categories,
        ).save()
        master_item.refresh()

        # Test occurrences as full calendar items, unfolded from the master
        range_start, range_end = start, end + datetime.timedelta(days=3)
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]

        # Change the start and end of the second occurrence
        second_occurrence = unfolded[1]
        second_occurrence.start += datetime.timedelta(hours=1)
        second_occurrence.end += datetime.timedelta(hours=1)
        second_occurrence.save()

        # Test change on the master item
        master_item.refresh()
        self.assertEqual(len(master_item.modified_occurrences), 1)
        modified_occurrence = master_item.modified_occurrences[0]
        self.assertIsInstance(modified_occurrence, Occurrence)
        self.assertEqual(modified_occurrence.id, second_occurrence.id)
        self.assertEqual(modified_occurrence.start, second_occurrence.start)
        self.assertEqual(modified_occurrence.end, second_occurrence.end)
        self.assertEqual(modified_occurrence.original_start, second_occurrence.start - datetime.timedelta(hours=1))
        self.assertEqual(master_item.deleted_occurrences, None)

        # Test change on the unfolded item
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]
        self.assertEqual(len(unfolded), 4)
        self.assertEqual(unfolded[1].type, EXCEPTION)
        self.assertEqual(unfolded[1].start, second_occurrence.start)
        self.assertEqual(unfolded[1].end, second_occurrence.end)
        self.assertEqual(unfolded[1].original_start, second_occurrence.start - datetime.timedelta(hours=1))

    def test_delete_occurrence(self):
        # Test that we can delete an occurrence and see the cange on the master item
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            recurrence=Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4),
            categories=self.categories,
        ).save()
        master_item.refresh()

        # Test occurrences as full calendar items, unfolded from the master
        range_start, range_end = start, end + datetime.timedelta(days=3)
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]

        # Delete the third occurrence
        third_occurrence = unfolded[2]
        third_occurrence.delete()

        # Test change on the master item
        master_item.refresh()
        self.assertEqual(master_item.modified_occurrences, None)
        self.assertEqual(len(master_item.deleted_occurrences), 1)
        deleted_occurrence = master_item.deleted_occurrences[0]
        self.assertIsInstance(deleted_occurrence, DeletedOccurrence)
        self.assertEqual(deleted_occurrence.start, third_occurrence.start)

        # Test change on the unfolded items
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]
        self.assertEqual(len(unfolded), 3)

    def test_change_occurrence_via_index(self):
        # Test updating occurrences via occurrence index without knowing the ID of the occurrence.
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            subject=get_random_string(16),
            recurrence=Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4),
            categories=self.categories,
        ).save()

        # Change the start and end of the second occurrence
        second_occurrence = master_item.occurrence(index=2)
        second_occurrence.start = start + datetime.timedelta(days=1, hours=1)
        second_occurrence.end = end + datetime.timedelta(days=1, hours=1)
        second_occurrence.save(update_fields=["start", "end"])  # Test that UpdateItem works with only a few fields

        second_occurrence = master_item.occurrence(index=2)
        second_occurrence.refresh()
        self.assertEqual(second_occurrence.subject, master_item.subject)
        second_occurrence.start += datetime.timedelta(hours=1)
        second_occurrence.end += datetime.timedelta(hours=1)
        second_occurrence.save(update_fields=["start", "end"])  # Test that UpdateItem works after refresh

        # Test change on the master item
        master_item.refresh()
        self.assertEqual(len(master_item.modified_occurrences), 1)
        modified_occurrence = master_item.modified_occurrences[0]
        self.assertIsInstance(modified_occurrence, Occurrence)
        self.assertEqual(modified_occurrence.id, second_occurrence.id)
        self.assertEqual(modified_occurrence.start, second_occurrence.start)
        self.assertEqual(modified_occurrence.end, second_occurrence.end)
        self.assertEqual(modified_occurrence.original_start, second_occurrence.start - datetime.timedelta(hours=2))
        self.assertEqual(master_item.deleted_occurrences, None)

    def test_delete_occurrence_via_index(self):
        # Test deleting occurrences via occurrence index without knowing the ID of the occurrence.
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            subject=get_random_string(16),
            recurrence=Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4),
            categories=self.categories,
        ).save()

        # Delete the third occurrence
        third_occurrence = master_item.occurrence(index=3)
        third_occurrence.refresh()  # Test that GetItem works

        third_occurrence = master_item.occurrence(index=3)
        third_occurrence.delete()  # Test that DeleteItem works

        # Test change on the master item
        master_item.refresh()
        self.assertEqual(master_item.modified_occurrences, None)
        self.assertEqual(len(master_item.deleted_occurrences), 1)
        deleted_occurrence = master_item.deleted_occurrences[0]
        self.assertIsInstance(deleted_occurrence, DeletedOccurrence)
        self.assertEqual(deleted_occurrence.start, start + datetime.timedelta(days=2))

    def test_get_master_recurrence(self):
        # Test getting the master recurrence via an occurrence
        start = datetime.datetime(2016, 1, 1, 8, tzinfo=self.account.default_timezone)
        end = datetime.datetime(2016, 1, 1, 10, tzinfo=self.account.default_timezone)
        recurrence = Recurrence(pattern=DailyPattern(interval=1), start=start.date(), number=4)
        master_item = self.ITEM_CLASS(
            folder=self.test_folder,
            start=start,
            end=end,
            subject=get_random_string(16),
            recurrence=recurrence,
            categories=self.categories,
        ).save()

        # Get the master from an occurrence
        range_start, range_end = start, end + datetime.timedelta(days=3)
        unfolded = [i for i in self.test_folder.view(start=range_start, end=range_end) if self.match_cat(i)]
        third_occurrence = unfolded[2]
        self.assertEqual(third_occurrence.recurrence, None)
        master_from_occurrence = third_occurrence.recurring_master()

        master_from_occurrence.refresh()  # Test that GetItem works
        self.assertEqual(master_from_occurrence.recurrence, recurrence)
        self.assertEqual(master_from_occurrence.subject, master_item.subject)

        master_from_occurrence = third_occurrence.recurring_master()
        master_from_occurrence.subject = get_random_string(16)
        master_from_occurrence.save(update_fields=["subject"])  # Test that UpdateItem works
        master_from_occurrence.delete()  # Test that DeleteItem works

        with self.assertRaises(ErrorItemNotFound):
            master_item.delete()  # Item is gone from the server, so this should fail
        with self.assertRaises(ErrorItemNotFound):
            third_occurrence.delete()  # Item is gone from the server, so this should fail

    def test_invalid_updateitem_items(self):
        # Test here because CalendarItem is the only item that has a requiref field with no default
        item = self.get_test_item().save()
        with self.assertRaises(ValueError) as e:
            self.account.bulk_update([(item, [])])
        self.assertEqual(e.exception.args[0], "'fieldnames' must not be empty")

        # Test a field that has is_required=True
        start = item.start
        item.start = None
        with self.assertRaises(ValueError) as e:
            self.account.bulk_update([(item, ["start"])])
        self.assertEqual(e.exception.args[0], "'start' is a required field with no default")
        item.start = start

        # Test a field that has is_required_after_safe=True
        uid = item.uid
        item.uid = None
        with self.assertRaises(ValueError) as e:
            self.account.bulk_update([(item, ["uid"])])
        self.assertEqual(e.exception.args[0], "'uid' is a required field and may not be deleted")
        item.uid = uid

        item.is_meeting = None
        with self.assertRaises(ValueError) as e:
            self.account.bulk_update([(item, ["is_meeting"])])
        self.assertEqual(e.exception.args[0], "'is_meeting' is a read-only field")

    def test_meeting_request(self):
        # The test server only has one account so we cannot test meeting invitations
        with self.assertRaises(ValueError) as e:
            MeetingRequest(account=self.account).accept()
        self.assertEqual(e.exception.args[0], "'id' is a required field with no default")
        with self.assertRaises(ValueError) as e:
            MeetingRequest(account=self.account).decline()
        self.assertEqual(e.exception.args[0], "'id' is a required field with no default")
        with self.assertRaises(ValueError) as e:
            MeetingRequest(account=self.account).tentatively_accept()
        self.assertEqual(e.exception.args[0], "'id' is a required field with no default")

        with self.assertRaises(ErrorMissingInformationReferenceItemId) as e:
            AcceptItem(account=self.account).send()

    def test_clean(self):
        start = get_random_date()
        start_dt, end_dt = get_random_datetime_range(
            start_date=start, end_date=start + datetime.timedelta(days=365), tz=self.account.default_timezone
        )
        with self.assertRaises(ValueError) as e:
            CalendarItem(start=end_dt, end=start_dt).clean(version=self.account.version)
        self.assertIn("'end' must be greater than 'start'", e.exception.args[0])

        item = CalendarItem(start=start_dt, end=end_dt)
        item.clean(version=Version(EXCHANGE_2007))
        self.assertEqual(item._meeting_timezone, start_dt.tzinfo)
        self.assertEqual(item._start_timezone, None)
        self.assertEqual(item._end_timezone, None)

    def test_tz_field_for_field_name(self):
        self.assertEqual(
            CalendarItem(account=self.account).tz_field_for_field_name("start").name,
            "_start_timezone",
        )
        self.assertEqual(
            CalendarItem(account=self.account).tz_field_for_field_name("end").name,
            "_end_timezone",
        )
        account = self.get_account()
        account.version = Version(EXCHANGE_2007)
        self.assertEqual(
            CalendarItem(account=account).tz_field_for_field_name("start").name,
            "_meeting_timezone",
        )
        self.assertEqual(
            CalendarItem(account=account).tz_field_for_field_name("end").name,
            "_meeting_timezone",
        )


text:
package interviewPrep

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func levelOrder(root *TreeNode) [][]int {
	output := [][]int{}
	if root == nil {
		return output
	}
	tempQ := []*TreeNode{}
	tempQ = append(tempQ, root, nil)
	level := 0
	for len(tempQ) != 0 {
		// pop node from the queue
		node := tempQ[0]
		tempQ = tempQ[1:]

		// breaking condition
		if node == nil && len(tempQ) == 0 {
			break
		}

		// level check
		if node == nil {
			level++
			tempQ = append(tempQ, nil)
			continue
		}

		if node.Left != nil {
			tempQ = append(tempQ, node.Left)
		}
		if node.Right != nil {
			tempQ = append(tempQ, node.Right)
		}

		if len(output) == level {
			output = append(output, []int{})
		}
		output[level] = append(output[level], node.Val)
	}
	return output
}

redpajama_set_name: RedPajamaGithub


text:
"""
    Kubernetes

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

    OpenAPI spec version: v1.7.4

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_secret_volume_source import V1SecretVolumeSource

class TestV1SecretVolumeSource(unittest.TestCase):
    """ V1SecretVolumeSource unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testV1SecretVolumeSource(self):
        """
        Test V1SecretVolumeSource
        """
        model = kubernetes.client.models.v1_secret_volume_source.V1SecretVolumeSource()

if __name__ == '__main__':
    unittest.main()


text:
package fatSecret;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name="INGREDIENT")
public class Ingredient implements Serializable
{

    private int foodId;
    private String foodName;
//    private String xml = "";
    public Ingredient(int foodId, String foodName)
    {
        this.setFoodId(foodId);
        this.setFoodName(foodName);
    }

    public Ingredient() {
    }

    protected void setFoodId(int foodId) {
        this.foodId = foodId;
    }

    @Id
    @Column(name="FOOD_ID")
    public int getFoodId() {
        return foodId;
    }
    protected void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    public String getFoodName() {
        return foodName;
    }

    @Override
    public String toString() {
        return "Ingredient{" +
                "foodId=" + foodId +
                ", foodName='" + foodName + '\'' +
                '}';
    }
}


text:
package eneru

import (
	"bytes"
	"github.com/stretchr/testify/suite"
	"net/http"
	"net/http/httptest"
	"testing"
)

type UpdateSuite struct {
	suite.Suite
	server *httptest.Server
	client *Client
}

func TestUpdateSuite(t *testing.T) {
	suite.Run(t, &UpdateSuite{})
}

func (t *UpdateSuite) SetupSuite() {
	t.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		encodeResp(w, &UpdateResp{
			Index:   "test",
			Type:    "book",
			ID:      "1",
			Version: 2,
			Created: false,
		})
	}))

	t.client, _ = NewClient(t.server.URL, 512)
}

func (t *UpdateSuite) TearDownSuite() {
	t.server.Close()
}

func (t *UpdateSuite) TestBody() {
	req := t.client.Update("test", "book")
	req.Body(bytes.NewBuffer(nil))
	t.NotNil(req.body)
}

func (t *UpdateSuite) TestDo() {
	j := NewJson(func(j *Json) {
		j.AS("tags", "search", "computer")
	})

	resp, err := t.client.Update("test", "book").ID("1").Body(j).Do()
	t.NoError(err)
	t.Equal(resp.Index, "test")
	t.Equal(resp.Type, "book")
	t.Equal(resp.ID, "1")
	t.NotEqual(resp.Version, 1)
	t.False(resp.Created)
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { useStaticQuery, graphql } from 'gatsby';

import Banner from 'components/ui/Banner';

const HeroBanner = () => {
  const { markdownRemark } = useStaticQuery(graphql`
    query {
      markdownRemark(frontmatter: { category: { eq: "hero section" } }) {
        frontmatter {
          title
          subtitle
          content
          linkTo
          linkText
        }
      }
    }
  `);

  const heroBanner = markdownRemark.frontmatter;

  return (
    <Banner
      title={heroBanner.title}
      subtitle={heroBanner.subtitle}
      content={heroBanner.content}
      linkTo={heroBanner.linkTo}
      linkText={heroBanner.linkText}
    />
  );
};

HeroBanner.propTypes = {
  title: PropTypes.string.isRequired,
  subtitle: PropTypes.string.isRequired,
  content: PropTypes.string.isRequired,
  linkTo: PropTypes.string.isRequired,
  linkText: PropTypes.string.isRequired
};

export default HeroBanner;


text:
package io.opentelemetry.sdk.metrics.internal.exemplar;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.context.Context;

/**
 * Exemplar filters are used to pre-filter measurements before attempting to store them in a
 * reservoir.
 *
 * <p>This class is internal and is hence not for public use. Its APIs are unstable and can change
 * at any time.
 */
public interface ExemplarFilter {
  /** Returns whether or not a reservoir should attempt to filter a measurement. */
  boolean shouldSampleMeasurement(long value, Attributes attributes, Context context);

  /** Returns whether or not a reservoir should attempt to filter a measurement. */
  boolean shouldSampleMeasurement(double value, Attributes attributes, Context context);

  /**
   * A filter that only accepts measurements where there is a {@code Span} in {@link Context} that
   * is being sampled.
   */
  static ExemplarFilter sampleWithTraces() {
    return WithTraceExemplarFilter.INSTANCE;
  }

  /** A filter that accepts any measurement. */
  static ExemplarFilter alwaysSample() {
    return AlwaysSampleFilter.INSTANCE;
  }

  /** A filter that accepts no measurements. */
  static ExemplarFilter neverSample() {
    return NeverSampleFilter.INSTANCE;
  }
}


text:
<?php

function wpfoundation_scripts_with_jquery()
{
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/foundation/js/foundation.js', array( 'jquery' ) );
	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wpfoundation_scripts_with_jquery' );

if ( function_exists('register_sidebar') )
	register_sidebar(array(
		'before_widget' => '',
		'after_widget' => '',
		'before_title' => '
',
		'after_title' => '
',
	));

add_theme_support('menus');

/*
http://codex.wordpress.org/Function_Reference/register_nav_menus#Examples
*/
register_nav_menus(array(
    'top-bar-l' => 'Left Top Bar', // registers the menu in the WordPress admin menu editor
    'top-bar-r' => 'Right Top Bar'
));

/*
http://codex.wordpress.org/Function_Reference/wp_nav_menu
*/
// the left top bar
function foundation_top_bar_l() {
    wp_nav_menu(array(
        'container' => false,                           // remove nav container
        'container_class' => 'menu',           		// class of container
        'menu' => '',                      	        // menu name
        'menu_class' => 'top-bar-menu left',         	// adding custom nav class
        'theme_location' => 'top-bar-l',                // where it's located in the theme
        'before' => '',                                 // before each link
        'after' => '',                                  // after each link
        'link_before' => '',                            // before each link text
        'link_after' => '',                             // after each link text
        'depth' => 5,                                   // limit the depth of the nav
    	'fallback_cb' => false,                         // fallback function (see below)
        'walker' => new top_bar_walker()
	));
} // end left top bar

// the right top bar
function foundation_top_bar_r() {
    wp_nav_menu(array(
        'container' => false,                           // remove nav container
        'container_class' => '',           		// class of container
        'menu' => '',                      	        // menu name
        'menu_class' => 'top-bar-menu right',         	// adding custom nav class
        'theme_location' => 'top-bar-r',                // where it's located in the theme
        'before' => '',                                 // before each link
        'after' => '',                                  // after each link
        'link_before' => '',                            // before each link text
        'link_after' => '',                             // after each link text
        'depth' => 5,                                   // limit the depth of the nav
    	'fallback_cb' => false,                         // fallback function (see below)
        'walker' => new top_bar_walker()
	));
} // end right top bar

/*
Customize the output of menus for Foundation top bar classes
*/

class top_bar_walker extends Walker_Nav_Menu {

    function display_element($element, &$children_elements, $max_depth, $depth=0, $args, &$output) {
        $element->has_children = !empty($children_elements[$element->ID]);
        $element->classes[] = ($element->current || $element->current_item_ancestor) ? 'active' : '';
        $element->classes[] = ($element->has_children) ? 'has-dropdown' : '';

        parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
    }

    function start_el(&$output, $item, $depth, $args) {
        $item_html = '';
        parent::start_el($item_html, $item, $depth, $args);

        $output .= ($depth == 0) ? '

' : '';

        $classes = empty($item->classes) ? array() : (array) $item->classes;

        if(in_array('label', $classes)) {
            $output .= '

';
            $item_html = preg_replace('/]*>(.*)<\/a>/iU', '$1', $item_html);
        }

	if ( in_array('divider', $classes) ) {
		$item_html = preg_replace( '/]*>( .* )<\/a>/iU', '', $item_html );
	}

        $output .= $item_html;
    }

    function start_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "\n
\n";
    }

} // end top bar walker
?>


text:
/**
 * External dependencies
 */
import PropTypes from 'prop-types';
/**
 * A wrapping div with `role="group"` for use in the context menu.
 *
 * @param {Object} props Attributes to pass to the div.
 * @param {string} props.label Accessible label for the group.
 * @return {Node} The react node
 */
function Group({ label, ...props }) {
  return <div role="group" aria-label={label} {...props} />;
}
Group.propTypes = {
  label: PropTypes.string.isRequired,
};

export default Group;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using HighIronRanch.Core;
using HighIronRanch.Core.Helpers;
using HighIronRanch.Core.Repositories;
using HighIronRanch.Core.Services;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;

namespace HighIronRanch.Azure.DocumentDb
{
    public class DocumentDbViewModelRepository : IViewModelRepository
    {
        protected readonly IDocumentDbSettings _settings;
        protected readonly IDocumentDbClientFactory _clientFactory;
        protected readonly ILogger _logger;

        protected readonly IDictionary<Type, Uri> _collectionUris = new Dictionary<Type, Uri>();

        public DocumentDbViewModelRepository(IDocumentDbSettings settings, IDocumentDbClientFactory clientFactory, ILogger logger)
        {
            _settings = settings;
            _clientFactory = clientFactory;
            _logger = logger;
        }

        public class CollectionDoesNotExist : Exception
        {
            public CollectionDoesNotExist(Type type) : base($"Collection {type.Name} does not exist")
            {

            }
        }

        /// <summary>
        /// Verifies the collection exists and throws an exception if it does not.
        /// Marked virtual so a subclass with writing functionality could create the collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected virtual async Task CreateCollectionIfNecessaryAsync<T>()
        {
            var databaseLink = UriFactory.CreateDatabaseUri(_settings.DocumentDbRepositoryDatabaseId);
            var client = await _clientFactory.GetClientAsync(_settings);
            var collection = client.CreateDocumentCollectionQuery(databaseLink)
                                .Where(c => c.Id == typeof(T).Name)
                                .AsEnumerable()
                                .FirstOrDefault();
            if (collection == null)
            {
                _logger.Error(Common.LoggerContext, "Collection {0} does not exist", typeof(T).Name);
                throw new CollectionDoesNotExist(typeof(T));
            }
        }

        protected async Task<Uri> GetCollectionLinkAsync<T>()
        {
            if (!_collectionUris.ContainsKey(typeof (T)))
            {
                await CreateCollectionIfNecessaryAsync<T>();

                _collectionUris[typeof(T)] = UriFactory.CreateCollectionUri(_settings.DocumentDbRepositoryDatabaseId, typeof(T).Name);
            }
            return _collectionUris[typeof(T)];
        }

        protected Uri GetDocumentLink<T>(string documentId)
        {
            return UriFactory.CreateDocumentUri(_settings.DocumentDbRepositoryDatabaseId, typeof (T).Name, documentId);
        }

        public async Task<IQueryable<T>> GetAsync<T>() where T : IViewModel, new()
        {
            try
            {
                var collectionLink = await GetCollectionLinkAsync<T>();
                var client = await _clientFactory.GetClientAsync(_settings);
                var queryable = client.CreateDocumentQuery<T>(collectionLink);
                return queryable;
            }
            catch (Exception)
            {
                return new List<T>().AsQueryable();
            }
        }

        public IQueryable<T> Get<T>() where T : IViewModel, new()
        {
            return AsyncHelpers.RunSync<IQueryable<T>>(() => GetAsync<T>());
        }

        public async Task<T> GetAsync<T>(Guid id) where T : IViewModel, new()
        {
            var documentLink = GetDocumentLink<T>(id.ToString());
            var client = await _clientFactory.GetClientAsync(_settings);
            var response = await client.ReadDocumentAsync(documentLink);
            return JsonConvert.DeserializeObject<T>(response.Resource.ToString());
        }

        public T Get<T>(Guid id) where T : IViewModel, new()
        {
            return AsyncHelpers.RunSync<T>(() => GetAsync<T>(id));
        }
    }

}


text:
package temportalist.esotericraft.galvanization.client

import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.entity.{Render, RenderManager}
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fml.client.registry.IRenderFactory
import net.minecraftforge.fml.relauncher.{Side, SideOnly}
import temportalist.esotericraft.emulation.client.EntityModel
import temportalist.esotericraft.galvanization.common.entity.EntityEmpty

/**
  *
  * Created by TheTemportalist on 5/5/2016.
  *
  * @author TheTemportalist
  */
@SideOnly(Side.CLIENT)
class RenderEmpty(manager: RenderManager) extends Render[EntityEmpty](manager) {

	override def getEntityTexture(entity: EntityEmpty): ResourceLocation = null

	override def doRender(empty: EntityEmpty,
			x: Double, y: Double, z: Double, yaw: Float, partialTicks: Float): Unit = {

		GlStateManager.pushMatrix()
		empty.getEntityModelInstance(empty.getEntityWorld) match {
			case model: EntityModel[_, _] =>
				model.forceRender(empty.getEntityStateInstance, x, y, z, yaw, partialTicks)
			case _ =>
		}
		GlStateManager.popMatrix()

		super.doRender(empty, x, y, z, yaw, partialTicks)
	}

}
@SideOnly(Side.CLIENT)
object RenderEmpty extends IRenderFactory[EntityEmpty] {
	override def createRenderFor(manager: RenderManager): Render[_ >: EntityEmpty] = {
		new RenderEmpty(manager)
	}
}


text:
<!DOCTYPE html>

Visit our HTML tutorial.


text:
#include "wx/glcanvas.h"
#include "../VisualWardrobe/Common.h"

class ShellGLCanvas: public wxGLCanvas
{
public:
    ShellGLCanvas(wxWindow *parent, wxWindowID id = wxID_ANY,
        const wxPoint& pos = wxDefaultPosition,
        const wxSize& size = wxDefaultSize, long style = 0,
        const wxString& name = wxT("ShellGLCanvas"));

    ~ShellGLCanvas();

    void LoadDXF(const wxString& filename);

protected:
    void OnPaint(wxPaintEvent& event);
    void OnSize(wxSizeEvent& event);
    void OnEraseBackground(wxEraseEvent& event);
    void OnMouse(wxMouseEvent& event);

private:
    void InitGL();
    void ResetProjectionMode();

	//struct GLData
	//{
	//	bool initialized;           // have OpenGL been initialized?
	//	float beginx, beginy;       // position of mouse
	//	float quat[4];              // orientation of object
	//	float zoom;                 // field of view in degrees
	//};

 //   GLData m_gldata;

	bool m_firstPaint;
    DECLARE_EVENT_TABLE()
};


text:
<?php

/* TwigBundle:Exception:exception.json.twig */
class __TwigTemplate_aa349d9889d77c942befad79736c5e4f7041c2e09ca9de8f5548b5fd510d95b3 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo twig_jsonencode_filter($this->getAttribute((isset($context["exception"]) ? $context["exception"] : null), "toarray", array()));
        echo "
";
    }

    public function getTemplateName()
    {
        return "TwigBundle:Exception:exception.json.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }
}


text:
require 'devise'

module Devise
  module Strategies
    class CookieAuthenticatable < ::Devise::Strategies::Authenticatable

      def valid?
        cookie.valid?
      end

      def authenticate!
        if fresh? && resource && validate(resource)
          Rails.logger.warn "√√  cookie authenticated! #{resource.inspect}"
          success!(resource)
        else
          pass
        end
      end

      private

      def cookie
        @cookie ||= Droom::AuthCookie.new(cookies)
      end

      def fresh?
        cookie.set_since?(Time.now - Settings.auth.cookie_period.hours)
      end

      def resource
        # returns nil when user is missing.
        @resource ||= mapping.to.where(:authentication_token => cookie.token).first
      end

      def pass
        cookie.unset
        super
      end
    end
  end

  module Models
    module CookieAuthenticatable
      # I'm sure this is configurable away, but who can find that sort of thing in devise?
    end
  end
end


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151005_204251_dd extends Migration
{
    public function up()
    {
        $rows = \app\models\User::query(['subscribe_is_tesla' => 1])->select('id,email')->all();
        foreach($rows as $row) {
            (new \yii\db\Query())->createCommand()->update(\app\models\User::TABLE, ['email' => strtolower($row['email'])], ['id' => $row['id']]);
        }
    }

    public function down()
    {
        echo "m151005_204251_dd cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
FROM phusion/baseimage:master
ARG NOMAD_VERSION="1.4.2"
MAINTAINER info@tecnick.com
ENV DEBIAN_FRONTEND noninteractive
ENV TERM linux
ENV HOME /root
ENV DISPLAY :0
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections \
# Add repositories and update
&& apt update && apt -y dist-upgrade \
&& apt install -y \
build-essential \
make \
parallel \
sudo \
unzip \
wget \
&& cd /tmp \
&& wget https://releases.hashicorp.com/nomad/${NOMAD_VERSION}/nomad_${NOMAD_VERSION}_linux_amd64.zip \
&& unzip nomad_${NOMAD_VERSION}_linux_amd64.zip -d /usr/bin/ \
&& rm -f nomad_${NOMAD_VERSION}_linux_amd64.zip \
# Cleanup temporary data and cache
&& apt clean \
&& apt autoclean \
&& apt -y autoremove \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Capitals and Countries skill, try saying...

* *Alexa launch capitals and countries*

* *Repeat*

* *Help*

"Think you know all the capitals and countries of the world?"
"Can you name the countries of the world by their capital?"

This skill is fun to play alone or with family and friends.

***

### Skill Details

* **Invocation Name:** capitals and countries
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.b1a23336-6ac5-405d-8c4d-0e1f4edab06e
* **ASIN:** B01DTY10TI
* **Author:** wesee
* **Release Date:** April 6, 2016 @ 10:02:37
* **In-App Purchasing:** No


text:
FROM python:3

# setup workdir
COPY . /src
WORKDIR /src

# setup the python and pytest environments
RUN pip install --upgrade pip setuptools
RUN pip install --upgrade -r requirements.txt
RUN pip install --upgrade -r requirements-tests.txt
RUN pip install -e .

# setup pytest user
RUN adduser --disabled-password --gecos "" --uid 7357 pytest
USER pytest

# setup entry point
ENTRYPOINT ["py.test"]


text:
package org.teknux.jettybootstrap.handler;

import java.text.MessageFormat;

import org.eclipse.jetty.server.Handler;
import org.teknux.jettybootstrap.JettyBootstrapException;
import org.teknux.jettybootstrap.handler.util.JettyLifeCycleLogListener;

abstract public class AbstractJettyHandler<T extends Handler> implements IJettyHandler<T> {

    @Override
    final public T getHandler() throws JettyBootstrapException {
        T handler = createHandler();

        handler.addLifeCycleListener(new JettyLifeCycleLogListener(this));

        return handler;
    }

    abstract protected T createHandler() throws JettyBootstrapException;

	@Override
	public String toString() {
		return MessageFormat.format("{0} [{1}]", getItemType(), getItemName());
	}
}


text:
using Filehook.Abstractions;
using Filehook.Core.Tests.Fixtures;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Options;

namespace Filehook.Core.Tests
{
    public class RegularFilehookService_SaveAsync
    {
        [Fact]
        public void Ok()
        {
            var storageName = "storageName";
            var style = "some_style";
            var someUrl = "someUrl";

            var data = new byte[] { 0xFF };

            var mockFileStorageNameResolver = new Mock<IFileStorageNameResolver>();
            var mockFileStyleResolver = new Mock<IFileStyleResolver>();
            var mockFileStorage = new Mock<IFileStorage>();
            var mockFileProccessor = new Mock<IFileProccessor>();
            var mockLocationTemplateParser = new Mock<ILocationTemplateParser>();
            var mockLocationParamFormatter = new Mock<ILocationParamFormatter>();
            var mockParamNameResolver = new Mock<IParamNameResolver>();
            var mockEntityIdResolver = new Mock<IEntityIdResolver>();

            var options = new FilehookOptions();

            mockFileStorageNameResolver
                .Setup(x => x.Resolve(It.IsAny<Expression<Func<EntityWithoutStorage, string>>>()))
                .Returns(storageName);

            mockFileStyleResolver
                .Setup(x => x.Resolve(It.IsAny<Expression<Func<EntityWithoutStorage, string>>>()))
                .Returns(new[] { new FileStyle(style) });

            mockFileStorage
                .SetupGet(x => x.Name)
                .Returns(storageName);

            mockFileStorage
                .Setup(x => x.SaveAsync(It.IsAny<string>(), It.IsAny<MemoryStream>()))
                .Returns(Task.FromResult("path"));

            mockFileStorage
                .Setup(x => x.GetUrl(It.IsAny<string>()))
                .Returns(someUrl);

            mockFileProccessor
                .Setup(x => x.CanProccess(It.IsAny<string>(), It.IsAny<byte[]>()))
                .Returns(true);

            // TODO
            // var fileProccessorResult = new IEnumerable<FileProccessingResult> { { style, new MemoryStream(data, false) } };
            // mockFileProccessor
            //     .Setup(x => x.ProccessAsync(It.IsAny<byte[]>(), It.IsAny<IEnumerable<FileStyle>>()))
            //     .Returns(Task.FromResult(fileProccessorResult));

            mockLocationTemplateParser
              .Setup(x => x.Parse(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
              .Returns("parsedTemplate");

            mockLocationParamFormatter
                .Setup(x => x.Format(It.IsAny<string>()))
                .Returns("formattedValue");

            var regularFilehookService = new RegularFilehookService(
                Options.Create(options),
                mockFileStorageNameResolver.Object,
                mockFileStyleResolver.Object,
                new[] { mockFileStorage.Object },
                new[] { mockFileProccessor.Object },
                mockLocationTemplateParser.Object,
                mockLocationParamFormatter.Object,
                mockParamNameResolver.Object,
                mockEntityIdResolver.Object);

            var entity = new EntityWithoutStorage
            {
                Id = "1"
            };

            var result = regularFilehookService.SaveAsync(entity, e => e.Name, "name1.ext", data);

            // TODO verify
        }
    }
}


text:
#include "RouteInfo.h"
#include "Buffer.h"
#include "nav2util.h"
#include "Log.h"

namespace isab{

/******************************************************/
/************  RouteInfoParts::Segment ****************/
/******************************************************/

   void RouteInfoParts::Segment::writeToBuf(Buffer *buf) const
   {
      buf->writeNextCharString(streetName);
      buf->writeNextUnaligned16bit(speedLimit);
      buf->writeNext8bit(flags);
      buf->writeNext8bit( (valid?0x01:0) | (changed?0x02:0) );
   }

   void RouteInfoParts::Segment::readFromBuf(Buffer *buf)
   {
      if (ownStreetName) {
         delete[] (char *)(streetName);
      }
      streetName = buf->getNextCharStringAlloc();
      ownStreetName = true;
      speedLimit = buf->readNextUnaligned16bit();
      flags = buf->readNext8bit();
      uint8 tmp = buf->readNext8bit();
      valid = tmp & 0x01;
      changed = (tmp & 0x02) != 0;
   }

   RouteInfoParts::Segment::~Segment()
   {
      // Sort of hackish. If the name is created from readFromBuf()
      // then we may delete the string pointer. Hack!
      if (ownStreetName) {
         delete[] (char *)(streetName);
      }
   }
   RouteInfoParts::Segment::Segment() :
      streetName(NULL), ownStreetName(false)
   { }

   RouteInfoParts::Segment::Segment(const Segment &old) :
      streetName(strdup_new(old.streetName)),
      speedLimit(old.speedLimit),
      flags(old.flags),
      valid(old.valid),
      changed(old.changed),
      ownStreetName(true)
   {
   }

   RouteInfoParts::Segment::Segment(Buffer *buf) :
      streetName(NULL), ownStreetName(false)
   {
      ownStreetName = false;
      readFromBuf(buf);
   }

   RouteInfoParts::Segment &
   RouteInfoParts::Segment::operator= (const RouteInfoParts::Segment & old)
   {
      if (ownStreetName) {
         delete[] const_cast<char *>(streetName);
      }
      streetName = NULL;
      streetName = strdup_new(old.streetName);
      speedLimit = old.speedLimit;
      flags = old.flags;
      valid = old.valid;
      changed = old.changed;
      ownStreetName = true;
      return *this;
   }

   int RouteInfoParts::Segment::log(Log* log, const char* name) const
   {
#ifndef NO_LOG_OUTPUT
      log->debug("%s : streetName : %s", name, streetName);
      log->debugDump("streetName", (uint8*)streetName, strlen(streetName) + 1);
      log->debug("%s : speedLimit    : %"PRId16, name, speedLimit);
      log->debug("%s : flags         : %"PRIu8,  name, flags);
      log->debug("%s : valid         : %s", name, valid ? "yes" : "no");
      log->debug("%s : changed       : %s", name, changed ? "yes" : "no");
      log->debug("%s : ownStreetName : %s", name, ownStreetName ? "yes" :"no");
#endif
      return 0;
   }

/******************************************************/
/************  RouteInfoParts::Landmark ***************/
/******************************************************/

   RouteInfoParts::Landmark::Landmark(const RouteInfoParts::Landmark& other )
   {
      // Do not delete infostring
      ownInfo = false;
      info = NULL;
      *this = other;
   }

   RouteInfoParts::Landmark&
   RouteInfoParts::Landmark::operator=( const RouteInfoParts::Landmark& other)
   {
      if ( this != &other ) {
         Buffer buf(256);
         other.writeToBuf( &buf );
         this->readFromBuf( &buf );
      }
      return *this;
   }

   void RouteInfoParts::Landmark::writeToBuf(Buffer *buf) const
   {
      buf->writeNextCharString(info);
      buf->writeNextUnaligned16bit(type);
      buf->writeNext8bit(side);
      buf->writeNext8bit( (start?0x01:0) |
                          (stop?0x02:0)  |
                          (disturbedRoute?0x04:0)
                        );
      buf->writeNextUnaligned32bit(startDistance);
      buf->writeNextUnaligned32bit(stopDistance);
   }

   void RouteInfoParts::Landmark::readFromBuf(Buffer *buf)
   {
      if (ownInfo) {
         delete[] (char *)(info);
      }
      info = buf->getNextCharStringAlloc();
      ownInfo = true;
      type = LandmarkType(buf->readNextUnaligned16bit());
      side = LandmarkSide(buf->readNext8bit());
      uint8 tmp = buf->readNext8bit();
      start = tmp & 0x01;
      stop = (tmp & 0x02) != 0;
      disturbedRoute = (tmp & 0x04) != 0;
      startDistance = buf->readNextUnaligned32bit();
      stopDistance = buf->readNextUnaligned32bit();
   }

   int RouteInfoParts::Landmark::log(class Log* log, int order) const
   {
#ifndef NO_LOG_OUTPUT
      log->debug("%d : info : %s", order, info);
      log->debugDump("info : ", (uint8*)info, strlen(info) + 1);
      log->debug("%d : side           : %u", order, side);
      log->debug("%d : type           : %u", order, type);
      log->debug("%d : disturbedRoute : %s", order,
                 disturbedRoute ? "yes" : "no");
      log->debug("%d : start          : %s", order, start ? "yes" : "no");
      log->debug("%d : stop           : %s", order, stop ? "yes" : "no");
      log->debug("%d : startDistance  : %"PRId32, order, startDistance);
      log->debug("%d : stopDistance   : %"PRId32, order, stopDistance);
      log->debug("%d : ownInfo        : %s", order, ownInfo ? "yes" : "no");
#endif
      return 0;
   }

   RouteInfoParts::Landmark::Landmark(const char *ainfo,
                                      bool astart, bool astop, bool adetour,
                                      enum LandmarkSide aside,
                                      enum LandmarkType atype,
                                      int32 astartDistance,
                                      int32 astopDistance)
      : info(ainfo), side(aside), type(atype), disturbedRoute(adetour),
        start(astart), stop(astop), startDistance(astartDistance),
        stopDistance(astopDistance), ownInfo(false)
   {
   }

   RouteInfoParts::Landmark::Landmark(Buffer *buf)
   {
      ownInfo = false;
      readFromBuf(buf);
   }

   RouteInfoParts::Landmark::~Landmark()
   {
      if (ownInfo) {
         delete[] (char *)(info);
      }
   }

   bool RouteInfoParts::Landmark::matchesStartStop(enum Landmark::StartStopQuery q,
                                                   int32 currdist) const
   {
      switch (q) {
         case ActiveNow:
            if (start && (startDistance>=0) && (currdist > startDistance) ) {
               return false;
            }
            if (stop && (stopDistance>=0) && (currdist < stopDistance) ) {
               return false;
            }
            return true;    // Neither before the start nor after the end.
         case ActiveOnWpt:
            return true;
         case Begins:
            return (start);
         case Ends:
            return (stop);
      }
      return false;
   }

   bool RouteInfoParts::Landmark::isDetour(enum Landmark::StartStopQuery q, int32 currDist) const
   {
      if (! matchesStartStop(q, currDist)) {
         return false;
      }
      return disturbedRoute;
   }

   bool RouteInfoParts::Landmark::isSpeedCamera(enum Landmark::StartStopQuery q, int32 currDist) const
   {
      if (! matchesStartStop(q, currDist)) {
         return false;
      }
      return (type == cameraLM);
   }

   const char * RouteInfoParts::Landmark::getDescription() const
   {
      return info;
   }

/******************************************************/
/************  RouteInfoParts::Lane *******************/
/******************************************************/

   RouteInfoParts::Lane::Lane( uint8 lane )
   {
      m_lane = lane;
   }

   RouteInfoParts::Lane::Lane( Buffer *buf )
   {
      readFromBuf(buf);
   }

   RouteInfoParts::Lane::Lane( const Lane& other )
   {
      m_lane = other.m_lane;
   }

   bool RouteInfoParts::Lane::isPreferred()
   {
      return (m_lane >> 7 & 0x1) != 0;
   }

   bool RouteInfoParts::Lane::isAllowed()
   {
      return (m_lane >> 6 & 0x1) == 0;
   }

   RouteInfoParts::Lane::Direction RouteInfoParts::Lane::direction()
   {
      return (Direction)(m_lane & 0x1F);
   }

   void RouteInfoParts::Lane::writeToBuf(Buffer *buf) const
   {
      buf->writeNext8bit(m_lane);
   }

   void RouteInfoParts::Lane::readFromBuf(Buffer *buf)
   {
      m_lane = buf->readNext8bit();
   }

   int RouteInfoParts::Lane::log(class Log* log, int order) const
   {
#ifndef NO_LOG_OUTPUT
#endif
      return 0;
   }

/******************************************************/
/************  RouteInfoParts::SignPost ***************/
/******************************************************/

   RouteInfoParts::SignPost::SignPost()
      : m_text(""), m_distance(0), ownInfo(false)
   {
      m_textColor.red = 0xff;
      m_textColor.green = 0xff;
      m_textColor.blue = 0xff;

      m_backColor.red = 0;
      m_backColor.green = 0;
      m_backColor.blue = 0xff;

      m_frontColor.red = 0;
      m_frontColor.green = 0xff;
      m_frontColor.blue = 0xff;
   }

   RouteInfoParts::SignPost::SignPost( const char *atext, int32 adist,
                                       uint8 atextRed, uint8 atextGreen, uint8 atextBlue,
                                       uint8 abgRed, uint8 abgGreen, uint8 abgBlue,
                                       uint8 afgRed, uint8 afgGreen, uint8 afgBlue)
      : m_text(atext), m_distance(adist), ownInfo(false)
   {
      m_textColor.red = atextRed;
      m_textColor.green = atextGreen;
      m_textColor.blue = atextBlue;

      m_backColor.red = abgRed;
      m_backColor.green = abgGreen;
      m_backColor.blue = abgBlue;

      m_frontColor.red = afgRed;
      m_frontColor.green = afgGreen;
      m_frontColor.blue = afgBlue;
   }

   RouteInfoParts::SignPost::SignPost(Buffer *buf)
   {
      ownInfo = false;
      readFromBuf(buf);
   }

   RouteInfoParts::SignPost::~SignPost()
   {
      if (ownInfo) {
         delete[] (char *)(m_text);
      }
   }

   RouteInfoParts::SignPost& RouteInfoParts::SignPost::operator=( const RouteInfoParts::SignPost& other )
   {
      if (ownInfo) {
         delete[] (char *)(m_text);
      }
      m_text = NULL;
      m_text = strdup_new(other.m_text);
      ownInfo = true; // Allocated on line above
      m_textColor = other.m_textColor;
      m_backColor = other.m_backColor;
      m_frontColor = other.m_frontColor;
      return *this;
   }

   void RouteInfoParts::SignPost::writeToBuf(Buffer *buf) const
   {
      buf->writeNextCharString(m_text);
      buf->writeNext8bit( m_textColor.red );
      buf->writeNext8bit( m_textColor.green );
      buf->writeNext8bit( m_textColor.blue );

      buf->writeNext8bit( m_backColor.red );
      buf->writeNext8bit( m_backColor.green );
      buf->writeNext8bit( m_backColor.blue );

      buf->writeNext8bit( m_frontColor.red );
      buf->writeNext8bit( m_frontColor.green );
      buf->writeNext8bit( m_frontColor.blue );

      buf->writeNextUnaligned32bit(m_distance);
   }

   void RouteInfoParts::SignPost::readFromBuf(Buffer *buf)
   {
      if (ownInfo) {
         delete[] (char *)(m_text);
      }
      m_text = buf->getNextCharStringAlloc();
      ownInfo = true;
      m_textColor.red = buf->readNext8bit();
      m_textColor.green = buf->readNext8bit();
      m_textColor.blue = buf->readNext8bit();

      m_backColor.red = buf->readNext8bit();
      m_backColor.green = buf->readNext8bit();
      m_backColor.blue = buf->readNext8bit();

      m_frontColor.red = buf->readNext8bit();
      m_frontColor.green = buf->readNext8bit();
      m_frontColor.blue = buf->readNext8bit();

      m_distance = buf->readNextUnaligned32bit();
   }

   int RouteInfoParts::SignPost::log(class Log* log, int order) const
   {
#ifndef NO_LOG_OUTPUT
#endif
      return 0;
   }

   const char* RouteInfoParts::SignPost::getText() const
   {
      return m_text;
   }

/******************************************************/
/************  RouteInfoParts::Crossing ***************/
/******************************************************/

   void RouteInfoParts::Crossing::writeToBuf(Buffer *buf) const
   {
      buf->writeNextUnaligned32bit(action);
      buf->writeNextUnaligned32bit(distToNextCrossing);
      buf->writeNextUnaligned32bit(lat);
      buf->writeNextUnaligned32bit(lon);
      buf->writeNext8bit(crossingType);
      buf->writeNext8bit(exitCount);
      buf->writeNext8bit( (valid?0x01:0) | (changed?0x02:0) );
   }

   void RouteInfoParts::Crossing::readFromBuf(Buffer *buf)
   {
      action = buf->readNextUnaligned32bit();
      distToNextCrossing = buf->readNextUnaligned32bit();
      lat=buf->readNextUnaligned32bit();
      lon=buf->readNextUnaligned32bit();
      crossingType = buf->readNext8bit();
      exitCount = buf->readNext8bit();
      uint8 tmp = buf->readNext8bit();
      valid = tmp & 0x01;
      changed = (tmp & 0x02) != 0;
   }

   int RouteInfoParts::Crossing::log(class Log* log, const char* name) const
   {
#ifndef NO_LOG_OUTPUT
      log->debug("%s : action             : %"PRIu32, name, action);
      log->debug("%s : distToNextCrossing : %"PRIu32, name, distToNextCrossing);
      log->debug("%s : crossingType       : %"PRIu8,  name, crossingType);
      log->debug("%s : exitCount          : %"PRIu8,  name, exitCount);
      log->debug("%s : lat                : %"PRId32, name, lat);
      log->debug("%s : lon                : %"PRId32, name, lon);
      log->debug("%s : valid              : %s", name, valid   ? "yes" : "no");
      log->debug("%s : changed            : %s", name, changed ? "yes" : "no");
#endif
      return 0;
   }

   void RouteInfoParts::RouteListCrossing::writeToBuf(Buffer *buf) const
   {
      buf->writeNextUnaligned16bit(wptNo);
      buf->writeNext8bit(toTarget);
      buf->writeNextUnaligned32bit(distToGoal);
      buf->writeNextUnaligned32bit(timeToGoal);
      crossing.writeToBuf(buf);
      buf->writeNext8bit(segments.size());   // One Segment before the next crossing
      buf->writeNext8bit(rlc_landmarks.size());   // No landmarks

      segment_container::const_iterator i;
      for (i=segments.begin(); i!=segments.end(); ++i) {
         (*i)->writeToBuf(buf);
      }

      landmark_container::const_iterator j;
      for (j=rlc_landmarks.begin(); j!=rlc_landmarks.end(); ++j) {
         (*j)->writeToBuf(buf);
      }

      buf->writeNext8bit(rlc_lanes.noLanes);
      buf->writeNextUnaligned32bit(rlc_lanes.distance);
      buf->writeNext8bit(rlc_lanes.m_laneVector.size());
      RouteInfoParts::Lanes::rip_lane_vector::const_iterator k;
      for( k=rlc_lanes.m_laneVector.begin();
           k!=rlc_lanes.m_laneVector.end(); ++k ) {
         (*k)->writeToBuf(buf);
      }
   }

   void RouteInfoParts::RouteListCrossing::readFromBuf(Buffer *buf)
   {
      wptNo=buf->readNextUnaligned16bit();
      toTarget=buf->readNext8bit();
      distToGoal=buf->readNextUnaligned32bit();
      timeToGoal=buf->readNextUnaligned32bit();
      crossing.readFromBuf(buf);
      int numSegments = buf->readNext8bit();
      int numLandmarks = buf->readNext8bit();
      int i;

      segments.resize(numSegments);
      for (i=0; i<numSegments; ++i) {
         segments[i]=new Segment(buf);
      }

      rlc_landmarks.resize(numLandmarks);
      for (i=0; i<numLandmarks; ++i) {
         rlc_landmarks[i]=new Landmark(buf);
      }

      rlc_lanes.noLanes = buf->readNext8bit()==1;
      rlc_lanes.distance = buf->readNextUnaligned32bit();
      int numLanes = buf->readNext8bit();
      rlc_lanes.m_laneVector.resize(numLanes);
      for( i=0; i<numLanes; ++i ){
         RouteInfoParts::Lane* lane = new RouteInfoParts::Lane(buf);
         rlc_lanes.m_laneVector[i] = lane;
      }
   }

   RouteInfoParts::RouteListCrossing::~RouteListCrossing()
   {
      std::vector<Segment*>::iterator i;
      for (i=segments.begin(); i!=segments.end(); ++i) {
         delete *i;
      }
      segments.clear();
      std::vector<Landmark*>::iterator j;
      for (j=rlc_landmarks.begin(); j!=rlc_landmarks.end(); ++j) {
         delete *j;
      }
      rlc_landmarks.clear();

      RouteInfoParts::Lanes::rip_lane_vector::iterator k;
      for( k = rlc_lanes.m_laneVector.begin();
           k != rlc_lanes.m_laneVector.end();
           ++k ) {
         delete *k;
      }
      rlc_lanes.m_laneVector.clear();
   }

   const char * RouteInfoParts::RouteListCrossing::hasDetourLandmark(enum Landmark::StartStopQuery q) const
   {
      landmark_container::const_iterator i = rlc_landmarks.begin();
      while (i != rlc_landmarks.end()) {
         if ((*i)->isDetour(q, -1)) {
            return (*i)->getDescription();
         }
         ++i;
      }
      return NULL;
   }

   const char * RouteInfoParts::RouteListCrossing::hasSpeedCameraLandmark(enum Landmark::StartStopQuery q) const
   {
      landmark_container::const_iterator i = rlc_landmarks.begin();
      while (i != rlc_landmarks.end()) {
         if ((*i)->isSpeedCamera(q, -1)) {
            return (*i)->getDescription();;
         }
         ++i;
      }
      return NULL;
   }

/******************************************************/
/****************  RouteInfo **************************/
/******************************************************/

   void RouteInfo::writeToBuf(Buffer *buf) const
   {
      buf->writeNext8bit (onTrackStatus);
      buf->writeNextUnaligned16bit(simInfoStatus);
      buf->writeNextUnaligned32bit(timeToGoal);
      buf->writeNextUnaligned32bit(distToWpt);
      buf->writeNextUnaligned32bit(distToGoal);
      buf->writeNextUnaligned32bit(distToTrack);
      buf->writeNextUnaligned32bit(lat);
      buf->writeNextUnaligned32bit(lon);
//      buf->writeNextUnaligned32bit(origLat);
//      buf->writeNextUnaligned32bit(origLon);
//      buf->writeNextUnaligned32bit(destLat);
//      buf->writeNextUnaligned32bit(destLon);
      buf->writeNext8bit (toOnTrackTurn);
      buf->writeNext8bit (toTrackTurn);
      buf->writeNextUnaligned16bit(timeToWpt);
      buf->writeNextUnaligned16bit(latency);
      buf->writeNextUnaligned16bit(speed);
      buf->writeNext8bit(overSpeed);
      buf->writeNext8bit(toTarget);
      buf->writeNextUnaligned16bit(crossingNo);
      currSeg.writeToBuf(buf);
      buf->writeNextUnaligned32bit(distToAltAttribSegment);
      altAttribSegment.writeToBuf(buf);
      currCrossing.writeToBuf(buf);
      nextSeg1.writeToBuf(buf);
      nextCrossing1.writeToBuf(buf);
      nextSeg2.writeToBuf(buf);
      buf->writeNext8bit(rip_landmarks.size());
      landmark_container::const_iterator j;
      for (j=rip_landmarks.begin(); j!=rip_landmarks.end(); ++j) {
         (*j)->writeToBuf(buf);
      }
      buf->writeNext8bit(rip_lanes.noLanes);
      buf->writeNextUnaligned32bit(rip_lanes.distance);
      buf->writeNext8bit(rip_lanes.m_laneVector.size());
      RouteInfoParts::Lanes::rip_lane_vector::const_iterator k;
      for( k=rip_lanes.m_laneVector.begin();
           k!=rip_lanes.m_laneVector.end(); ++k ) {
         (*k)->writeToBuf(buf);
      }
      rip_signpost.writeToBuf(buf);
   }

   void RouteInfo::readFromBuf(Buffer *buf)
   {
      onTrackStatus = OnTrackEnum(buf->readNext8bit());
      simInfoStatus = buf->readNextUnaligned16bit();
      timeToGoal    = buf->readNextUnaligned32bit();
      distToWpt     = buf->readNextUnaligned32bit();
      distToGoal    = buf->readNextUnaligned32bit();
      distToTrack   = buf->readNextUnaligned32bit();
      lat           = buf->readNextUnaligned32bit();
      lon           = buf->readNextUnaligned32bit();
//      origLat       = buf->readNextUnaligned32bit();
//      origLon       = buf->readNextUnaligned32bit();
//      destLat       = buf->readNextUnaligned32bit();
//      destLon       = buf->readNextUnaligned32bit();
      toOnTrackTurn = buf->readNext8bit();
      toTrackTurn   = buf->readNext8bit();
      timeToWpt     = buf->readNextUnaligned16bit();
      latency       = buf->readNextUnaligned16bit();
      speed         = buf->readNextUnaligned16bit();
      overSpeed     = buf->readNext8bit() != 0;
      toTarget      = buf->readNext8bit();
      crossingNo    = buf->readNextUnaligned16bit();
      currSeg.readFromBuf(buf);
      distToAltAttribSegment = buf->readNextUnaligned32bit();
      altAttribSegment.readFromBuf(buf);
      currCrossing.readFromBuf(buf);
      nextSeg1.readFromBuf(buf);
      nextCrossing1.readFromBuf(buf);
      nextSeg2.readFromBuf(buf);
      int numLandmarks = buf->readNext8bit();
      int i;
      landmark_container::iterator lmIt;
      for( lmIt = rip_landmarks.begin();
           lmIt != rip_landmarks.end();
           ++lmIt ) {
         delete *lmIt;
      }
      rip_landmarks.resize(numLandmarks);
      for (i=0; i<numLandmarks; ++i) {
         rip_landmarks[i]=new RouteInfoParts::Landmark(buf);
      }
      rip_lanes.noLanes = buf->readNext8bit()==1;
      rip_lanes.distance = buf->readNextUnaligned32bit();
      int numLanes = buf->readNext8bit();
      RouteInfoParts::Lanes::rip_lane_vector::iterator lvIt;
      for( lvIt = rip_lanes.m_laneVector.begin();
           lvIt != rip_lanes.m_laneVector.end();
           ++lvIt ) {
         delete *lvIt;
      }
      rip_lanes.m_laneVector.resize(numLanes);
      for( i=0; i<numLanes; ++i ){
         RouteInfoParts::Lane* lane = new RouteInfoParts::Lane(buf);
         rip_lanes.m_laneVector[i] = lane;
      }
      rip_signpost = RouteInfoParts::SignPost(buf);
   }

   RouteInfo& RouteInfo::operator=( const RouteInfo& other )
   {
      if ( this != &other ) {
         Buffer buf(100);
         other.writeToBuf( &buf );
         this->readFromBuf( &buf );
      }
      return *this;
   }

   RouteInfo::RouteInfo( const RouteInfo& other )
   {
      *this = other;
   }

   RouteInfo::~RouteInfo()
   {
      landmark_container::iterator lmIt;
      for( lmIt = rip_landmarks.begin();
           lmIt != rip_landmarks.end();
           ++lmIt ) {
         delete *lmIt;
      }
      RouteInfoParts::Lanes::rip_lane_vector::iterator lnIt;
      for( lnIt = rip_lanes.m_laneVector.begin();
           lnIt != rip_lanes.m_laneVector.end();
           ++lnIt ) {
         delete *lnIt;
      }
      rip_lanes.m_laneVector.clear();
   }

   int RouteInfo::log(class Log* log) const
   {
#ifndef NO_LOG_OUTPUT
      log->debug("--- Start of Routeinfo %p ---", (void*)this);
      log->debug(" onTrackStatus: %u", onTrackStatus);
      log->debug(" simInfoStatus: %"PRIu16, simInfoStatus);
      log->debug(" timeToGoal   : %"PRId32, timeToGoal);
      log->debug(" distToWpt    : %"PRId32, distToWpt);
      log->debug(" distToGoal   : %"PRId32, distToGoal);
      log->debug(" distToTrack  : %"PRId32, distToTrack);
      log->debug(" lat          : %"PRId32, lat);
      log->debug(" lon          : %"PRId32, lon);
      log->debug(" toOnTrackTurn: %"PRIu8,  toOnTrackTurn);
      log->debug(" toTrackTurn  : %"PRIu8,  toTrackTurn);
      log->debug(" timeToWpt    : %"PRIu16, timeToWpt);
      log->debug(" latency      : %"PRIu16, latency);
      log->debug(" speed        : %"PRIu16, speed);
      log->debug(" overSpeed    : %s",      overSpeed ? "yes" : "no");
      log->debug(" toTarget     : %"PRIu8,  toTarget);
      log->debug(" crossingNo   : %"PRId16, crossingNo);
      currSeg.log(log, "currSeg");
      log->debug(" distToAltAttribSegment: %"PRId32, distToAltAttribSegment);
      altAttribSegment.log(log, "altAttribSegment");
      currCrossing.log(log, "currCrossing");
      nextSeg1.log(log, "nextSeg1");
      nextCrossing1.log(log, "nextCrossing1");
      nextSeg2.log(log, "nextSeg2");
      log->debug(" rip_landmarks (%u):", rip_landmarks.size());
      for(landmark_container::const_iterator q = rip_landmarks.begin();
          q != rip_landmarks.end(); ++q){
         (*q)->log(log, std::distance(rip_landmarks.begin(), q));
      }
      log->debug("--- End   of Routeinfo %p ---", (void*)this);
#endif
      return 0;
   }

   const char * RouteInfo::hasDetourLandmark(enum RouteInfoParts::Landmark::StartStopQuery q) const
   {
      landmark_container::const_iterator i = rip_landmarks.begin();
      while (i != rip_landmarks.end()) {
         if ((*i)->isDetour(q, distToWpt)) {
            return (*i)->getDescription();
         }
         ++i;
      }
      return NULL;
   }

   const char * RouteInfo::hasSpeedCameraLandmark(
      enum RouteInfoParts::Landmark::StartStopQuery q) const
   {
      landmark_container::const_iterator i = rip_landmarks.begin();
      while (i != rip_landmarks.end()) {
         if ((*i)->isSpeedCamera(q, distToWpt)) {
            return (*i)->getDescription();;
         }
         ++i;
      }
      return NULL;
   }

/******************************************************/
/****************  RouteList **************************/
/******************************************************/

   RouteList::RouteList(Buffer *buf)
   {
      const int numCrossings = buf->readNextUnaligned16bit();

      crossings.resize(numCrossings);

      for (int i=0; i<numCrossings; ++i) {
         RouteInfoParts::RouteListCrossing *tmpcrossing =
            new RouteInfoParts::RouteListCrossing;
         tmpcrossing->readFromBuf(buf);
         crossings[i]=tmpcrossing;
      }
   }

   void RouteList::writeToBuf(Buffer *buf) const
   {
      buf->writeNextUnaligned16bit(crossings.size());
      std::vector<RouteInfoParts::RouteListCrossing *>::const_iterator i;

      for (i=crossings.begin(); i!=crossings.end(); ++i) {
         (*i)->writeToBuf(buf);
      }
   }

   RouteList::~RouteList()
   {
       std::vector<RouteInfoParts::RouteListCrossing *>::iterator i;

      for (i=crossings.begin(); i!=crossings.end(); ++i) {
         delete *i;
      }
   }

}


text:
title: Luces
active: "journal"
date: 2009-11-03T02:54:00-04:00
author: David Hernandez
layout: post
permalink: /luces/
image:
  feature: "http://micheandino.files.wordpress.com/2009/11/tumblr_ksiiqhzb6i1qa1qgjo1_1280.jpg"
header-img: "http://micheandino.files.wordpress.com/2009/11/tumblr_ksiiqhzb6i1qa1qgjo1_1280.jpg"
categories:
  - street
tags:
  - outdoor
  - merida
  - venezuela
  - street
format: image
comments: "true"
---

Luces


text:
HADOOP_PATH=~/hadoop-2.7.0

APP_NAME=StreamCompressor
JAR_NAME=StreamCompressor

# compile
$HADOOP_PATH/bin/hadoop com.sun.tools.javac.Main -Xlint $APP_NAME.java

# packing
jar cf $JAR_NAME.jar $APP_NAME*.class


text:
package io.pivotal.cc.clusterside;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ClustersideApplication.class)
public class ClustersideApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
using ClientDependency.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using ThumNet.EasyAD.Managers;
using ThumNet.EasyAD.Models;
using ThumNet.EasyAD.ViewModels;
using Umbraco.Web.Editors;
using Umbraco.Web.Mvc;
using ThumNet.EasyAD.Repositories;
using ThumNet.EasyAD.Handlers;
using ThumNet.EasyAD.Configuration;
using Umbraco.Core.Configuration;

namespace ThumNet.EasyAD.Controllers
{
    [PluginController(AppConstants.PluginControllerName)]
    public class EasyADApiController : UmbracoAuthorizedJsonController
    {
        public OptionsViewModel GetOptions()
        {
            return new OptionsViewModel
            {
                AllUserTypes = Services.UserService.GetAllUserTypes().ToDictionary(t => t.Id, t => t.Name),
                AllSections = Services.SectionService.GetSections().ToDictionary(t => t.Alias, t => t.Name)
            };
        }

        // sample url: /umbraco/backoffice/EasyAD/EasyADApi/GetById?groupId=1
        public EasyADGroup GetById(int id)
        {
            var repo = new EasyADRepository(DatabaseContext.Database, DatabaseContext.SqlSyntax);
            return repo.GetById(id);
        }

        public Config GetConfig()
        {
            var config = UmbracoConfig.For.EasyAD();
            return config;
        }

        public IEnumerable<EasyADGroup> GetAll()
        {
            var repo = new EasyADRepository(DatabaseContext.Database, DatabaseContext.SqlSyntax);
            return repo.GetAll();
        }

        public int DeleteById(int id)
        {
            var groupManager = GroupBasedUserManagerResolver.Current.Manager;
            var repo = new EasyADRepository(DatabaseContext.Database, DatabaseContext.SqlSyntax);
            var handler = new DeleteGroupHandler(repo, groupManager, Services.UserService);
            return handler.Handle(id);
        }

        public GroupSaveViewModel PostSave(EasyADGroup group)
        {
            var groupManager = GroupBasedUserManagerResolver.Current.Manager;
            string message = "";

            if (!ValidateGroup(group.Name, groupManager, ref message))
            {
                return FailedSave(message);
            }

            if (!ValidUserType(group.UserType))
            {
                return FailedSave("Invalid User Type!");
            }

            if (!ValidateSections(group.Sections, ref message))
            {
                return FailedSave(message);
            }

            var repo = new EasyADRepository(DatabaseContext.Database, DatabaseContext.SqlSyntax);
            var handler = new SaveGroupHandler(repo, groupManager, Services.UserService);
            var groupId = handler.Handle(group);
            return new GroupSaveViewModel
            {
                GroupId = groupId,
                Success = true,
                Message = "Group created!"
            };
        }

        private bool ValidateGroup(string name, IGroupBasedUserManager groupManager, ref string message)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                message = "Group name is required!";
                return false;
            }

            bool groupExists = groupManager.GroupExists(name);
            if (!groupExists)
            {
                message = string.Format("Group with name '{0}' not found in AD!", name);
                return false;
            }

            return true;
        }

        private bool ValidUserType(int userType)
        {
            return Services.UserService.GetAllUserTypes().Any(u => u.Id == userType);
        }

        private bool ValidateSections(string sections, ref string message)
        {
            sections = sections ?? string.Empty;
            var groupSections = sections.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            if (groupSections.Length == 0)
            {
                message = "At least one sections is required!";
                return false;
            }

            var allSections = Services.SectionService.GetSections().Select(s => s.Alias);
            var validSections = groupSections.All(s => allSections.Contains(s));
            if (!validSections)
            {
                message = "Invalid section selected!";
                return false;
            }

            return true;
        }

        private GroupSaveViewModel FailedSave(string message)
        {
            return new GroupSaveViewModel
            {
                Success = false,
                Message = message
            };
        }
    }
}


text:
using System.Threading;
using Myre.Entities.Services;
using System;
using System.Collections.Generic;

namespace Myre.Entities.Events
{
    internal interface IEventInvocation
    {
        void Execute();

        void Recycle();
    }

    internal interface IEvent
    {

    }

    /// <summary>
    /// An interface which defines methods for retrieving events.
    /// </summary>
    public interface IEventService
        : IService
    {
        Event<T> GetEvent<T>();
    }

    /// <summary>
    /// A class which manages the sending of events.
    /// </summary>
    public class EventService
        : Service, IEventService
    {
        private readonly Dictionary<Type, IEvent> _events = new();
        private Queue<IEventInvocation> _waitingEvents = new();
        private Queue<IEventInvocation> _executingEvents = new();
        private SpinLock _spinLock;

        /// <summary>
        /// Gets an event of the specified type.
        /// </summary>
        /// <typeparam name="T">The type of data this event sends.</typeparam>
        /// <returns></returns>
        public Event<T> GetEvent<T>()
        {
            var type = typeof(T);

            if (!_events.TryGetValue(type, out var e))
            {
                e = new Event<T>(this);
                _events[type] = e;
            }

            return (Event<T>)e;
        }

        /// <summary>
        /// Sends any queued events.
        /// </summary>
        /// <param name="elapsedTime">The elapsed time.</param>
        public override void Update(float elapsedTime)
        {
            while (_waitingEvents.Count > 0)
            {
                FlipBuffers();
                ExecuteEvents();
            }
        }

        internal void Queue(IEventInvocation eventInvocation)
        {
            var taken = false;
            try
            {
                _spinLock.Enter(ref taken);
                _waitingEvents.Enqueue(eventInvocation);
            }
            finally
            {
                if (taken)
                    _spinLock.Exit();
            }
        }

        private void ExecuteEvents()
        {
            while (_executingEvents.Count > 0)
            {
                var invocation = _executingEvents.Dequeue();

                invocation.Execute();
                invocation.Recycle();
            }
        }

        private void FlipBuffers()
        {
            var taken = false;
            try
            {
                _spinLock.Enter(ref taken);
                var tmp = _waitingEvents;
                _waitingEvents = _executingEvents;
                _executingEvents = tmp;
            }
            finally
            {
                if (taken)
                    _spinLock.Exit();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<DataContextDriver>
  <MainAssembly>UmbracoLinqPad.dll</MainAssembly>
  <SupportUri>https://github.com/Shazwazza/UmbracoLinqPadDriver</SupportUri>
</DataContextDriver>


text:
from mkt.site.utils import chunked

from mkt.developers.tasks import generate_image_assets
from mkt.webapps.models import Webapp

def run():
    for chunk in chunked(Webapp.objects.all(), 50):
        for app in chunk:
            generate_image_assets.delay(app)


text:
@protocol EventHeaderViewOutput;

@interface EventHeaderView : UIView <EventHeaderViewInput, EventHeaderModuleInput>

@property (nonatomic, weak) IBOutlet UIImageView *eventImageView;
@property (nonatomic, weak) IBOutlet UIView *backgroundView;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topConstraint;

@property (nonatomic, strong) id<EventHeaderViewOutput> output;

+ (EventHeaderView *)eventHeaderView;

@end


text:
int query_parser_parse(query_parse_context* c);
int query_parser_lex_init(void* scanner);
int query_parser_lex_destroy(void* scanner);
int query_parser_set_extra(void* extra, void* scanner);

void query_parser_error(YYLTYPE* locp, query_parse_context* context, const char* err) {
  context->error = malloc(1024 * sizeof(char));
  snprintf(context->error, 1024, "line %d: %s", locp->first_line, err);
}

extern int query_parser_debug;

wp_error* wp_query_parse(const char* s, const char* default_field, wp_query** query) {
  query_parse_context c;
  c.input = s;
  c.default_field = default_field;
  c.error = NULL;

  query_parser_lex_init(&c.scanner);
  query_parser_set_extra(&c, c.scanner);
  int ret = query_parser_parse(&c);
  query_parser_lex_destroy(c.scanner);

  if(ret != 0) RAISE_ERROR("parse error: %s", c.error);

  if(c.result == NULL) // empty query
    *query = wp_query_new_empty();
  else
    *query = c.result;

  return NO_ERROR;
}


text:
package com.commonsware.android.c2dm;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.c2dm.C2DMessaging;

public class PushEndpointDemo extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void registerAccount(View v) {
    EditText acct=(EditText)findViewById(R.id.account);

    C2DMessaging.register(this, acct.getText().toString());
  }
}


text:
describe('AjaxContentBlocksHashSerializer', function () {
  const service = new AjaxContentBlocksHashSerializer();
  const hash = AjaxServiceMockData.existingContentBlocksHash1();

  describe('The ajax content blocks serializer', function () {
    it('can stringify & parse a AjaxContentBlocksHash', function () {
      const stringified = service.stringify(hash);
      const parsed = service.parse(stringified);

      expect(parsed['my-path'].api_key).toBe(hash['my-path'].api_key);
      expect(parsed['my-path'].content_path).toBe(hash['my-path'].content_path);
      expect(parsed['my-path'].content).toBe(hash['my-path'].content);
      expect(parsed['my-path'].created_at).toEqual(hash['my-path'].created_at);
      expect(parsed['my-path'].updated_at).toEqual(hash['my-path'].updated_at);
    });
  });
});


text:
import Backbone from 'backbone';
import $ from 'jquery';
import _ from 'underscore';

// Models
import TabModel from './../models/tabModel';

// Collection
import TabCollection from './../collections/tabCollection';

// Views
import PipelineView from './pipeline';
import SettingsArea from './settingsArea';
import TabController from './tabController';

Backbone.$ = $;

// Work-Area view
var WorkArea = Backbone.View.extend({
    template: _.template($('#work-area-template').html()),
    initialize: function(options) {
        this.messageGroup = options.messageGroup;
        this.pipeline = options.pipeline;
        this.tabGroup = new TabCollection();
    },
    render: function() {
        this.$el.html(this.template);
        this.settingsArea = new SettingsArea();
        this.$el.find('#settings-area').html(this.settingsArea.render().$el);
        this.pipelineView = new PipelineView({
            id: 'pipeline',
            messageGroup: this.messageGroup,
            pipeline: this.pipeline,
            clickComponentEvent: this.settingsArea.clickComponentEvent
        });
        var tabModel = new TabModel({
            id: 'pipeline',
            view: this.pipelineView
        });
        this.tabGroup.add(tabModel);
        this.tabController = new TabController({
            messageGroup: this.messageGroup,
            pipeline: this.pipeline,
            tabGroup: this.tabGroup
        });
        this.$el.find('#work-area-content').html(this.tabController.render().$el);
        return this;
    }
});

module.exports = WorkArea;


text:
package br.com.find.cep.service;

import br.com.find.cep.exception.AddressNotFoundException;
import br.com.find.cep.resource.AddressRequest;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.*;

/**
 * The type Address service provider test.
 * @author Felipe Adorno (felipeadsc@gmail.com)
 */
@RunWith(JUnit4.class)
public class AddressServiceProviderTest extends TestCase {

    private AddressRequest santaRita;
    private AddressRequest sebastiaoSoares;
    private AddressRequest siqueiraCampos;
    private AddressService addressService = new AddressServiceProvider();

    @Before
    public void setUp() throws Exception {
        santaRita = new AddressRequest("Rua 1", "Fernandes", "Santa Rita do Sapucaí", "MG");
        sebastiaoSoares = new AddressRequest("Rua Prof. Sebastião Soares de Faria", "Bela Vista", "São Paulo", "SP");
        siqueiraCampos = new AddressRequest("Rua Dr. Siqueira Campos", "Liberdade", "São Paulo", "SP");
    }

    @Test(expected = AddressNotFoundException.class)
    public void testRemoveAddressByIdWithoutAddress() throws Exception {
        AddressRequest expectedAddressRequest = createAddress();
        addressService.removeAddressById(expectedAddressRequest.getId());
    }

    @Test(expected = AddressNotFoundException.class)
    public void testRemoveAddressById() throws Exception {
        AddressRequest expectedAddressRequest = createAddress();
        addressService.saveAddress(expectedAddressRequest);

        AddressRequest addressRequest = addressService.findAddressById(expectedAddressRequest.getId());
        assertThat(expectedAddressRequest, equalTo(addressRequest));

        addressService.removeAddressById(expectedAddressRequest.getId());

        addressService.findAddressById(expectedAddressRequest.getId());

    }

    @Test
    public void testUpdateAddress() throws Exception {
        AddressRequest expectedAddressRequest = createAddress();
        expectedAddressRequest.setCep("01317010");
        addressService.saveAddress(expectedAddressRequest);
        expectedAddressRequest.setCity("Santa Rita do Sapucai");

        addressService.updateAddress(expectedAddressRequest);

        AddressRequest addressRequest = addressService.findAddressById(expectedAddressRequest.getId());
        assertThat(expectedAddressRequest, equalTo(addressRequest));
    }

    @Test(expected = AddressNotFoundException.class)
    public void testSaveAddressWithInvalidCep() throws Exception {
        AddressRequest expectedAddressRequest = createAddress();
        expectedAddressRequest.setCep("12345678");
        addressService.saveAddress(expectedAddressRequest);
    }

    @Test
    public void testSaveAddress() throws Exception {
        testFindAddressById(); //is the same test because don't have repository to verify the calls
    }

    @Test
    public void testFindAddressById() throws Exception {
        AddressRequest expectedAddressRequest = createAddress();
        addressService.saveAddress(expectedAddressRequest);
        AddressRequest addressRequest = addressService.findAddressById(expectedAddressRequest.getId());

        assertThat(expectedAddressRequest, equalTo(addressRequest));
    }

    @Test(expected = AddressNotFoundException.class)
    public void findAddressByIdWithWrongId() throws Exception {
        addressService.findAddressById("123");
    }

    @Test(expected = AddressNotFoundException.class)
    public void testFindAddressWithWrongCep() throws Exception {
        addressService.findAddressByCep("01220123");
    }

    @Test
    public void testFindSiqueiraCamposAddress() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("01509020");
        assertThat(addressRequest, equalTo(siqueiraCampos));
    }

    @Test
    public void testFindSebastiaoSoaresAddress() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("01317010");
        assertThat(addressRequest, equalTo(sebastiaoSoares));
    }

    @Test
    public void testFindSantaRitaAddressWithWrongCepNoZero() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("37540123");
        assertThat(addressRequest, equalTo(santaRita));
    }

    @Test
    public void testFindSantaRitaAddressWithWrongCepOneZero() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("37540120");
        assertThat(addressRequest, equalTo(santaRita));
    }

    @Test
    public void testFindSantaRitaAddressWithWrongCepTwoZero() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("37540100");
        assertThat(addressRequest, equalTo(santaRita));
    }

    @Test
    public void testFindSantaRitaAddressWithWrongCepThreeZero() throws Exception {
        AddressRequest addressRequest = addressService.findAddressByCep("37540000");
        assertThat(addressRequest, equalTo(santaRita));
    }

    private AddressRequest createAddress() {
        AddressRequest expectedAddressRequest = new AddressRequest();
        expectedAddressRequest.setStreet("Rua1");
        expectedAddressRequest.setState("SP");
        expectedAddressRequest.setDistrict("Bela Vista");
        expectedAddressRequest.setCep("01317010");
        expectedAddressRequest.setCity("São Paulo");
        expectedAddressRequest.setComplement("Sem complemento");
        expectedAddressRequest.setNumber(28L);
        return expectedAddressRequest;
    }
}


text:
<!DOCTYPE html>

    <title>数字的精度修复</title>
    <meta charset="utf-8">

<input type="text" name="first"/>
+
<input type="text" name="second"/>
=
<input type="text" name="rest" value="" readonly>
<button id="fixed">toFixed方式</button>
<button id="ten">通过10的倍数方式</button>