text:
from django.conf import settings
from django.test import TestCase
from pillowtop.feed.couch import change_from_couch_row

import sqlalchemy
from fluff.signals import rebuild_table, indicator_document_updated

if not settings.configured:
    settings.configure(DEBUG=True)

import fluff
from couchdbkit import Document
from datetime import date, datetime, timedelta
from fakecouch import FakeCouchDb
from dimagi.utils.parsing import json_format_date

WEEK = timedelta(days=7)

def flat_field(fn):
    def getter(item):
        return unicode(fn(item) or "")
    return fluff.FlatField(getter)

class Base0(fluff.Calculator):

    @fluff.filter_by
    def base_0_filter(self):
        pass

    @fluff.date_emitter
    def base_0_emitter(self):
        pass

class Base1(Base0):

    @fluff.filter_by
    def base_1_filter(self):
        pass

    @fluff.date_emitter
    def base_1_emitter(self):
        pass

class Base2(Base0):

    @fluff.filter_by
    def base_2_filter(self):
        pass

    @fluff.date_emitter
    def base_2_emitter(self):
        pass

class Base3(Base1, Base2):

    @fluff.filter_by
    def base_3_filter(self):
        pass

    @fluff.date_emitter
    def base_3_emitter(self):
        pass

class Indicators1(fluff.IndicatorDocument):
    base0 = Base0(window=WEEK)

class Indicators2(fluff.IndicatorDocument):
    base1 = Base1(window=WEEK)
    base2 = Base2(window=WEEK)

class FluffTest(TestCase):

    @classmethod
    def setUpClass(cls):
        # hack - force disconnecting the signals because ctable doesn't play nice with mocks
        cls.previous_signal_receivers = indicator_document_updated.receivers
        indicator_document_updated.receivers = []
        cls.engine = sqlalchemy.create_engine(settings.SQL_REPORTING_DATABASE_URL)

    def setUp(self):
        self.fakedb = FakeCouchDb()
        MockIndicators.set_db(self.fakedb)
        MockIndicatorsWithGetters.set_db(self.fakedb)
        MockDoc.set_db(self.fakedb)

        MockIndicatorsSql.set_db(self.fakedb)
        rebuild_table(self.engine, None, MockIndicatorsSql)
        rebuild_table(self.engine, None, MockIndicatorsSqlWithFlatFields)

    @classmethod
    def tearDownClass(cls):
        indicator_document_updated.receivers = cls.previous_signal_receivers

    def tearDown(self):
        with self.engine.begin() as connection:
            MockIndicatorsSql()._table.drop(connection, checkfirst=True)
            MockIndicatorsSqlWithFlatFields()._table.drop(connection, checkfirst=True)
        self.engine.dispose()

    def test_calculator_base_classes(self):
        # Base0
        self.assertEqual(Base0._fluff_emitters, set([
            'base_0_emitter',
        ]))
        self.assertEqual(Base0._fluff_filters, set([
            'base_0_filter',
        ]))

        # Base1
        self.assertEqual(Base1._fluff_emitters, set([
            'base_0_emitter',
            'base_1_emitter',
        ]))
        self.assertEqual(Base1._fluff_filters, set([
            'base_0_filter',
            'base_1_filter',
        ]))

        # Base2
        self.assertEqual(Base2._fluff_emitters, set([
            'base_0_emitter',
            'base_2_emitter',
        ]))
        self.assertEqual(Base2._fluff_filters, set([
            'base_0_filter',
            'base_2_filter',
        ]))

        # Base2
        self.assertEqual(Base3._fluff_emitters, set([
            'base_0_emitter',
            'base_1_emitter',
            'base_2_emitter',
            'base_3_emitter',
        ]))
        self.assertEqual(Base3._fluff_filters, set([
            'base_0_filter',
            'base_1_filter',
            'base_2_filter',
            'base_3_filter',
        ]))

    def test_indicator_classes(self):
        self.assertEquals(Indicators1._calculators.keys(), ['base0'])
        self.assertEquals(Indicators2._calculators.keys(), ['base1', 'base2'])

    def test_indicator_calculation(self):
        actions = [dict(date="2012-09-23", x=2), dict(date="2012-09-24", x=3)]
        doc = dict(
            actions=actions,
            get_id="123",
            domain="mock",
            owner_id="test_owner",
            doc_type='MockDoc'
        )
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            classname = cls.__name__
            pillow = cls.pillow()()
            pillow.process_change(change_from_couch_row({'changes': [], 'id': '123', 'seq': 1, 'doc': doc}))
            indicator = self.fakedb.mock_docs.get("%s-123" % classname, None)
            self.assertIsNotNone(indicator)
            self.assertEqual(11, len(indicator))
            self.assertEqual(8, len(indicator['value_week']))
            self.assertIn("value_week", indicator)
            self.assertIn("date", indicator["value_week"])
            self.assertIn("null", indicator["value_week"])
            self.assertIn("date_value", indicator["value_week"])
            self.assertIn("null_value", indicator["value_week"])
            self.assertEqual({'date': "2012-09-23", 'value': 1, 'group_by': None}, indicator["value_week"]["date"][0])
            self.assertEqual({'date': "2012-09-24", 'value': 1, 'group_by': None}, indicator["value_week"]["date"][1])
            self.assertEqual({'date': None, 'value': 1, 'group_by': None}, indicator["value_week"]["null"][0])

            self.assertEqual({'date': "2012-09-23", 'value': 2, 'group_by': None}, indicator["value_week"]["date_value"][0])
            self.assertEqual({'date': "2012-09-24", 'value': 3, 'group_by': None}, indicator["value_week"]["date_value"][1])
            self.assertEqual({'date': None, 'value': 2, 'group_by': None}, indicator["value_week"]["null_value"][0])

            self.assertEqual(dict(date='2013-01-01', group_by=['abc', 'xyz'], value=3), indicator["value_week"]["group_list"][0])
            self.assertEqual(dict(date='2013-01-01', group_by=['abc', '123'], value=2), indicator["value_week"]["group_val"][0])
            self.assertEqual(dict(date='2013-01-01', group_by=['abc', '123'], value=1), indicator["value_week"]["group_no_val"][0])

    def test_calculator_calculate(self):
        calc = ValueCalculator(WEEK)
        calc.fluff = MockIndicators
        values = calc.calculate(MockDoc.wrap(dict(actions=[dict(date="2012-09-23", x=2),
                                                           dict(date="2012-09-24", x=3)])))
        self.assertEquals(len(values.keys()), 8)
        self.assertEquals(values['null_value'], [dict(date=None, value=2, group_by=None)])
        self.assertEquals(values['date_value'], [
            dict(date=date(2012, 9, 23), value=2, group_by=None),
            dict(date=date(2012, 9, 24), value=3, group_by=None)])
        self.assertEquals(values['date'], [
            dict(date=date(2012, 9, 23), value=1, group_by=None),
            dict(date=date(2012, 9, 24), value=1, group_by=None)])
        self.assertEquals(values['null'], [dict(date=None, value=1, group_by=None)])
        self.assertEquals(values['group_list'], [dict(date=date(2013, 1, 1), group_by=['abc', 'xyz'], value=3)])
        self.assertEquals(values['group_val'], [dict(date=date(2013, 1, 1), group_by=['abc', '123'], value=2)])
        self.assertEquals(values['group_no_val'], [dict(date=date(2013, 1, 1), group_by=['abc', '123'], value=1)])
        self.assertEquals(values['group_null'], [dict(date=None, group_by=['abc', 'xyz'], value=1)])

    def test_calculator_get_result(self):
        key = ['a', 'b']
        now = datetime.utcnow().date()
        start = json_format_date(now - WEEK)
        end = json_format_date(now)
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            classname = cls.__name__
            self.fakedb.add_view('fluff/generic', [
                (
                    {'reduce': True, 'key': [classname, 'a', 'b', 'value_week', 'null', None], 'wrap_doc': True},
                    [{"key": None, "value": {"sum": 3}}]
                ),
                (
                    {'reduce': True, 'key': [classname, 'a', 'b', 'value_week', 'null_value', None], 'wrap_doc': True},
                    [{"key": None, "value": {"max": 8}}]
                ),
                (
                    {'startkey': [classname, 'a', 'b', 'value_week', 'date', start],
                        'endkey': [classname, 'a', 'b', 'value_week', 'date', end],
                        'reduce': True, 'wrap_doc': True},
                    [{"key": None, "value": {"count": 7}}]
                ),
                (
                    {'startkey': [classname, 'a', 'b', 'value_week', 'date_value', start],
                        'endkey': [classname, 'a', 'b', 'value_week', 'date_value', end],
                        'reduce': True, 'wrap_doc': True},
                    [{"key": None, "value": {"sum": 11}}]
                )
            ])
            value = cls.get_result('value_week', key, reduce=True)
            self.assertEqual(value['null'], 3)
            self.assertEqual(value['date'], 7)
            self.assertEqual(value['date_value'], 11)
            self.assertEqual(value['null_value'], 8)

    def test_indicator_diff_new(self):
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            classname = cls.__name__
            doc = cls(
                domain="mock",
                owner_id="123",
                value_week=dict(
                    date=[[date(2012, 02, 23), 1]],
                    null=[],
                    date_value=[],
                    null_value=[[None, 3]]
                )
            )
            diff = doc.diff(None)
            self.maxDiff = None
            expected = dict(domains=['mock'],
                            database=cls.Meta.app_label,
                            doc_type=classname,
                            group_values=['mock', '123'],
                            group_names=['domain', 'owner_id'],
                            group_type_map={'domain': 'integer', 'owner_id': 'string'},
                            indicator_changes=[
                                dict(calculator='value_week',
                                     emitter='date',
                                     emitter_type='date',
                                     reduce_type='count',
                                     values=[dict(date=date(2012, 2, 23), value=1, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='null_value',
                                     emitter_type='null',
                                     reduce_type='max',
                                     values=[dict(date=None, value=3, group_by=None)])
                            ],
                            all_indicators=self.all_indicators())
            self.assertEqual(expected, diff)

    def test_indicator_diff_same(self):
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            doc = cls(domain="mock",
                      owner_id="123",
                      value_week=dict(
                          date=[date(2012, 02, 23)],
                          null=[],
                          date_value=[],
                          null_value=[[None, 3]]
                      ))
            another = cls(doc.to_json())
            diff = doc.diff(another)
            self.assertIsNone(diff)

    def all_indicators(self):
        return [
            dict(calculator='value_week',
                 emitter='date_value',
                 emitter_type='date',
                 reduce_type='sum'),
            dict(calculator='value_week',
                 emitter='date',
                 emitter_type='date',
                 reduce_type='count'),
            dict(calculator='value_week',
                 emitter='null',
                 emitter_type='null',
                 reduce_type='sum'),
            dict(calculator='value_week',
                 emitter='null_value',
                 emitter_type='null',
                 reduce_type='max'),
        ]

    def test_indicator_diff(self):
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            current = cls(domain="mock",
                                     owner_id="123",
                                     value_week=dict(date=[[date(2012, 02, 23), 1]],
                                                     null=[],
                                                     date_value=[[date(2012, 02, 23), 3]],
                                                     null_value=[]))
            new = cls(domain="mock",
                      owner_id="123",
                      value_week=dict(
                          date=[[date(2012, 02, 24), 1]],
                          null=[[None, 1]],
                          date_value=[[date(2012, 02, 23), 4]],
                          null_value=[[None, 2]]))

            diff = new.diff(current)
            self.assertIsNotNone(diff)
            self.maxDiff = None
            expected = dict(domains=['mock'],
                            database=cls.Meta.app_label,
                            doc_type=cls.__name__,
                            group_values=['mock', '123'],
                            group_names=['domain', 'owner_id'],
                            group_type_map={'domain': 'integer', 'owner_id': 'string'},
                            indicator_changes=[
                                dict(calculator='value_week',
                                     emitter='date_value',
                                     emitter_type='date',
                                     reduce_type='sum',
                                     values=[dict(date=date(2012, 2, 23), value=4, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='date',
                                     emitter_type='date',
                                     reduce_type='count',
                                     values=[dict(date=date(2012, 2, 24), value=1, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='null',
                                     emitter_type='null',
                                     reduce_type='sum',
                                     values=[dict(date=None, value=1, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='null_value',
                                     emitter_type='null',
                                     reduce_type='max',
                                     values=[dict(date=None, value=2, group_by=None)])
                            ],
                            all_indicators=self.all_indicators())
            self.assertEqual(expected, diff)

    def test_indicator_diff_dict(self):
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            current = cls(domain="mock",
                                     owner_id="123",
                                     value_week=dict(
                                         date=[dict(date=date(2012, 2, 23), value=1, group_by=None)],
                                         date_value=[[date(2012, 02, 24), 1]],
                                         group_list=[],
                                         null_value=[dict(date=None, value=1, group_by='abc')],
                                     ))
            new = cls(domain="mock",
                      owner_id="123",
                      value_week=dict(
                          date=[[date(2012, 02, 24), 1]],
                          date_value=[dict(date=date(2012, 2, 20), value=2, group_by=None)],
                          group_list=[dict(date=date(2013, 1, 1), value=3, group_by=['abc', '123'])],
                          null_value=[dict(date=None, value=1, group_by='abc')],
                      ))

            diff = new.diff(current)
            self.assertIsNotNone(diff)
            self.maxDiff = None
            expected = dict(domains=['mock'],
                            database=cls.Meta.app_label,
                            doc_type=cls.__name__,
                            group_values=['mock', '123'],
                            group_names=['domain', 'owner_id'],
                            group_type_map={'domain': 'integer', 'owner_id': 'string'},
                            indicator_changes=[
                                dict(calculator='value_week',
                                     emitter='date_value',
                                     emitter_type='date',
                                     reduce_type='sum',
                                     values=[dict(date=date(2012, 2, 20), value=2, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='date',
                                     emitter_type='date',
                                     reduce_type='count',
                                     values=[dict(date=date(2012, 2, 24), value=1, group_by=None)]),
                                dict(calculator='value_week',
                                     emitter='group_list',
                                     emitter_type='date',
                                     reduce_type='sum',
                                     values=[dict(date=date(2013, 1, 1), value=3, group_by=['abc', '123'])]),
                            ],
                            all_indicators=[
                                dict(calculator='value_week',
                                     emitter='date_value',
                                     emitter_type='date',
                                     reduce_type='sum'),
                                dict(calculator='value_week',
                                     emitter='date',
                                     emitter_type='date',
                                     reduce_type='count'),
                                dict(calculator='value_week',
                                     emitter='group_list',
                                     emitter_type='date',
                                     reduce_type='sum'),
                                dict(calculator='value_week',
                                     emitter='null_value',
                                     emitter_type='null',
                                     reduce_type='max'),
                            ])
            self.assertEqual(expected, diff)

    def test_flat_field_types(self):
        str_field = fluff.FlatField(lambda case: "hello")
        self.assertEquals(str_field.calculate('bar'), "hello")

        unicode_field = fluff.FlatField(lambda case: u"unicode!!")
        self.assertEquals(unicode_field.calculate('bar'), u"unicode!!")

        num_field = fluff.FlatField(lambda case: 432123141)
        self.assertRaises(AssertionError, num_field.calculate, 'bar')

    def test_save_to_sql(self):
        actions = [dict(date="2012-09-23", x=2), dict(date="2012-09-24", x=3)]
        doc = dict(
            actions=actions,
            get_id="123",
            domain="mock",
            owner_id="test_owner"
        )
        current = MockIndicatorsSql(_id='234')
        current.calculate(MockDoc.wrap(doc))
        current.save_to_sql(current.diff(None), self.engine)
        expected = [
            (u'123', date(1, 1, 1), u'mock', u'test_owner', None, None, None, None, None, 2, None, 1),
            (u'123', date(2013, 1, 1), u'abc', u'123', None, None, 2, None, 1, None, None, None),
            (u'123', date(2012, 9, 24), u'mock', u'test_owner', 3, None, None, None, None, None, 1, None),
            (u'123', date(2012, 9, 23), u'mock', u'test_owner', 2, None, None, None, None, None, 1, None),
            (u'123', date(1, 1, 1), u'abc', u'xyz', None, None, None, 1, None, None, None, None),
            (u'123', date(2013, 1, 1), u'abc', u'xyz', None, 3, None, None, None, None, None, None),
        ]

        with self.engine.begin() as connection:
            rows = connection.execute(sqlalchemy.select([current._table]))
            self.assertEqual(rows.rowcount, len(expected))
            for row in rows:
                self.assertIn(row, expected)

    def test_save_to_sql_update(self):
        self.test_save_to_sql()

        actions = [dict(date="2012-09-23", x=5)]
        doc = dict(
            actions=actions,
            get_id="123",
            domain="mock",
            owner_id="test_owner"
        )
        current = MockIndicatorsSql(_id='234')
        current.calculate(MockDoc.wrap(doc))
        current.save_to_sql(current.diff(None), self.engine)
        expected = [
            (u'123', date(1, 1, 1), u'mock', u'test_owner', None, None, None, None, None, 2, None, 1),
            (u'123', date(2013, 1, 1), u'abc', u'123', None, None, 2, None, 1, None, None, None),
            (u'123', date(2012, 9, 23), u'mock', u'test_owner', 5, None, None, None, None, None, 1, None),
            (u'123', date(1, 1, 1), u'abc', u'xyz', None, None, None, 1, None, None, None, None),
            (u'123', date(2013, 1, 1), u'abc', u'xyz', None, 3, None, None, None, None, None, None),
        ]

        with self.engine.begin() as connection:
            rows = connection.execute(sqlalchemy.select([current._table]))
            self.assertEqual(rows.rowcount, len(expected))
            for row in rows:
                self.assertIn(row, expected)

    def test_save_to_sql_flat_fields(self):
        actions = [dict(date="2012-09-23", x=2), dict(date="2012-09-24", x=3)]
        doc = dict(
            actions=actions,
            opened_on="2012-09-23",
            closed_on="2013-09-23",
            get_id="123",
            domain="mock",
            owner_id="test_owner"
        )
        current = MockIndicatorsSqlWithFlatFields(_id='234')
        current.calculate(MockDoc.wrap(doc))
        current.save_to_sql(current.diff(None), self.engine)
        expected = [
            (u'123', date(2012, 9, 24), u'2012-09-23', u'2013-09-23', u'mock', u'test_owner', 3, None, None, None, None, None, 1, None),
            (u'123', date(2013, 1, 1), u'2012-09-23', u'2013-09-23', u'abc', u'123', None, None, 2, None, 1, None, None, None),
            (u'123', date(1, 1, 1), u'2012-09-23', u'2013-09-23', u'abc', u'xyz', None, None, None, 1, None, None, None, None),
            (u'123', date(2012, 9, 23), u'2012-09-23', u'2013-09-23', u'mock', u'test_owner', 2, None, None, None, None, None, 1, None),
            (u'123', date(1, 1, 1), u'2012-09-23', u'2013-09-23', u'mock', u'test_owner', None, None, None, None, None, 2, None, 1),
            (u'123', date(2013, 1, 1), u'2012-09-23', u'2013-09-23', u'abc', u'xyz', None, 3, None, None, None, None, None, None),
        ]

        with self.engine.begin() as connection:
            rows = connection.execute(sqlalchemy.select([current._table]))
            self.assertEqual(rows.rowcount, len(expected))
            for row in rows:
                self.assertIn(row, expected)

    def test_deleting_on_doc_type_change(self):
        actions = [dict(date="2012-09-23", x=2), dict(date="2012-09-24", x=3)]
        doc = dict(
            actions=actions,
            get_id="123",
            domain="mock",
            owner_id="test_owner",
            doc_type='MockDoc'
        )
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            classname = cls.__name__
            pillow = cls.pillow()()
            pillow.process_change(change_from_couch_row({'changes': [], 'id': '123', 'seq': 1, 'doc': doc}))
            indicator = self.fakedb.mock_docs.get("%s-123" % classname, None)
            self.assertIsNotNone(indicator)

        doc['doc_type'] = 'MockArchive'
        for cls in [MockIndicators, MockIndicatorsWithGetters]:
            classname = cls.__name__
            pillow = cls.pillow()()
            pillow.process_change(change_from_couch_row({'changes': [], 'id': '123', 'seq': 1, 'doc': doc}))
            indicator = self.fakedb.mock_docs.get("%s-123" % classname, None)
            self.assertIsNone(indicator)

    def test_deleting_on_doc_type_change_sql(self):
        actions = [dict(date="2012-09-23", x=2), dict(date="2012-09-24", x=3)]
        doc = dict(
            actions=actions,
            get_id="123",
            domain="mock",
            owner_id="test_owner",
            doc_type='MockDoc'
        )

        for cls in [MockIndicatorsSql]:
            pillow = cls.pillow()()
            pillow.process_change(change_from_couch_row({'changes': [], 'id': '123', 'seq': 1, 'doc': doc}))
            with self.engine.begin() as connection:
                rows = connection.execute(sqlalchemy.select([cls._table]))
                self.assertEqual(rows.rowcount, 6)

        doc['doc_type'] = 'MockArchive'
        for cls in [MockIndicatorsSql]:
            pillow = cls.pillow()()
            pillow.process_change(change_from_couch_row({'changes': [], 'id': '123', 'seq': 1, 'doc': doc}))
            with self.engine.begin() as connection:
                rows = connection.execute(sqlalchemy.select([cls._table]))
                self.assertEqual(rows.rowcount, 0)

class MockDoc(Document):
    _doc_type = "Mock"

class MockDocArchive(Document):
    _doc_type = "MockArchive"

class ValueCalculator(fluff.Calculator):

    @fluff.date_emitter
    def date_value(self, case):
        for action in case.actions:
            yield [action['date'], action['x']]

    @fluff.custom_null_emitter('max')
    def null_value(self, case):
        yield [None, 2]

    @fluff.custom_date_emitter('count')
    def date(self, case):
        for action in case.actions:
            yield action['date']

    @fluff.null_emitter
    def null(self, case):
        yield None

    @fluff.date_emitter
    def group_list(self, case):
        yield dict(date=date(2013, 1, 1), value=3, group_by=['abc', 'xyz'])

    @fluff.date_emitter
    def group_val(self, case):
        yield dict(date=date(2013, 1, 1), value=2, group_by=['abc', '123'])

    @fluff.date_emitter
    def group_no_val(self, case):
        yield dict(date=date(2013, 1, 1), group_by=['abc', '123'])

    @fluff.null_emitter
    def group_null(self, case):
        yield dict(group_by=['abc', 'xyz'])

class MockIndicators(fluff.IndicatorDocument):

    document_class = MockDoc
    group_by = ('domain', 'owner_id')
    group_by_type_map = {'domain': fluff.TYPE_INTEGER}
    domains = ('mock',)
    deleted_types = ('MockArchive',)
    save_direct_to_sql = False

    value_week = ValueCalculator(window=WEEK)

    class Meta:
        app_label = 'fluff'

class MockIndicatorsWithGetters(fluff.IndicatorDocument):

    document_class = MockDoc
    group_by = (
        fluff.AttributeGetter('domain'),
        fluff.AttributeGetter('owner_id', getter_function=lambda item: item['owner_id'])
    )
    group_by_type_map = {'domain': fluff.TYPE_INTEGER}
    domains = ('mock',)
    deleted_types = ('MockArchive',)
    save_direct_to_sql = False

    value_week = ValueCalculator(window=WEEK)

    class Meta:
        app_label = 'fluff'

class MockIndicatorsSql(fluff.IndicatorDocument):

    document_class = MockDoc
    group_by = ('domain', 'owner_id')
    group_by_type_map = {'domain': fluff.TYPE_STRING}
    domains = ('mock',)
    deleted_types = ('MockArchive',)

    value_week = ValueCalculator(window=WEEK)

    class Meta:
        app_label = 'fluff'

class MockIndicatorsSqlWithFlatFields(fluff.IndicatorDocument):

    document_class = MockDoc
    group_by = ('domain', 'owner_id')
    group_by_type_map = {'domain': fluff.TYPE_STRING}
    domains = ('mock',)

    opened_on = flat_field(lambda case: case['opened_on'])
    closed_on = flat_field(lambda case: case['closed_on'])
    value_week = ValueCalculator(window=WEEK)

    class Meta:
        app_label = 'fluff'


text:
/**
 * AppView has two global chrome responsibilities:
 * First to listen for active page changes in order to check for a page model
 * aside property in order to render the aside background grad or not.
 * Second to simply instatiate and add the navView element to the DOM.
 */
(function (Portfolio, Backbone) {

    /**
     * @class AppView
     */
    Portfolio.views.AppView = Backbone.View.extend({

        navView: null,

        initialize: function () {
            this.listenTo(this.collection, 'change:active', _handlePageChange);

            this.navView = new Portfolio.views.NavView({
                collection: this.collection
            });
        },

        render: function () {
            this.navView.render();
            this.$el.find('.nav-container').append(this.navView.el);
        }
    });

    //--------------------------------------------------------------------------
    //
    // private methods
    //
    //--------------------------------------------------------------------------

    /**
     * Because the aside background graphic element has to exist in the
     * background element context outside the element managed by any PageView,
     * the AppView takes care of monitoring this by checking for the 'aside'
     * property on the relevent page Model whenever a new page becomes active,
     * and keeping the aside class in sync on the background element.
     *
     * @method  _handlePageChange
     * @private
     *
     * @param  {Model} pageModel page Model of the new active page
     */
    function _handlePageChange (pageModel) {

        var $background = this.$el.find('.background');

        if (pageModel.get('aside')) {
            $background.addClass('aside');
        }
        else {
            $background.removeClass('aside');
        }
    }

}(window.Portfolio, Backbone));

redpajama_set_name: RedPajamaGithub


text:
import Noty from 'noty/lib/noty.js';
import ClipboardJS from 'clipboard/dist/clipboard.js';
import nocache from 'superagent-no-cache';
import request from 'superagent';

!function () {
    let clipboard = new ClipboardJS('.js-clipboard', {
        text: function (trigger) {
            return trigger.innerText;
        }
    });

    // noinspection JSUnresolvedFunction
    clipboard.on('success', function (event) {
        let item = event.trigger;

        item.className += ' copied';

        showNoty(event.text);

        loadPwd(item);
    });

    // noinspection JSUnresolvedFunction
    clipboard.on('error', function (event) {
        console.error(event);
    });

    function showNoty(pwd) {
        let text = 'Copied: ' + pwd + '';

        // noinspection JSUnresolvedFunction
        new Noty({
            text: text,
            layout: 'topCenter',
            theme: 'relax',
            type: 'success',
            timeout: 1000,
            progressBar: false
        }).show();
    }

    function loadPwd(item) {
        let data = {
            length: item.dataset.length,
            number: item.dataset.number,
            mark: item.dataset.mark,
            extra: item.dataset.extra
        };

        request
            .get('/ajax/get-pwd.php')
            .query(data)
            .use(nocache)
            .set('accept', 'json')
            .end((error, result) => {
                if (error) {
                    console.error('error', error);
                } else {
                    if (result.body.error) {
                        console.error('error', result.body.message);
                    } else {
                        setTimeout(function () {
                            item.innerText = result.body.pwd;
                            item.classList.remove('copied');
                        }, 1000);
                    }
                }
            });
    }
}();


text:
namespace Topshelf
{
    using System;
    using HostConfigurators;
    using Runtime;

    public static class InstallHostConfiguratorExtensions
    {
        public static HostConfigurator BeforeInstall(this HostConfigurator configurator, Action callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeInstall",
                x => x.BeforeInstall(settings => callback())));

            return configurator;
        }

        public static HostConfigurator BeforeInstall(this HostConfigurator configurator,
            Action<InstallHostSettings> callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeInstall",
                x => x.BeforeInstall(callback)));

            return configurator;
        }

        public static HostConfigurator AfterInstall(this HostConfigurator configurator, Action callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterInstall",
                x => x.AfterInstall(settings => callback())));

            return configurator;
        }

        public static HostConfigurator AfterInstall(this HostConfigurator configurator,
            Action<InstallHostSettings> callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterInstall", x => x.AfterInstall(callback)));

            return configurator;
        }

        public static HostConfigurator BeforeRollback(this HostConfigurator configurator, Action callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeRollback",
                x => x.BeforeRollback(settings => callback())));

            return configurator;
        }

        public static HostConfigurator BeforeRollback(this HostConfigurator configurator,
            Action<InstallHostSettings> callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeRollback",
                x => x.BeforeRollback(callback)));

            return configurator;
        }

        public static HostConfigurator AfterRollback(this HostConfigurator configurator, Action callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterRollback",
                x => x.AfterRollback(settings => callback())));

            return configurator;
        }

        public static HostConfigurator AfterRollback(this HostConfigurator configurator,
            Action<InstallHostSettings> callback)
        {
            if (configurator == null)
                throw new ArgumentNullException("configurator");

            configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterRollback",
                x => x.AfterRollback(callback)));

            return configurator;
        }
    }
}


text:
WEBDATA_EXPORT extern const base::FilePath::CharType kWebDataFilename[];

// Note: On desktop, the account-scoped web data store is only stored in memory,
// so doesn't have a file path. So this constant only exists on mobile.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
WEBDATA_EXPORT extern const base::FilePath::CharType kAccountWebDataFilename[];
#endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)

#endif  // COMPONENTS_WEBDATA_COMMON_WEBDATA_CONSTANTS_H_


text:
package com.quizbowl.app.dataStore;

public class TFstore {
	private String question,answer;
	private int points;

	public TFstore(String question,String answer,int points)
	{
		this.question = question;
		this.answer = answer;
		this.points = points;
	}
	public String getQuestion()
	{
		return this.question;
	}
	public String getAnswer()
	{
		return this.answer;
	}
	public int getPoints()
	{
		return this.points;
	}
}


text:
Puppet::Type.newtype(:trove_datastore) do

  @doc = "Manage creation of Trove datastores"

  ensurable

  newparam(:name, :namevar => true) do
    desc "Datastore version name)"
    newvalues(/^.*$/)
  end

  newparam(:version) do
    desc "Datastore version name"
  end

  newproperty(:id) do
    validate do |v|
      raise(Puppet::Error, 'This is a read only property')
    end
  end

  validate do
    raise(Puppet::Error, 'Version must be set') unless self[:version]
  end
end


text:
package MySource;

use strict;
use vars '@ISA';

use MyCustom;
use TAP::Parser::Source;

@ISA = qw( TAP::Parser::Source MyCustom );

sub _initialize {
    my $self = shift;
    $self->SUPER::_initialize(@_);
    $main::INIT{ ref($self) }++;
    $self->{initialized} = 1;
    return $self;
}

sub source {
    my $self = shift;
    return $self->SUPER::source(@_);
}

sub get_stream {
    my $self   = shift;
    my $stream = $self->SUPER::get_stream(@_);

    # re-bless it:
    bless $stream, 'MyIterator';
}

1;


text:
import { Settings } from '../../../settings/models/settings';

export class RetrieveSettings {
  static readonly type = '[Settings] Get settings from backend';
}

export class SetSettings {
  static readonly type = '[Settings] Modify settings according to user input';
  constructor(public settings: Settings) {}
}


text:
<resources>
    <string name="app_name">ToStringContainsDemo</string>
</resources>


text:
module ImdbListParser
  module SharedMethods
    def movies
      @movies ||= elements.inject([]) { |acc, html| acc << html.elements[1].elements[0].child.inner_text }
    end

    def display(*options)
      movies.each_with_index.inject([]) do |acc, (mov, ind)|
        acc << ([mov] + valid_methods(options).map { |meth| meth[ind] })
      end
    end

    def find_rank(movie)
      ind = movies.map(&:downcase).index(movie.downcase) || 'Unable to locate movie in the list.'
      ind.to_s =~ /\d+/ ? ind + 1 : ind
    end

    private

    def elements
      @elements ||= html.css('tbody.lister-list tr').inject([]) { |acc, elements| acc << elements }
    end

    def html
      @html ||= Nokogiri::HTML(open(@url))
    end

    def years
      @years ||= elements.inject([]) { |acc, html| acc << html.elements[1].elements[1].children.inner_text[/\d+/] }
    end

    def ratings
      @ratings ||= elements.inject([]) { |acc, html| acc << html.elements[2].children.children.inner_text }
    end

    def valid_methods(arr)
      arr.map { |meth| instance_eval(meth.to_s) if SharedMethods.private_method_defined?(meth) }.compact
    end
  end
end


text:
package org.apache.flink.runtime.taskexecutor;

import org.apache.flink.api.common.resources.CPUResource;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.IllegalConfigurationException;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.util.TestLogger;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/** Test suite for {@link TaskExecutorResourceUtils}. */
public class TaskExecutorResourceUtilsTest extends TestLogger {
	private static final double CPU_CORES = 1.0;
	private static final MemorySize TASK_HEAP = MemorySize.ofMebiBytes(1);
	private static final MemorySize TASK_OFF_HEAP = MemorySize.ofMebiBytes(2);
	private static final MemorySize NETWORK = MemorySize.ofMebiBytes(3);
	private static final MemorySize MANAGED = MemorySize.ofMebiBytes(4);

	@Test
	public void testResourceSpecFromConfig() {
		TaskExecutorResourceSpec resourceSpec = TaskExecutorResourceUtils.resourceSpecFromConfig(createValidConfig());
		assertThat(resourceSpec.getCpuCores(), is(new CPUResource(CPU_CORES)));
		assertThat(resourceSpec.getTaskHeapSize(), is(TASK_HEAP));
		assertThat(resourceSpec.getTaskOffHeapSize(), is(TASK_OFF_HEAP));
		assertThat(resourceSpec.getNetworkMemSize(), is(NETWORK));
		assertThat(resourceSpec.getManagedMemorySize(), is(MANAGED));
	}

	@Test(expected = IllegalConfigurationException.class)
	public void testResourceSpecFromConfigFailsIfNetworkSizeIsNotFixed() {
		Configuration configuration = createValidConfig();
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, MemorySize.ofMebiBytes(1));
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MAX, MemorySize.ofMebiBytes(2));
		TaskExecutorResourceUtils.resourceSpecFromConfig(configuration);
	}

	@Test
	public void testResourceSpecFromConfigFailsIfRequiredOptionIsNotSet() {
		TaskExecutorResourceUtils.CONFIG_OPTIONS.stream()
			.filter(option -> !option.hasDefaultValue())
			.forEach(option -> {
				try {
					TaskExecutorResourceUtils.resourceSpecFromConfig(setAllRequiredOptionsExceptOne(option));
					fail("should fail with " + IllegalConfigurationException.class.getSimpleName());
				} catch (IllegalConfigurationException e) {
					// expected
				}
			});
	}

	@Test
	public void testAdjustForLocalExecution() {
		Configuration configuration = TaskExecutorResourceUtils.adjustForLocalExecution(new Configuration());

		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MIN), is(TaskExecutorResourceUtils.DEFAULT_SHUFFLE_MEMORY_SIZE));
		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MAX), is(TaskExecutorResourceUtils.DEFAULT_SHUFFLE_MEMORY_SIZE));
		assertThat(configuration.get(TaskManagerOptions.MANAGED_MEMORY_SIZE), is(TaskExecutorResourceUtils.DEFAULT_MANAGED_MEMORY_SIZE));
	}

	@Test
	public void testNetworkMinAdjustForLocalExecutionIfMaxSet() {
		MemorySize networkMemorySize = MemorySize.ofMebiBytes(1);
		Configuration configuration = new Configuration();
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MAX, networkMemorySize);
		TaskExecutorResourceUtils.adjustForLocalExecution(configuration);

		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MIN), is(networkMemorySize));
		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MAX), is(networkMemorySize));
	}

	@Test
	public void testNetworkMaxAdjustForLocalExecutionIfMinSet() {
		MemorySize networkMemorySize = MemorySize.ofMebiBytes(1);
		Configuration configuration = new Configuration();
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, networkMemorySize);
		TaskExecutorResourceUtils.adjustForLocalExecution(configuration);

		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MIN), is(networkMemorySize));
		assertThat(configuration.get(TaskManagerOptions.NETWORK_MEMORY_MAX), is(networkMemorySize));
	}

	private static Configuration createValidConfig() {
		Configuration configuration = new Configuration();
		configuration.set(TaskManagerOptions.CPU_CORES, CPU_CORES);
		configuration.set(TaskManagerOptions.TASK_HEAP_MEMORY, TASK_HEAP);
		configuration.set(TaskManagerOptions.TASK_OFF_HEAP_MEMORY, TASK_OFF_HEAP);
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, NETWORK);
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MAX, NETWORK);
		configuration.set(TaskManagerOptions.MANAGED_MEMORY_SIZE, MANAGED);
		return configuration;
	}

	private static Configuration setAllRequiredOptionsExceptOne(ConfigOption<?> optionToNotSet) {
		Configuration configuration = new Configuration();
		if (!TaskManagerOptions.CPU_CORES.equals(optionToNotSet)) {
			configuration.set(TaskManagerOptions.CPU_CORES, 1.0);
		}

		// skip network to exclude min/max mismatch config failure
		MemorySize network = MemorySize.ofMebiBytes(3);
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, network);
		configuration.set(TaskManagerOptions.NETWORK_MEMORY_MAX, network);

		//noinspection unchecked
		TaskExecutorResourceUtils.CONFIG_OPTIONS
			.stream()
			.filter(option -> !option.equals(TaskManagerOptions.CPU_CORES))
			.filter(option -> !option.equals(optionToNotSet))
			.forEach(option -> configuration.set((ConfigOption<MemorySize>) option, MemorySize.ofMebiBytes(1)));

		return configuration;
	}
}


text:
import React, { FC, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import {
  Modal,
  ModalHeader,
  ModalFooter,
  Button,
  Anchor,
  Alert,
} from '@keen.io/ui-core';
import { BodyText } from '@keen.io/typography';

import {
  Container,
  Description,
  EmailExtraction,
  Footer,
  Cancel,
} from './ConfirmExtraction.styles';

import {
  getExtractionConfirmation,
  queriesActions,
} from '../../modules/queries';

const ConfirmExtraction: FC = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const { isVisible } = useSelector(getExtractionConfirmation);

  const closeHandler = useCallback(
    () => dispatch(queriesActions.cancelExtraction()),
    []
  );

  return (
    <Modal isOpen={isVisible} onClose={closeHandler}>
      {() => (
        <>
          <ModalHeader onClose={closeHandler}>
            {t('extraction_confirmation.title')}
          </ModalHeader>
          <Container>
            <Alert type="info">{t('extraction_confirmation.alert')}</Alert>
            <Description>
              <BodyText variant="body1">
                {t('extraction_confirmation.message')}
              </BodyText>
            </Description>
          </Container>
          <ModalFooter>
            <Footer>
              <Button
                variant="secondary"
                onClick={() => {
                  dispatch(queriesActions.continueExtraction());
                }}
              >
                {t('extraction_confirmation.confirm_button')}
              </Button>
              <EmailExtraction>
                <Button
                  variant="secondary"
                  onClick={() => {
                    dispatch(queriesActions.cancelExtraction());
                    dispatch(queriesActions.extractToEmail());
                  }}
                >
                  {t('extraction_confirmation.extract_email_button')}
                </Button>
              </EmailExtraction>
              <Cancel>
                <Anchor onClick={closeHandler}>
                  {t('extraction_confirmation.cancel')}
                </Anchor>
              </Cancel>
            </Footer>
          </ModalFooter>
        </>
      )}
    </Modal>
  );
};

export default ConfirmExtraction;


text:
  <title>Timer</title>

  Reload page timer AJAX timer
  Long polling messenger Websocket chat

Client time:

Server time:


text:
<?php

namespace Stati\Site;

use Liquid\Liquid;
use Stati\Entity\Collection;
use Stati\Entity\Doc;
use Stati\Event\ConsoleOutputEvent;
use Stati\Event\WillResetSiteEvent;
use Stati\Reader\CollectionReader;
use Stati\Reader\StaticFileReader;
use Stati\Reader\PageReader;
use Stati\Reader\DataReader;
use Stati\Renderer\CollectionRenderer;
use Stati\Renderer\PageRenderer;
use Stati\Writer\CollectionWriter;
use Stati\Writer\StaticFileWriter;
use Stati\Writer\PageWriter;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Stati\Site\SiteEvents;
use Stati\Event\DidResetSiteEvent;
use Stati\Event\WillReadSiteEvent;
use Stati\Event\SiteEvent;

class Site
{
    /**
     * Config from _config.yml
     *
     * @var array
     */
    protected $config;

    /**
     * @var array
     */
    protected $posts;

    /**
     * @var array
     */
    protected $pages;

    /**
     * @var array
     */
    protected $staticFiles;

    /**
     * @var array
     */
    protected $relatedPosts;

    /**
     * @var array
     */
    protected $collections = [];

    /**
     * @var array
     */
    protected $data = [];

    /**
     * @var EventDispatcherInterface
     */
    protected $dispatcher;

    /**
     * @var string Site generation time
     */
    protected $time;

    /**
     * @var string
     */
    protected $toString;

    public function __construct(array $config)
    {
        $this->config = new Config($config);

        $this->config["cache_dir"] = sys_get_temp_dir() . '/' . $this->config['name'];

        if (!is_dir($this->config["cache_dir"])) {
            mkdir($this->config["cache_dir"], 0777, true);
        }

        $this->config['collections'] = array_merge($this->config['collections'], [
            'posts' => [
                'permalink' => $this->config['permalink'],
                'output' => true,
            ]
        ]);

        $this->dispatcher = new EventDispatcher();
    }

    public function process()
    {
        $this->dispatcher->dispatch(SiteEvents::WILL_PROCESS_SITE, new SiteEvent($this));

        $this->reset();

        $this->read();

        $this->generate();

        $this->render();

        $this->write();

        $this->dispatcher->dispatch(SiteEvents::DID_PROCESS_SITE, new SiteEvent($this));
    }

    public function reset()
    {
        $fs = new Filesystem();
        $this->dispatcher->dispatch(SiteEvents::WILL_RESET_SITE, new WillResetSiteEvent($this, $fs));
        $fs->remove($this->getDestination());
        $fs->mkdir($this->getDestination());
        $this->dispatcher->dispatch(SiteEvents::DID_RESET_SITE, new DidResetSiteEvent($this, $fs));
    }

    public function read()
    {
        //Read static files
        $this->dispatcher->dispatch(SiteEvents::WILL_READ_SITE, new WillReadSiteEvent($this));
        $this->dispatcher->dispatch(SiteEvents::WILL_READ_STATIC_FILES, new SiteEvent($this));
        $staticFileReader = new StaticFileReader($this);
        $this->setStaticFiles($staticFileReader->read());
        $this->dispatcher->dispatch(SiteEvents::DID_READ_STATIC_FILES, new SiteEvent($this));

        $this->dispatcher->dispatch(SiteEvents::WILL_READ_COLLECTIONS, new SiteEvent($this));
        //Read collections
        $collectionReader = new CollectionReader($this);
        $this->setCollections($collectionReader->read());
        $this->dispatcher->dispatch(SiteEvents::DID_READ_COLLECTIONS, new SiteEvent($this));

        $this->dispatcher->dispatch(SiteEvents::WILL_READ_PAGES, new SiteEvent($this));
        //Read pages
        $pageReader = new PageReader($this);
        $this->setPages($pageReader->read());
        $this->dispatcher->dispatch(SiteEvents::DID_READ_PAGES, new SiteEvent($this));

        $this->dispatcher->dispatch(SiteEvents::WILL_READ_DATA, new SiteEvent($this));
        //Read pages
        $dataReader = new DataReader($this);
        $this->setData($dataReader->read());
        $this->dispatcher->dispatch(SiteEvents::DID_READ_DATA, new SiteEvent($this));
        $this->dispatcher->dispatch(SiteEvents::DID_READ_SITE, new SiteEvent($this));
    }

    public function generate()
    {
        $this->dispatcher->dispatch(SiteEvents::WILL_GENERATE_SITE, new SiteEvent($this));
        $this->dispatcher->dispatch(SiteEvents::DID_GENERATE_SITE, new SiteEvent($this));
    }

    public function render()
    {
        $this->dispatcher->dispatch(SiteEvents::WILL_RENDER_SITE, new SiteEvent($this));
        $this->dispatcher->dispatch(SiteEvents::WILL_RENDER_COLLECTIONS, new SiteEvent($this));

        //Render Collections
        $collectionRenderer = new CollectionRenderer($this);
        $this->setCollections($collectionRenderer->renderAll());
        $this->dispatcher->dispatch(SiteEvents::DID_RENDER_COLLECTIONS, new SiteEvent($this));

        //Render Pages
        $this->dispatcher->dispatch(SiteEvents::WILL_RENDER_PAGES, new SiteEvent($this));
        $pageRenderer = new PageRenderer($this);
        $this->setPages($pageRenderer->renderAll());
        $this->dispatcher->dispatch(SiteEvents::DID_RENDER_PAGES, new SiteEvent($this));

        $this->dispatcher->dispatch(SiteEvents::DID_RENDER_SITE, new SiteEvent($this));
    }

    public function write()
    {
        $this->dispatcher->dispatch(SiteEvents::WILL_WRITE_SITE, new SiteEvent($this));
        // Write static files
        $this->dispatcher->dispatch(SiteEvents::WILL_WRITE_STATIC_FILES, new SiteEvent($this));

        $staticFileWriter = new StaticFileWriter($this);
        $staticFileWriter->writeAll();
        $this->dispatcher->dispatch(SiteEvents::DID_WRITE_STATIC_FILES, new SiteEvent($this));

        // Write Collection files
        $this->dispatcher->dispatch(SiteEvents::WILL_WRITE_COLLECTIONS, new SiteEvent($this));
        $collectionWriter = new CollectionWriter($this);
        $collectionWriter->writeAll();
        $this->dispatcher->dispatch(SiteEvents::DID_WRITE_COLLECTIONS, new SiteEvent($this));

        // Write Page files
        $this->dispatcher->dispatch(SiteEvents::WILL_WRITE_PAGES, new SiteEvent($this));
        $pageWriter = new PageWriter($this);
        $pageWriter->writeAll();
        $this->dispatcher->dispatch(SiteEvents::DID_WRITE_PAGES, new SiteEvent($this));
        $this->dispatcher->dispatch(SiteEvents::DID_WRITE_SITE, new SiteEvent($this));
    }

    /**
     * @param $item
     * @return mixed
     */
    public function __get($item = null)
    {
        if (!$item) {
            return null;
        }
        $getter = implode('', array_map(function ($part) {
            return ucfirst($part);
        }, explode('_', $item)));
        $field = lcfirst($getter);

        //If the method exists, return it
        if (method_exists($this, 'get'.$getter)) {
            return $this->{'get'.$getter}();
        }

        //If the property exists, return it
        if (property_exists(self::class, $field)) {
            return $this->{$field};
        }

        // If it's a collection, return the corresponding one
        if (isset($this->collections[$item])) {
            return $this->collections[$item]->getDocs();
        }

        // If this is a data item, return it;
        if (isset($this->data[$item])) {
            return $this->data[$item];
        }

        // If this is a config item, return it;
        if (isset($this->config[$item])) {
            return $this->config[$item];
        }

        return null;
    }

    public function __set($name, $value)
    {
        $this->{$name} = $value;
    }

    public function get($item)
    {
        return $this->__get($item);
    }

    public function field_exists($item)
    {
        return true;
    }

    public function getTime()
    {
        if ($this->time) {
            return $this->time;
        }
        $this->time = date_create()->format(DATE_RFC3339);
        return $this->time;
    }

    public function getDestination()
    {
        if (isset($this->config['destination'])) {
            return $this->config['destination'];
        }
        return './_site/';
    }

    /**
     * @return array
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param array $config
     */
    public function setConfig($config)
    {
        $this->config = $config;
    }

    /**
     * @return array
     */
    public function getPosts()
    {
        if (isset($this->collections['posts'])) {
            return $this->collections['posts']->getDocs();
        }
        $col = new Collection('posts');
        return $col->getDocs();
    }

    /**
     * @param Collection $posts
     */
    public function setPosts($posts)
    {
        $this->posts = $posts;
    }

    /**
     * @return array
     */
    public function getPages()
    {
        return $this->pages;
    }

    /**
     * @param array $pages
     */
    public function setPages($pages)
    {
        $this->pages = $pages;
    }

    /**
     * @param Doc $page
     */
    public function addPage($page)
    {
        $this->pages[] = $page;
    }

    /**
     * @return array
     */
    public function getStaticFiles()
    {
        return $this->staticFiles;
    }

    /**
     * @param array $staticFiles
     */
    public function setStaticFiles($staticFiles)
    {
        $this->staticFiles = $staticFiles;
    }

    /**
     * @return array
     */
    public function getRelatedPosts()
    {
        return $this->relatedPosts;
    }

    /**
     * @param array $relatedPosts
     */
    public function setRelatedPosts($relatedPosts)
    {
        $this->relatedPosts = $relatedPosts;
    }

    /**
     * @return array
     */
    public function getCollections()
    {
        return $this->collections;
    }

    /**
     * @param array $collections
     */
    public function setCollections($collections)
    {
        $this->collections = $collections;
    }

    /**
     * @return EventDispatcherInterface
     */
    public function getDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * @param EventDispatcherInterface $dispatcher
     */
    public function setDispatcher($dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param array $data
     */
    public function setData(array $data)
    {
        $this->data = $data;
    }

    public function __toString()
    {
        if ($this->toString) {
            return $this->toString;
        }

        $str = implode('', self::arrayFlattenToString($this->config));
        $str .= implode('', self::arrayFlattenToString($this->data));
        $cols = array_map(function ($col) {
            /**
             * @var Collection $col
             */
            return implode('', array_map(function ($doc) {
                /**
                 * @var Doc $doc
                 */
                return $doc->getCacheFilename();
            }, $col->getDocs()));
        }, array_values($this->collections));

        $str .= implode('', $cols);
        $this->toString = $str;
        return $str;
    }

    public static function arrayFlattenToString($array)
    {
        $return = array();
        if (is_array($array)) {
            foreach ($array as $element) {
                if (is_array($element)) {
                    $return = array_merge($return, self::arrayFlattenToString($element));
                } elseif (is_object($element)) {
                    $return[] = (string)$element;
                } else {
                    $return[] = $element;
                }
            }
        }

        return $return;
    }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/PlatformValues.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ImportInstanceVolumeDetailItem.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes an import instance task.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API ImportInstanceTaskDetails
  {
  public:
    ImportInstanceTaskDetails();
    ImportInstanceTaskDetails(const Aws::Utils::Xml::XmlNode& xmlNode);
    ImportInstanceTaskDetails& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
A description of the task.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
A description of the task.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
A description of the task.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
A description of the task.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
A description of the task.

     */
    inline ImportInstanceTaskDetails& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
A description of the task.

     */
    inline ImportInstanceTaskDetails& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
A description of the task.

     */
    inline ImportInstanceTaskDetails& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The ID of the instance.

     */
    inline const Aws::String& GetInstanceId() const{ return m_instanceId; }

    /**
     *
The ID of the instance.

     */
    inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; }

    /**
     *
The ID of the instance.

     */
    inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); }

    /**
     *
The ID of the instance.

     */
    inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); }

    /**
     *
The ID of the instance.

     */
    inline ImportInstanceTaskDetails& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;}

    /**
     *
The ID of the instance.

     */
    inline ImportInstanceTaskDetails& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;}

    /**
     *
The ID of the instance.

     */
    inline ImportInstanceTaskDetails& WithInstanceId(const char* value) { SetInstanceId(value); return *this;}

    /**
     *
The instance operating system.

     */
    inline const PlatformValues& GetPlatform() const{ return m_platform; }

    /**
     *
The instance operating system.

     */
    inline void SetPlatform(const PlatformValues& value) { m_platformHasBeenSet = true; m_platform = value; }

    /**
     *
The instance operating system.

     */
    inline void SetPlatform(PlatformValues&& value) { m_platformHasBeenSet = true; m_platform = std::move(value); }

    /**
     *
The instance operating system.

     */
    inline ImportInstanceTaskDetails& WithPlatform(const PlatformValues& value) { SetPlatform(value); return *this;}

    /**
     *
The instance operating system.

     */
    inline ImportInstanceTaskDetails& WithPlatform(PlatformValues&& value) { SetPlatform(std::move(value)); return *this;}

    /**
     *
One or more volumes.

     */
    inline const Aws::Vector<ImportInstanceVolumeDetailItem>& GetVolumes() const{ return m_volumes; }

    /**
     *
One or more volumes.

     */
    inline void SetVolumes(const Aws::Vector<ImportInstanceVolumeDetailItem>& value) { m_volumesHasBeenSet = true; m_volumes = value; }

    /**
     *
One or more volumes.

     */
    inline void SetVolumes(Aws::Vector<ImportInstanceVolumeDetailItem>&& value) { m_volumesHasBeenSet = true; m_volumes = std::move(value); }

    /**
     *
One or more volumes.

     */
    inline ImportInstanceTaskDetails& WithVolumes(const Aws::Vector<ImportInstanceVolumeDetailItem>& value) { SetVolumes(value); return *this;}

    /**
     *
One or more volumes.

     */
    inline ImportInstanceTaskDetails& WithVolumes(Aws::Vector<ImportInstanceVolumeDetailItem>&& value) { SetVolumes(std::move(value)); return *this;}

    /**
     *
One or more volumes.

     */
    inline ImportInstanceTaskDetails& AddVolumes(const ImportInstanceVolumeDetailItem& value) { m_volumesHasBeenSet = true; m_volumes.push_back(value); return *this; }

    /**
     *
One or more volumes.

     */
    inline ImportInstanceTaskDetails& AddVolumes(ImportInstanceVolumeDetailItem&& value) { m_volumesHasBeenSet = true; m_volumes.push_back(std::move(value)); return *this; }

  private:
    Aws::String m_description;
    bool m_descriptionHasBeenSet;
    Aws::String m_instanceId;
    bool m_instanceIdHasBeenSet;
    PlatformValues m_platform;
    bool m_platformHasBeenSet;
    Aws::Vector<ImportInstanceVolumeDetailItem> m_volumes;
    bool m_volumesHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
package de.codecentric.resilient.booking.commands;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import de.codecentric.resilient.dto.ConnoteDTO;

/**
 * @author Benjamin Wilms
 */
public class ConnoteCommand extends HystrixCommand<ConnoteDTO> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConnoteCommand.class);

    private final RestTemplate restTemplate;

    private final boolean secondTry;

    public ConnoteCommand(RestTemplate restTemplate, boolean secondTry) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ConnoteServiceClientGroup"))
            .andCommandKey(HystrixCommandKey.Factory.asKey("ConnoteServiceClient")));
        this.restTemplate = restTemplate;
        this.secondTry = secondTry;
    }

    @Override
    protected ConnoteDTO run() throws Exception {
        return restTemplate.getForObject("http://connote-service/rest/connote/create", ConnoteDTO.class);
    }

    @Override
    protected ConnoteDTO getFallback() {

        if (secondTry) {
            LOGGER.debug(LOGGER.isDebugEnabled() ? "Second Connote Service Call started" : null);

            ConnoteCommand connoteCommand = new ConnoteCommand(restTemplate, false);
            return connoteCommand.execute();

        } else {

            LOGGER.debug(LOGGER.isDebugEnabled() ? "Fallback Connote Service call" : null);

            ConnoteDTO connoteDTO = new ConnoteDTO();
            connoteDTO.setFallback(true);

            if (getExecutionException() != null) {
                Exception exceptionFromThrowable = getExceptionFromThrowable(getExecutionException());

                if (exceptionFromThrowable == null) {
                    connoteDTO.setErrorMsg("Unable to check exception type");

                } else if (exceptionFromThrowable instanceof HystrixRuntimeException) {
                    HystrixRuntimeException hystrixRuntimeException = (HystrixRuntimeException) exceptionFromThrowable;
                    connoteDTO.setErrorMsg(hystrixRuntimeException.getFailureType().name());

                } else if (exceptionFromThrowable instanceof HystrixTimeoutException) {
                    connoteDTO.setErrorMsg(HystrixRuntimeException.FailureType.TIMEOUT.name());
                } else {

                    connoteDTO.setErrorMsg(exceptionFromThrowable.getMessage());
                }

            } else
                connoteDTO.setErrorMsg("unable to create connote");
            return connoteDTO;
        }
    }
}


text:
from google.analytics import admin_v1alpha

async def sample_get_display_video360_advertiser_link_proposal():
    # Create a client
    client = admin_v1alpha.AnalyticsAdminServiceAsyncClient()

    # Initialize request argument(s)
    request = admin_v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest(
        name="name_value",
    )

    # Make the request
    response = await client.get_display_video360_advertiser_link_proposal(request=request)

    # Handle the response
    print(response)

# [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDisplayVideo360AdvertiserLinkProposal_async]


text:
package drone_slam.base.navdata;

import java.util.EventListener;

public interface WifiListener extends EventListener {

    public void received(long link_quality);

}


text:
"""Top-level presubmit script for content/test/gpu.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""

USE_PYTHON3 = True

EXTRA_PATHS_COMPONENTS = [
    ('build', ),
    ('build', 'fuchsia'),
    ('build', 'util'),
    ('testing', ),
    ('third_party', 'catapult', 'common', 'py_utils'),
    ('third_party', 'catapult', 'devil'),
    ('third_party', 'catapult', 'telemetry'),
    ('third_party', 'catapult', 'third_party', 'typ'),
    ('tools', 'perf'),
]

def CommonChecks(input_api, output_api):
  results = []

  gpu_env = dict(input_api.environ)
  current_path = input_api.PresubmitLocalPath()
  chromium_src_path = input_api.os_path.realpath(
      input_api.os_path.join(current_path, '..', '..', '..'))
  testing_path = input_api.os_path.join(chromium_src_path, 'testing')
  gpu_env.update({
      'PYTHONPATH':
      input_api.os_path.pathsep.join([testing_path, current_path]),
      'PYTHONDONTWRITEBYTECODE':
      '1',
  })

  gpu_tests = [
      input_api.Command(
          name='run_content_test_gpu_unittests',
          cmd=[input_api.python3_executable, 'run_unittests.py', 'gpu_tests'],
          kwargs={'env': gpu_env},
          message=output_api.PresubmitError,
          python3=True),
      input_api.Command(name='validate_tag_consistency',
                        cmd=[
                            input_api.python3_executable,
                            'validate_tag_consistency.py', 'validate'
                        ],
                        kwargs={},
                        message=output_api.PresubmitError,
                        python3=True),
  ]
  results.extend(input_api.RunTests(gpu_tests))

  results.extend(
      input_api.canned_checks.RunUnitTestsInDirectory(
          input_api,
          output_api,
          input_api.os_path.join(input_api.PresubmitLocalPath(),
                                 'unexpected_passes'), [r'^.+_unittest\.py$'],
          env=gpu_env,
          run_on_python2=False,
          run_on_python3=True,
          skip_shebang_check=True))

  results.extend(
      input_api.canned_checks.RunUnitTestsInDirectory(
          input_api,
          output_api,
          input_api.os_path.join(input_api.PresubmitLocalPath(),
                                 'flake_suppressor'), [r'^.+_unittest\.py$'],
          env=gpu_env,
          run_on_python2=False,
          run_on_python3=True,
          skip_shebang_check=True))

  pylint_extra_paths = [
      input_api.os_path.join(chromium_src_path, *component)
      for component in EXTRA_PATHS_COMPONENTS
  ]
  pylint_checks = input_api.canned_checks.GetPylint(
      input_api,
      output_api,
      extra_paths_list=pylint_extra_paths,
      pylintrc='pylintrc',
      version='2.7')
  results.extend(input_api.RunTests(pylint_checks))

  results.extend(CheckForNewSkipExpectations(input_api, output_api))
  results.extend(CheckPytypePathsInSync(input_api, output_api))

  return results

def CheckForNewSkipExpectations(input_api, output_api):
  """Checks for and dissuades the addition of new Skip expectations."""
  new_skips = []
  expectation_file_dir = input_api.os_path.join(input_api.PresubmitLocalPath(),
                                                'gpu_tests',
                                                'test_expectations')
  file_filter = lambda f: f.AbsoluteLocalPath().startswith(expectation_file_dir)
  for affected_file in input_api.AffectedFiles(file_filter=file_filter):
    for _, line in affected_file.ChangedContents():
      if input_api.re.search(r'\[\s*Skip\s*\]', line):
        new_skips.append((affected_file, line))
  result = []
  if new_skips:
    warnings = []
    for affected_file, line in new_skips:
      warnings.append('  Line "%s" in file %s' %
                      (line, affected_file.LocalPath()))
    result.append(
        output_api.PresubmitPromptWarning(
            'Suspected new Skip expectations found:\n%s\nPlease only use such '
            'expectations when they are strictly necessary, e.g. the test is '
            'impacting other tests. Otherwise, opt for a '
            'Failure/RetryOnFailure expectation.' % '\n'.join(warnings)))
  return result

def CheckPytypePathsInSync(input_api, output_api):
  """Checks that run_pytype.py's paths are in sync with PRESUBMIT.py's"""
  filepath = input_api.os_path.join(input_api.PresubmitLocalPath(),
                                    'run_pytype.py')
  with open(filepath) as infile:
    contents = infile.read()
  # Grab the EXTRA_PATHS_COMPONENTS = [...] portion as a string.
  match = input_api.re.search(r'(EXTRA_PATHS_COMPONENTS\s*=\s*[^=]*\]\n)',
                              contents, input_api.re.DOTALL)
  if not match:
    return [
        output_api.PresubmitError(
            'Unable to find EXTRA_PATHS_COMPONENTS in run_pytype.py. Maybe '
            'the code in PRESUBMIT.py needs to be updated?')
    ]
  expression = match.group(0)
  expression = expression.split('=', 1)[1]
  expression = expression.lstrip()
  pytype_path_components = input_api.ast.literal_eval(expression)
  if EXTRA_PATHS_COMPONENTS != pytype_path_components:
    return [
        output_api.PresubmitError(
            'EXTRA_PATHS_COMPONENTS is not synced between PRESUBMIT.py and '
            'run_pytype.py, please ensure they are identical.')
    ]
  return []

def CheckChangeOnUpload(input_api, output_api):
  return CommonChecks(input_api, output_api)

def CheckChangeOnCommit(input_api, output_api):
  return CommonChecks(input_api, output_api)


text:
make html
rsync --delete -az _build/html/ ~/src/sjl.bitbucket.org/flask-lesscss
hg -R ~/src/sjl.bitbucket.org commit -Am 'flask-lesscss: Update documentation.'
hg -R ~/src/sjl.bitbucket.org push


text:
package org.socialsignin.springframework.data.dynamodb.demo.domain;

import javax.validation.constraints.NotNull;

import org.springframework.data.annotation.Id;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * This is a clone of the Reply class in the AmazonDB examples at
 * http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/
 * JavaQueryScanORMModelExample.html
 *
 * The Reply table has a composite primary key ( hash and range). For
 * spring-data-dynamodb to support datatypes with composite keys, the composite
 * keys must be encapuslated in a separate class, resulting in a single primary
 * key attribute annotated with @Id.
 *
 * This class has therefore been modified slightly - the id and replyDateTime
 * attributes were properties of this class, but they are now part of the
 * ReplyId composite id class which is referenced. Setters and getters must be
 * still provided for the Amazon databinding to function - these are now
 * delegator methods for the attributes of the referenced composite id.
 *
 * @author Michael Lavelle
 */
@DynamoDBTable(tableName = "Reply")
public class Reply {

	@Id
	private ReplyId replyId;
	@NotNull
	private String message;
	private String postedBy;

	@DynamoDBHashKey(attributeName = "Id")
	@DynamoDBMarshalling(marshallerClass=ThreadIdMarshaller.class)
	public ThreadId getThreadId() {
		return replyId != null ? replyId.getThreadId() : null;
	}

	public void setThreadId(ThreadId id) {

		if (replyId == null) {
			replyId = new ReplyId();
		}
		replyId.setThreadId(id);

	}

	@DynamoDBRangeKey(attributeName = "ReplyDateTime")
	public String getReplyDateTime() {
		return replyId != null ? replyId.getReplyDateTime() : null;
	}

	public void setReplyDateTime(String replyDateTime) {

		if (replyId == null) {
			replyId = new ReplyId();
		}
		replyId.setReplyDateTime(replyDateTime);

	}

	@DynamoDBAttribute(attributeName = "Message")
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@DynamoDBAttribute(attributeName = "PostedBy")
	public String getPostedBy() {
		return postedBy;
	}

	public void setPostedBy(String postedBy) {
		this.postedBy = postedBy;
	}
}


text:
"""
Flask - Hello World
"""

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api')
def my_microservice():
    return jsonify({'Hello': 'World'})

if __name__ == "__main__":
    app.run()


text: - Implement more MapFuncs in CoreMap for SparkCore


text:
class UserFilteringField < ActiveRecord::Base

  attr_accessible :user_id, :filtering_field_id, :field_value
  ###
  ### Relationships
  ###

  belongs_to :user
  belongs_to :filtering_field

  ###
  ###  Validations
  ###
  validates_uniqueness_of :user_id, :scope => :filtering_field_id
end

# == Schema Information
#
# Table name: user_filtering_fields
#
#  id                 :integer          not null, primary key
#  user_id            :integer          not null
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#  filtering_field_id :integer          not null
#  field_value        :string(255)
#


text:
{% extends "base.html" %}

{% block content %}

{{ _('Edit Your Profile') }}

{% include 'flash.html' %}

    <form class="form-horizontal" action="" method="post" name="edit">
        {{form.hidden_tag()}}

            {{ _('Your nickname:') }}

                {{ form.nickname(maxlength = 64, class = "span4") }}
                {% for error in form.errors.nickname %}
                    [{{error}}]

                {% endfor %}

            {{ _('About yourself:') }}

                {{ form.about_me(cols = 64, rows = 4, class = "span4") }}
                {% for error in form.errors.about_me %}
                    [{{error}}]

                {% endfor %}

                <input class="btn btn-primary" type="submit" value="{{ _('Save Changes') }}">

    </form>

</form>
{% endblock %}


text:
(function() {
  function AlbumCtrl(Fixtures, SongPlayer) {
//    console.log(Fixtures.getAlbum());
    this.albumData = Fixtures.getAlbum();
    this.songPlayer = SongPlayer;
  }

  angular
    .module('blocJams')
    .controller('AlbumCtrl', ['Fixtures', 'SongPlayer', AlbumCtrl]);
})();


text:
require 'walrus/grammar/ruby_expression'

module Walrus
  class Grammar
    class MessageExpression < RubyExpression
      def compile options = {}
        # simple case
        @target.source_text + '.' + @message.source_text
      end
    end # class MessageExpression
  end # class Grammar
end # Walrus


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var question_control_service_1 = require('./question-control.service');
/**
 * DynamicFormComponent is the entry point and the main container for the form.
 * Create components to represent the dynamic form.
 * presents a list of questions, each question bound to a <df-question> component element.
 * The <df-question> tag matches the DynamicFormQuestionComponent, the component responsible for
 * rendering the details of each individual question based on values in the data-bound question object.
 * modul.Id means Component-Relative Paths are used so we don't need to full path to the template.
 */
var DynamicFormComponent = (function () {
    function DynamicFormComponent(qcs) {
        this.qcs = qcs;
        this.questions = [];
        this.payLoad = '';
    }
    /**
     * (property) DynamicFormComponent.qcs: QuestionControlService
     */
    DynamicFormComponent.prototype.ngOnInit = function () {
        this.form = this.qcs.toFormGroup(this.questions);
    };
    DynamicFormComponent.prototype.onSubmit = function () {
        this.payLoad = JSON.stringify(this.form.value);
    };
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], DynamicFormComponent.prototype, "questions", void 0);
    DynamicFormComponent = __decorate([
        core_1.Component({
            moduleId: module.id,
            selector: 'dynamic-form',
            templateUrl: 'dynamic-form.component.html',
            providers: [question_control_service_1.QuestionControlService]
        }),
        __metadata('design:paramtypes', [question_control_service_1.QuestionControlService])
    ], DynamicFormComponent);
    return DynamicFormComponent;
}());
exports.DynamicFormComponent = DynamicFormComponent;
//# sourceMappingURL=dynamic-form.component.js.map


text:
class CreateQompositions < ActiveRecord::Migration
  def change
    create_table :qompositions do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end


text:
package services

import (
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// request is send a request
type Request struct {
	Id                   int32    `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
	Msg                  string   `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *Request) Reset()         { *m = Request{} }
func (m *Request) String() string { return proto.CompactTextString(m) }
func (*Request) ProtoMessage()    {}
func (*Request) Descriptor() ([]byte, []int) {
	return fileDescriptor_a0b84a42fa06f626, []int{0}
}

func (m *Request) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Request.Unmarshal(m, b)
}
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Request.Marshal(b, m, deterministic)
}
func (m *Request) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Request.Merge(m, src)
}
func (m *Request) XXX_Size() int {
	return xxx_messageInfo_Request.Size(m)
}
func (m *Request) XXX_DiscardUnknown() {
	xxx_messageInfo_Request.DiscardUnknown(m)
}

var xxx_messageInfo_Request proto.InternalMessageInfo

func (m *Request) GetId() int32 {
	if m != nil {
		return m.Id
	}
	return 0
}

func (m *Request) GetMsg() string {
	if m != nil {
		return m.Msg
	}
	return ""
}

type Response struct {
	Id                   int32    `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
	Msg                  string   `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *Response) Reset()         { *m = Response{} }
func (m *Response) String() string { return proto.CompactTextString(m) }
func (*Response) ProtoMessage()    {}
func (*Response) Descriptor() ([]byte, []int) {
	return fileDescriptor_a0b84a42fa06f626, []int{1}
}

func (m *Response) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Response.Unmarshal(m, b)
}
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Response.Marshal(b, m, deterministic)
}
func (m *Response) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Response.Merge(m, src)
}
func (m *Response) XXX_Size() int {
	return xxx_messageInfo_Response.Size(m)
}
func (m *Response) XXX_DiscardUnknown() {
	xxx_messageInfo_Response.DiscardUnknown(m)
}

var xxx_messageInfo_Response proto.InternalMessageInfo

func (m *Response) GetId() int32 {
	if m != nil {
		return m.Id
	}
	return 0
}

func (m *Response) GetMsg() string {
	if m != nil {
		return m.Msg
	}
	return ""
}

func init() {
	proto.RegisterType((*Request)(nil), "services.request")
	proto.RegisterType((*Response)(nil), "services.response")
}

func init() { proto.RegisterFile("service.proto", fileDescriptor_a0b84a42fa06f626) }

var fileDescriptor_a0b84a42fa06f626 = []byte{
	// 181 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2d, 0x4e, 0x2d, 0x2a,
	0xcb, 0x4c, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x80, 0x72, 0x8b, 0x95, 0xb4,
	0xb9, 0xd8, 0x8b, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0xf8, 0xb8, 0x98, 0x32, 0x53, 0x24,
	0x18, 0x15, 0x18, 0x35, 0x58, 0x83, 0x98, 0x32, 0x53, 0x84, 0x04, 0xb8, 0x98, 0x73, 0x8b, 0xd3,
	0x25, 0x98, 0x14, 0x18, 0x35, 0x38, 0x83, 0x40, 0x4c, 0x25, 0x1d, 0x2e, 0x8e, 0xa2, 0xd4, 0xe2,
	0x82, 0xfc, 0xbc, 0xe2, 0x54, 0xc2, 0xaa, 0x8d, 0x1c, 0xb8, 0xb8, 0x82, 0xf2, 0x4b, 0x4b, 0x52,
	0xdd, 0x4b, 0x33, 0x53, 0x52, 0x85, 0x8c, 0xb8, 0xd8, 0x4b, 0x52, 0x8b, 0x4b, 0x32, 0xf3, 0xd2,
	0x85, 0x04, 0xf5, 0x60, 0xd6, 0xeb, 0x41, 0xed, 0x96, 0x12, 0x42, 0x16, 0x82, 0xd8, 0xa0, 0xc4,
	0xe0, 0xa4, 0xc7, 0x25, 0x9d, 0x99, 0xaf, 0x97, 0x5e, 0x54, 0x90, 0xac, 0x97, 0x58, 0x90, 0x99,
	0x9e, 0x58, 0x92, 0x5a, 0x9e, 0x58, 0x09, 0x57, 0xe9, 0xc4, 0x1b, 0x0c, 0x65, 0x05, 0x80, 0x3c,
	0x15, 0xc0, 0x98, 0xc4, 0x06, 0xf6, 0x9d, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x59, 0x7d, 0xd9,
	0x1e, 0xee, 0x00, 0x00, 0x00,
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// RouteGuideClient is the client API for RouteGuide service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type RouteGuideClient interface {
	// for grpc demo usage
	Testing(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}

type routeGuideClient struct {
	cc *grpc.ClientConn
}

func NewRouteGuideClient(cc *grpc.ClientConn) RouteGuideClient {
	return &routeGuideClient{cc}
}

func (c *routeGuideClient) Testing(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := c.cc.Invoke(ctx, "/services.RouteGuide/testing", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// RouteGuideServer is the server API for RouteGuide service.
type RouteGuideServer interface {
	// for grpc demo usage
	Testing(context.Context, *Request) (*Response, error)
}

func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) {
	s.RegisterService(&_RouteGuide_serviceDesc, srv)
}

func _RouteGuide_Testing_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(Request)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(RouteGuideServer).Testing(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/services.RouteGuide/Testing",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(RouteGuideServer).Testing(ctx, req.(*Request))
	}
	return interceptor(ctx, in, info, handler)
}

var _RouteGuide_serviceDesc = grpc.ServiceDesc{
	ServiceName: "services.RouteGuide",
	HandlerType: (*RouteGuideServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "testing",
			Handler:    _RouteGuide_Testing_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "service.proto",
}


text:
require "snapshot/version"

module Snapshot
  class NoKeyProvided < Exception; end

  mattr_accessor :xvfb
  @@xvfb = "xvfb-run --server-args='-screen 0, 1024x768x24'"

  mattr_accessor :cutycapt_path

  mattr_accessor :cutycapt_args

  @@cutycapt_args = ->(*args) do
    options = args.extract_options!

    url = (args.first || options[:url]).try(:to_s)
    if url.nil? and !options.has_key?(:url)
      raise NoKeyProvided, "No url provided for cutycapt"
    end

    url = "http://" + url unless url =~ /http:\/\//
      args_string = ["--url=\"%s\"" % url]

    options[:js_can_open_window] ||= true
    args_string.push("--js-can-open-windows=on") if options[:js_can_open_window]

    options[:header] ||= false
    args_string.push("--header=#{options[:header]}") if options[:header]

    if !options[:out]
      raise NoKeyProvided, "No out provided for cutycapt"
    end
    args_string.push("--out=%s" % options[:out])

    args_string.join(" ")
  end

  def self.path
    Dir.pwd
  end

  def self.rails3?
    File.exists?(File.join(path, 'script', 'rails'))
  end

  def self.logger
    @logger ||= begin
                  logger_path = File.join(File.dirname(Rails.configuration.paths["log"].first),'snapshot.log')
                  log = Reporter::Logger.new(logger_path)
                  log.method(:info)
                rescue
                  method(:puts)
                end
  end
end

require "snapshot/storage"
require "snapshot/base"
require "snapshot/court"
require "snapshot/idinfo"

if Snapshot.rails3?
  Snapshot.cutycapt_path = "#{Snapshot.path}/lib/CutyCapt/CutyCapt"
  Snapshot::Court.base_out_path = "#{Snapshot.path}/public/crimes"
  Snapshot::Idinfo.base_out_path = "#{Snapshot.path}/public/certs"
else
  rails_root = File.expand_path('../../../../../', __FILE__)
  Snapshot.cutycapt_path = "#{rails_root}/lib/CutyCapt/CutyCapt"
  Snapshot::Court.base_out_path = "#{rails_root}/public/crimes"
  Snapshot::Idinfo.base_out_path = "#{rails_root}/public/certs"
end

unless  File.exist?(Snapshot.cutycapt_path)
  raise "Please check your cutycapt path !!!"
end


text:
var geotools = Packages.org.geotools;
var Registry = require("../registry").Registry;

var registry = new Registry();

/** private: method[create]
 *  :arg config: ``Object`` Configuration object.
 *  :returns: ``Object`` A symbolizer or a rule.
 *
 *  Create a symbolizer or a rule given a configuration object.
 */
exports.create = registry.create;

/** private: method[register] */
exports.register = registry.register;

exports._builder = new geotools.styling.StyleBuilder();
exports._filterFactory = geotools.factory.CommonFactoryFinder.getFilterFactory(null);


text:
<?php
// src/KeeperBundle/Form/RegistrationType.php

namespace KeeperBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('numTel');
        $builder->add('numBoitier');
    }

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }

    public function getNumTel()
    {
        return $this->getBlockPrefix();
    }
}