text:
from twisted.trial.unittest import TestCase
from twisted.internet import defer, reactor

from mock import MagicMock

from alchimia import TWISTED_STRATEGY

from sqlalchemy import MetaData, Table, Column, Integer, String, DateTime
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.schema import CreateTable
from sqlalchemy.pool import StaticPool

from crudset.error import TooMany, MissingRequiredFields
from crudset.crud import Crud, Paginator, Ref, Sanitizer, Readset, Writeset
from crudset.crud import SanitizationContext, SaniChain, crudFromSpec

from twisted.python import log
import logging
class TwistedLogStream(object):
    def write(self, msg):
        log.msg(msg.rstrip())
    def flush(self):
        pass
    def close(self):
        pass
logging.basicConfig(stream=TwistedLogStream())
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

metadata = MetaData()
families = Table('family', metadata,
    Column('id', Integer, primary_key=True),
    Column('location', String),
    Column('surname', String),
)

people = Table('people', metadata,
    Column('id', Integer, primary_key=True),
    Column('created', DateTime),
    Column('family_id', Integer, ForeignKey('family.id')),
    Column('name', String),
)

pets = Table('pets', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String),
    Column('family_id', Integer, ForeignKey('family.id')),
    Column('owner_id', Integer, ForeignKey('people.id')),
)

class CrudTest(TestCase):

    timeout = 10

    @defer.inlineCallbacks
    def engine(self):
        engine = create_engine('sqlite://',
                               connect_args={'check_same_thread': False},
                               reactor=reactor,
                               strategy=TWISTED_STRATEGY,
                               poolclass=StaticPool)
        yield engine.execute(CreateTable(families))
        yield engine.execute(CreateTable(people))
        yield engine.execute(CreateTable(pets))
        defer.returnValue(engine)

    def test_sanitizerChain(self):
        """
        If you pass a list of sanitizers as the sanitizer, it will be wrapped
        in a SaniChain
        """
        sani = Sanitizer(families)
        crud = Crud(Readset(families), [sani, sani])
        self.assertTrue(isinstance(crud.sanitizer, SaniChain))
        self.assertEqual(crud.sanitizer.sanitizers, [sani, sani])

    def test_read_write_tablesDiffer(self):
        """
        The Readset and Writeset tables must be the same
        """
        self.assertRaises(Exception, Crud, Readset(pets), Sanitizer(families))

    @defer.inlineCallbacks
    def test_create(self):
        """
        You can create an object.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))

        family = yield crud.create(engine, {'surname': 'Jones'})
        self.assertEqual(family['surname'], 'Jones')
        self.assertNotEqual(family['id'], None)
        self.assertEqual(family['location'], None)

    @defer.inlineCallbacks
    def test_create_fixed(self):
        """
        You can create a Crud with fixed attributes.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families),
                    Sanitizer(families, ['surname']))
        crud = crud.fix({'surname':'Hammond'})

        family = yield crud.create(engine, {})
        self.assertEqual(family['surname'], 'Hammond')

        fam2 = yield crud.create(engine, {'surname': 'Jones'})
        self.assertEqual(fam2['surname'], 'Hammond')

    @defer.inlineCallbacks
    def test_create_sanitize(self):
        """
        A policy's sanitizer should be used to sanitize fields.
        """
        engine = yield self.engine()
        called = {}
        class Foo(object):
            sanitizer = Sanitizer(families)
            @sanitizer.sanitizeData
            def sani(self, context, data):
                called['context'] = context
                return {'surname': 'Jones'}

        crud = Crud(Readset(families), Foo().sanitizer)
        family = yield crud.create(engine, {})
        self.assertEqual(family['surname'], 'Jones')
        self.assertEqual(called['context'].action, 'create')
        self.assertEqual(called['context'].query, None)

    @defer.inlineCallbacks
    def test_fix_succession(self):
        """
        You can fix attributes one after the other.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        crud = crud.fix({'surname': 'Jones'})
        crud = crud.fix({'location': 'Sunnyville'})

        family = yield crud.create(engine, {})
        self.assertEqual(family['surname'], 'Jones')
        self.assertEqual(family['location'], 'Sunnyville')

    @defer.inlineCallbacks
    def test_fetch(self):
        """
        When you fetch, you see the readable fields, which means every field
        by default.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': '13'})

        fams = yield crud.fetch(engine)
        self.assertEqual(len(fams), 1)
        self.assertEqual(fams[0]['surname'], '13')

    @defer.inlineCallbacks
    def test_fetch_fixed(self):
        """
        Fixed attributes restrict the fetched objects.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})

        crud2 = crud.fix({'surname': 'Johnson'})
        fams = yield crud2.fetch(engine)
        self.assertEqual(len(fams), 0, "Should only find (non-existent) "
                         "records matching the fixed values")

    @defer.inlineCallbacks
    def test_fetch_expression(self):
        """
        You can limit even further.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))

        for i in xrange(10):
            yield crud.create(engine, {'surname': 'Family %d' % (i,)})

        family4 = yield crud.fetch(engine, families.c.surname == 'Family 4')
        self.assertEqual(len(family4), 1)
        self.assertEqual(family4[0]['surname'], 'Family 4')

    @defer.inlineCallbacks
    def test_fetch_readable(self):
        """
        You can limit the set of readable fields.
        """
        engine = yield self.engine()
        crud1 = Crud(Readset(families), Sanitizer(families))
        yield crud1.create(engine, {'surname': 'Johnson', 'location': 'Alabama'})

        crud2 = Crud(Readset(families, ['surname']))
        fams = yield crud2.fetch(engine)
        self.assertEqual(fams[0], {'surname': 'Johnson'}, "Should only show "
                         "the readable fields.")

    @defer.inlineCallbacks
    def test_fetch_limit(self):
        """
        You can limit the number of returned records.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        for i in xrange(10):
            yield crud.create(engine, {'surname': 'Johnson %d' % (i,)})

        fams = yield crud.fetch(engine, limit=5)
        self.assertEqual(len(fams), 5)

    @defer.inlineCallbacks
    def test_fetch_order(self):
        """
        You can specify an ordering
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        for i in xrange(10):
            yield crud.create(engine, {'surname': 'sodkevoiuans'[i]})

        fams = yield crud.fetch(engine, order=families.c.surname)
        ordered = sorted(fams, key=lambda x:x['surname'])
        self.assertEqual(fams, ordered, "Should be ordered")

    @defer.inlineCallbacks
    def test_fetch_offset(self):
        """
        You can offset the limit.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        fams = []
        for i in xrange(10):
            fam = yield crud.create(engine, {'surname': 'abcdefghijklmnop'[i]})
            fams.append(fam)

        results = yield crud.fetch(engine, limit=5, offset=2, order=families.c.surname)
        self.assertEqual(results, fams[2:2+5])

    @defer.inlineCallbacks
    def test_getOne(self):
        """
        You can get just one item.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        fam = yield crud.create(engine, {'surname': 'hey'})
        one = yield crud.getOne(engine)
        self.assertEqual(one, fam)

    @defer.inlineCallbacks
    def test_getOne_where(self):
        """
        You can get one by a where clause
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        fam1 = yield crud.create(engine, {'surname': 'bob'})
        yield crud.create(engine, {'surname': 'Jones'})
        one = yield crud.getOne(engine, families.c.surname == 'bob')
        self.assertEqual(one, fam1)

    @defer.inlineCallbacks
    def test_getOne_moreThanOne(self):
        """
        If getOne returns more than one, it's an exception.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families))
        yield crud.create(engine, {'surname': 'bob'})
        yield crud.create(engine, {'surname': 'Jones'})
        self.assertFailure(crud.getOne(engine), TooMany)

    @defer.inlineCallbacks
    def test_getOne_None(self):
        """
        If there is no result, return None.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families))
        one = yield crud.getOne(engine)
        self.assertEqual(one, None)

    @defer.inlineCallbacks
    def test_count(self):
        """
        You can count the records.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families))
        for i in xrange(14):
            yield crud.create(engine, {'surname': str(i)})

        count = yield crud.count(engine)
        self.assertEqual(count, 14)

    @defer.inlineCallbacks
    def test_count_where(self):
        """
        You can count filtered records.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        for i in xrange(14):
            yield crud.create(engine, {'surname': str(i)})

        count = yield crud.count(engine, families.c.surname == '12')
        self.assertEqual(count, 1)

    @defer.inlineCallbacks
    def test_count_fixed(self):
        """
        The count is restricted by fixed attributes.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})
        yield crud.create(engine, {'surname': 'Arnold'})

        crud2 = crud.fix({'surname': 'Arnold'})
        count = yield crud2.count(engine)
        self.assertEqual(count, 1)

    @defer.inlineCallbacks
    def test_update(self):
        """
        You can update sets.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})
        fams = yield crud.update(engine, {'surname': 'Jamison'})
        self.assertEqual(len(fams), 1)
        self.assertEqual(fams[0]['surname'], 'Jamison')

    @defer.inlineCallbacks
    def test_update_fixed(self):
        """
        Fixed attributes are part of the update.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones', 'location': 'anvilania'})
        yield crud.create(engine, {'surname': 'James', 'location': 'gotham'})

        crud2 = crud.fix({'surname': 'James'})
        yield crud2.update(engine, {'location': 'middle earth'})

        fams = yield crud.fetch(engine, families.c.surname == u'Jones')
        self.assertEqual(fams[0]['location'], 'anvilania')

        fams = yield crud.fetch(engine, families.c.surname == u'James')
        self.assertEqual(fams[0]['location'], 'middle earth')

    @defer.inlineCallbacks
    def test_update_fixedNoChange(self):
        """
        You aren't allowed to update the fixed attributes.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones', 'location': 'bar'})

        crud2 = crud.fix({'surname': 'Jones'})
        fams = yield crud2.update(engine, {'surname': 'Allison',
                                           'location': 'hawaii'})
        fam = fams[0]
        self.assertEqual(fam['surname'], 'Jones', "Should keep fixed value")

    @defer.inlineCallbacks
    def test_update_nothing(self):
        """
        It's a no-op to update nothing.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})
        fams = yield crud.update(engine, {})
        fam = fams[0]
        self.assertEqual(fam['surname'], 'Jones')

    @defer.inlineCallbacks
    def test_update_allFixed(self):
        """
        All the fixed attributes should be taken into consideration.
        """
        engine = yield self.engine()
        crud = Crud(Readset(pets), Sanitizer(pets))
        yield crud.create(engine, {'name': 'Jones', 'family_id': 1})
        yield crud.create(engine, {'name': 'James', 'family_id': 20})
        yield crud.create(engine, {'name': 'Jones', 'family_id': 20})
        yield crud.create(engine, {'name': 'James', 'family_id': 1})

        crud2 = crud.fix({'name': 'James', 'family_id': 20})
        yield crud2.update(engine, {'owner_id': -1})

        fams = yield crud.fetch(engine)
        actual = set()
        for fam in fams:
            actual.add((fam['owner_id'], fam['name'], fam['family_id']))

        expected = set([
            (None, 'Jones', 1),
            (-1, 'James', 20),
            (None, 'Jones', 20),
            (None, 'James', 1),
        ])
        self.assertEqual(actual, expected, "Should only change the one thing")

    @defer.inlineCallbacks
    def test_update_expression(self):
        """
        You can filter the update by expression, too.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones', 'location': 'anvilania'})
        yield crud.create(engine, {'surname': 'James', 'location': 'gotham'})

        fams = yield crud.update(engine, {'location': 'middle earth'},
                                 families.c.surname == 'James')
        self.assertEqual(len(fams), 1)

        fams = yield crud.fetch(engine, families.c.surname == u'Jones')
        self.assertEqual(fams[0]['location'], 'anvilania')

        fams = yield crud.fetch(engine, families.c.surname == u'James')
        self.assertEqual(fams[0]['location'], 'middle earth')

    @defer.inlineCallbacks
    def test_update_sanitize(self):
        """
        A sanitizer should be used to sanitize fields on update.
        """
        engine = yield self.engine()
        called = []
        class Foo(object):
            sanitizer = Sanitizer(families)
            @sanitizer.sanitizeData
            def sani(self, context, data):
                called.append(context)
                return {'surname': 'Jones'}

        crud = Crud(Readset(families), Foo().sanitizer)
        family = yield crud.create(engine, {})
        called.pop()
        fams = yield crud.update(engine, {'surname': 'Arnold'},
                                 families.c.id==family['id'])
        self.assertEqual(fams[0]['surname'], 'Jones')
        self.assertEqual(called[0].action, 'update')
        self.assertEqual(
            str(called[0].query),
            str(families.select().where(families.c.id==family['id'])))

    @defer.inlineCallbacks
    def test_update_fixed_sanitizeQuery(self):
        """
        Fixed attributes should make their way into the query passed to the
        sanitizer.
        """
        engine = yield self.engine()
        called = []
        class Foo(object):
            sanitizer = Sanitizer(families)
            @sanitizer.sanitizeData
            def sani(self, context, data):
                called.append(context)
                return data

        crud = Crud(Readset(families), Foo().sanitizer).fix(
            {'surname': 'Arnold'})
        yield crud.create(engine, {})
        called.pop()
        fams = yield crud.update(engine, {'location': 'Bolivia'})
        self.assertEqual(fams[0]['location'], 'Bolivia')
        self.assertEqual(called[0].action, 'update')
        self.assertEqual(
            str(called[0].query),
            str(families.select().where(families.c.surname=='Arnold')))

    @defer.inlineCallbacks
    def test_delete(self):
        """
        You can delete sets of things.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families))
        yield crud.create(engine, {'surname': 'Jones'})
        yield crud.delete(engine)
        fams = yield crud.fetch(engine, )
        self.assertEqual(len(fams), 0)

    @defer.inlineCallbacks
    def test_delete_fixed(self):
        """
        The fixed variables influence what is deleted.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})
        crud2 = crud.fix({'surname': 'Arnold'})
        yield crud2.create(engine, {})
        yield crud2.delete(engine)

        fams = yield crud.fetch(engine, )
        self.assertEqual(len(fams), 1, "Should have only deleted the fixed")
        self.assertEqual(fams[0]['surname'], 'Jones')

    @defer.inlineCallbacks
    def test_delete_expression(self):
        """
        You can filter by expression.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), Sanitizer(families))
        yield crud.create(engine, {'surname': 'Jones'})
        yield crud.create(engine, {'surname': 'Arnold'})
        yield crud.delete(engine, families.c.surname == 'Arnold')

        fams = yield crud.fetch(engine, )
        self.assertEqual(len(fams), 1, "Should have deleted Arnold")

    @defer.inlineCallbacks
    def test_references_null(self):
        """
        You can nest referenced tables when fetching.  They will be None
        if there is no row.
        """
        engine = yield self.engine()
        crud = Crud(Readset(people, references={
            'family': Ref(Readset(families),
                          people.c.family_id == families.c.id),
        }), Sanitizer(people))

        yield crud.create(engine, {'name': 'Sam'})
        peeps = yield crud.fetch(engine, )
        self.assertEqual(len(peeps), 1)
        sam = peeps[0]
        self.assertEqual(sam['family'], None, str(sam))
        self.assertEqual(sam['name'], 'Sam')

    @defer.inlineCallbacks
    def test_references_notNull(self):
        """
        You can nest objects by reference.
        """
        engine = yield self.engine()
        fam_crud = Crud(Readset(families), Sanitizer(families))
        family = yield fam_crud.create(engine, {'surname': 'Jones'})

        crud = Crud(Readset(people, references={
            'family': Ref(Readset(families), people.c.family_id == families.c.id),
        }), Sanitizer(people))
        sam = yield crud.create(engine, {'name': 'Sam', 'family_id': family['id']})
        self.assertEqual(sam['family'], family)

    @defer.inlineCallbacks
    def test_references_multiple(self):
        """
        You can have multiple references.
        """
        engine = yield self.engine()
        fam_crud = Crud(Readset(families), Sanitizer(families))
        johnson = yield fam_crud.create(engine, {'surname': 'Johnson'})

        person_crud = Crud(Readset(people), Sanitizer(people))
        john = yield person_crud.create(engine, {
            'family_id': johnson['id'],
            'name': 'John',
        })

        pets_crud = Crud(Readset(pets, references={
            'family': Ref(Readset(families), pets.c.family_id == families.c.id),
            'owner': Ref(Readset(people), pets.c.owner_id == people.c.id),
        }), Sanitizer(pets))

        cat = yield pets_crud.create(engine, {
            'family_id': johnson['id'],
            'name': 'cat',
            'owner_id': john['id'],
        })
        self.assertEqual(cat['name'], 'cat')
        self.assertEqual(cat['family'], johnson)
        self.assertEqual(cat['owner'], john)

        dog = yield pets_crud.create(engine, {
            'name': 'dog',
            'owner_id': john['id']
        })
        self.assertEqual(dog['name'], 'dog')
        self.assertEqual(dog['owner'], john)
        self.assertEqual(dog['family'], None)

        fish = yield pets_crud.create(engine, {
            'name': 'bob',
            'family_id': johnson['id'],
        })
        self.assertEqual(fish['name'], 'bob')
        self.assertEqual(fish['owner'], None)
        self.assertEqual(fish['family'], johnson)

    @defer.inlineCallbacks
    def test_references_list(self):
        """
        You can reference a list of things.
        """
        engine = yield self.engine()
        pet_crud = Crud(Readset(pets), Sanitizer(pets))
        fam_crud = Crud(Readset(families, references={
            'pets': Ref(Readset(pets), pets.c.family_id == families.c.id,
                multiple=True),
        }), Sanitizer(families))

        johnson = yield fam_crud.create(engine, {'surname': 'Johnson'})
        self.assertEqual(johnson['pets'], [])

        cat = yield pet_crud.create(engine, {
            'family_id': johnson['id'],
            'name': 'cat'})

        johnson_crud = fam_crud.fix({'id': johnson['id']})
        johnson = yield johnson_crud.getOne(engine)
        self.assertEqual(johnson['pets'], [cat])

        dog = yield pet_crud.create(engine, {
            'family_id': johnson['id'],
            'name': 'dog'})
        johnson = yield johnson_crud.getOne(engine)
        self.assertIn(dog, johnson['pets'])
        self.assertIn(cat, johnson['pets'])

    @defer.inlineCallbacks
    def test_table_attr(self):
        """
        You can expose the table names as an attribute.
        """
        engine = yield self.engine()
        crud = Crud(Readset(families), table_attr='_object')
        r = yield crud.create(engine, {'surname': 'Jones'})
        self.assertEqual(r['_object'], 'family')

        rlist = yield crud.fetch(engine)
        self.assertEqual(rlist[0]['_object'], 'family')

        rlist = yield crud.update(engine, {'surname': 'Jamison'})
        self.assertEqual(rlist[0]['_object'], 'family')

    @defer.inlineCallbacks
    def test_table_attr_reference(self):
        """
        table attr works with references, too.
        """
        engine = yield self.engine()
        fam_crud = Crud(Readset(families))
        family = yield fam_crud.create(engine, {'surname': 'Jones'})

        crud = Crud(Readset(people, references={
            'family': Ref(Readset(families), people.c.family_id == families.c.id),
        }), Sanitizer(people), table_attr='foo')
        sam = yield crud.create(engine, {'name': 'Sam', 'family_id': family['id']})
        self.assertEqual(sam['foo'], 'people')
        self.assertEqual(sam['family']['foo'], 'family')

    @defer.inlineCallbacks
    def test_table_map(self):
        """
        You can map table names to something else.
        """
        engine = yield self.engine()
        fam_crud = Crud(Readset(families), Sanitizer(families))
        family = yield fam_crud.create(engine, {'surname': 'Jones'})

        crud = Crud(
            Readset(people, references={
                'family': Ref(Readset(families), people.c.family_id == families.c.id),
            }),
            Sanitizer(people),
            table_attr='foo',
            table_map={
                people: 'Person',
                families: 'Aardvark',
            },
        )
        sam = yield crud.create(engine, {'name': 'Sam', 'family_id': family['id']})
        self.assertEqual(sam['foo'], 'Person')
        self.assertEqual(sam['family']['foo'], 'Aardvark')

    def test_table_map_attr_fix(self):
        """
        Fixed Cruds should retain the table_attr and map.
        """
        crud = Crud(
            Readset(families),
            table_attr='foo',
            table_map={'foo': 'bar'},
        )
        fixed = crud.fix({'id': 56})
        self.assertEqual(fixed.table_attr, 'foo')
        self.assertEqual(fixed.table_map, {'foo': 'bar'})

class ReadsetTest(TestCase):

    def test_default(self):
        """
        By default, all columns are read.
        """
        r = Readset(families)
        self.assertEqual(r.readable, set(['id', 'location', 'surname']))
        self.assertEqual(r.readable_columns, list(families.columns))
        self.assertEqual(r.references, {})

    def test_readable(self):
        """
        You can specify a list of columns that are readable.
        """
        r = Readset(families, ['location'])
        self.assertEqual(r.readable, set(['location']))
        self.assertEqual(r.readable_columns, [families.c.location])

    def test_references(self):
        """
        You can specify a mapping of references.
        """
        ref = Ref(Readset(families), people.c.family_id == families.c.id)
        r = Readset(people, references={'family': ref})
        self.assertEqual(r.references, {'family': ref})

class WritesetTest(TestCase):

    def test_default(self):
        """
        By default, no fields are writeable.
        """
        w = Writeset(families)
        self.assertEqual(w.writeable, set([]))

        data = {'foo': 'bar', 'surname': 'Jones'}
        output = self.successResultOf(w.sanitize(
            SanitizationContext(None, 'create', None), data))
        self.assertEqual(output, {}, "Should filter out all fields")
        output = self.successResultOf(w.sanitize(
            SanitizationContext(None, 'update', None), data))
        self.assertEqual(output, {}, "Should filter out all fields")

    @defer.inlineCallbacks
    def test_writeable(self):
        """
        Setting a list of writeable fields will let fields pass through.
        """
        w = Writeset(families, ['surname'])
        self.assertEqual(w.writeable, set(['surname']))

        data = {'foo': 'bar', 'surname': 'Jones', 'location': 'Nowhere'}
        output = yield w.sanitize(
            SanitizationContext(None, 'update', None), data)
        self.assertEqual(output, {'surname': 'Jones'}, "Surname is writeable")
        output = yield w.sanitize(
            SanitizationContext(None, 'create', None), data)
        self.assertEqual(output, {'surname': 'Jones'}, "Surname is writeable")

    def test_writeable_asColumns(self):
        """
        You can specify the writeable fields as SQLAlchemy columns.
        """
        w = Writeset(families, [families.c.surname])
        self.assertEqual(w.writeable, set(['surname']))

    @defer.inlineCallbacks
    def test_create_writeable(self):
        """
        Setting a list of create_writeable fields will only let the fields
        pass through when creating.
        """
        w = Writeset(families,
            writeable=['location'],
            create_writeable=['surname'])

        data = {'foo': 'bar', 'surname': 'Jones', 'location': 'Nowhere'}
        output = yield w.sanitize(
            SanitizationContext(None, 'create', None), data)
        self.assertEqual(output, {'surname': 'Jones', 'location': 'Nowhere'},
            "Writeable and create writeable are writeable during create")

        output = yield w.sanitize(
            SanitizationContext(None, 'update', None), data)
        self.assertEqual(output, {'location': 'Nowhere'},
            "Only writeable is writeable during update")

class PaginatorTest(TestCase):

    timeout = 10

    @defer.inlineCallbacks
    def engine(self):
        engine = create_engine('sqlite://',
                               connect_args={'check_same_thread': False},
                               reactor=reactor,
                               strategy=TWISTED_STRATEGY,
                               poolclass=StaticPool)
        yield engine.execute(CreateTable(families))
        yield engine.execute(CreateTable(people))
        yield engine.execute(CreateTable(pets))
        defer.returnValue(engine)

    @defer.inlineCallbacks
    def test_page(self):
        """
        You can paginate a Crud
        """
        engine = yield self.engine()
        crud = Crud(Readset(pets))
        pager = Paginator(crud, page_size=10, order=pets.c.id)

        monkeys = []
        for i in xrange(40):
            monkey = yield crud.create(engine, {'name': 'seamonkey %d' % (i,)})
            monkeys.append(monkey)

        page1 = yield pager.page(engine, 0)
        self.assertEqual(page1, monkeys[:10])
        page2 = yield pager.page(engine, 1)
        self.assertEqual(page2, monkeys[10:20])

    @defer.inlineCallbacks
    def test_page_where(self):
        """
        You can paginate filtered results, too
        """
        engine = yield self.engine()
        crud = Crud(Readset(pets), Sanitizer(pets))
        pager = Paginator(crud, page_size=3, order=pets.c.id)

        things = []
        _things = [
            {'name': 'thing 1'},
            {'name': 'thing 2'},
            {'name': 'dog'},
            {'name': 'cat'},
            {'name': 'dog'},
        ]
        for thing in _things:
            t = yield crud.create(engine, thing)
            things.append(t)

        page1 = yield pager.page(engine, 0, pets.c.name.startswith('thing'))
        self.assertEqual(page1, [things[0], things[1]])
        count = yield pager.pageCount(engine, pets.c.name.startswith('thing'))
        self.assertEqual(count, 1)

    @defer.inlineCallbacks
    def test_pageCount(self):
        """
        You can count the pages
        """
        engine = yield self.engine()
        crud = Crud(Readset(pets))
        pager = Paginator(crud, page_size=10, order=pets.c.id)

        monkeys = []
        for i in xrange(43):
            monkey = yield crud.create(engine, {'name': 'seamonkey %d' % (i,)})
            monkeys.append(monkey)

        pages = yield pager.pageCount(engine)
        self.assertEqual(pages, 5)

    @defer.inlineCallbacks
    def test_pageCountForills(self):
        """
        The page count should be accurate for all numbers.
        """
        engine = yield self.engine()
        crud = Crud(Readset(pets), Sanitizer(pets))
        pager = Paginator(crud, page_size=3, order=pets.c.id)

        count = yield pager.pageCount(engine)
        self.assertEqual(count, 0, "no records, no pages")

        yield crud.create(engine, {})
        count = yield pager.pageCount(engine)
        self.assertEqual(count, 1, "1 record, 1 page")

        yield crud.create(engine, {})
        yield crud.create(engine, {})
        count = yield pager.pageCount(engine)
        self.assertEqual(count, 1, "3 records, 1 page")

        yield crud.create(engine, {})
        count = yield pager.pageCount(engine)
        self.assertEqual(count, 2, "4 records, 2 pages")

class SanitizerTest(TestCase):

    create_context = SanitizationContext(None, 'create', None)
    update_context = SanitizationContext(None, 'update', None)

    @defer.inlineCallbacks
    def test_default(self):
        """
        An empty sanitizer will forbid any column from being updated.
        """
        class Foo(object):
            sanitizer = Sanitizer(pets)
        sanitizer = Foo().sanitizer

        data = {
            'foo': 'bar',
            'id': 12,
            'family_id': 19,
            'owner_id': -1,
            'name': 'bob',
        }
        output = yield sanitizer.sanitize(self.create_context, data)
        self.assertEqual(output, {
            'id': 12,
            'family_id': 19,
            'owner_id': -1,
            'name': 'bob',
        }, "Should pass-thru on every legitimate column by default")

    @defer.inlineCallbacks
    def test_required(self):
        """
        You can specify a list of fields that are required on create.
        """
        sanitizer = Sanitizer(pets, required=['name'])
        self.assertEqual(set(sanitizer.required), set(['name']))

        yield self.assertFailure(sanitizer.sanitize(self.create_context, {}),
            MissingRequiredFields)

        yield self.assertFailure(sanitizer.sanitize(self.create_context, {'name': None}),
            MissingRequiredFields)

        output = yield sanitizer.sanitize(self.create_context, {'name': 'bob'})
        self.assertEqual(output, {'name': 'bob'})

    @defer.inlineCallbacks
    def test_required_update(self):
        """
        Required on create validation does not happen on update except
        on null-checking.
        """
        sanitizer = Sanitizer(pets, required=['name'])
        self.assertEqual(set(sanitizer.required), set(['name']))
        output = yield sanitizer.sanitize(self.update_context, {})
        self.assertEqual(output, {})

        yield self.assertFailure(sanitizer.sanitize(self.update_context,
            {'name': None}),
            MissingRequiredFields)

    @defer.inlineCallbacks
    def test_sanitizeData(self):
        """
        You can specify a function that will sanitize the whole piece of data.
        """
        called = {}
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeData
            def myFunc(self, context, data):
                called['context'] = context
                called['data'] = data
                return {'name': 'john'}

        sanitizer = Foo().sanitizer

        indata = {
            'foo': 'bar',
            'name': 'bob',
        }
        output = yield sanitizer.sanitize(self.create_context, indata)
        self.assertEqual(output, {'name': 'john'})
        self.assertEqual(called['context'], self.create_context)
        self.assertEqual(called['data'], indata)

    @defer.inlineCallbacks
    def test_sanitizeField(self):
        """
        You can sanitize individual fields.
        """
        called = {}
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeField('name')
            def name(self, context, data, field):
                called['context'] = context
                called['data'] = data.copy()
                called['field'] = field
                return 'new name'

        sanitizer = Foo().sanitizer

        indata = {'name': 'sam'}
        output = yield sanitizer.sanitize(self.create_context, indata)
        self.assertEqual(output, {'name': 'new name'})
        self.assertEqual(called['context'], self.create_context)
        self.assertEqual(called['data'], {'name': 'sam'})
        self.assertEqual(called['field'], 'name')

    @defer.inlineCallbacks
    def test_sanitizeField_deferred(self):
        """
        Field sanitizers can return deferreds.
        """
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeField('name')
            def name(self, context, data, field):
                return defer.succeed('new name')

        sanitizer = Foo().sanitizer

        indata = {'name': 'sam'}
        output = yield sanitizer.sanitize(self.create_context, indata)
        self.assertEqual(output, {'name': 'new name'})

    @defer.inlineCallbacks
    def test_sanitizeField_order(self):
        """
        Fields are sanitized in the order added.
        """
        called = []
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeField('name')
            def name(self, context, data, field):
                called.append('name')
                return data[field]

            @sanitizer.sanitizeField('family_id')
            def family_id(self, context, data, field):
                called.append('family_id')
                return data[field]

        sanitizer = Foo().sanitizer

        indata = {'name': 'sam', 'family_id': 12}
        output = yield sanitizer.sanitize(self.create_context, indata)
        self.assertEqual(output, {'name': 'sam', 'family_id': 12})
        self.assertEqual(called, ['name', 'family_id'], "Should be called "
                         "in the order added")

    @defer.inlineCallbacks
    def test_sanitizeField_onlyCalledIfPresent(self):
        """
        The sanitizeField sanitizers should only be called if the field is
        present in the update/create data.
        """
        called = []
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeField('name')
            def name(self, context, data, field):
                called.append('name')
                return data[field]

        sanitizer = Foo().sanitizer

        indata = {'family_id': 12}
        output = yield sanitizer.sanitize(self.create_context, indata)
        self.assertEqual(output, {'family_id': 12})
        self.assertEqual(called, [], "Should not call name validator since "
                         "name wasn't present")

    def test_getSanitizedFields(self):
        """
        You can list the fields that are being sanitized.
        """
        class Foo(object):
            sanitizer = Sanitizer(pets)

            @sanitizer.sanitizeField('name')
            def name(self, context, data, field):
                pass

        self.assertEqual(Foo.sanitizer.getSanitizedFields(), ['name'])

class SaniChainTest(TestCase):

    @defer.inlineCallbacks
    def test_calls_all(self):
        """
        The chain will pass the data through each item in the sanitization
        chain.
        """
        sani1 = MagicMock()
        sani1.table = 'foo'
        sani1.sanitize.return_value = {'foo': 'bar'}
        sani2 = MagicMock()
        sani2.table = 'foo'
        sani2.sanitize.return_value = defer.succeed({'hey': 'ho'})

        chain = SaniChain([sani1, sani2])
        self.assertEqual(chain.table, 'foo')
        data = {'1': '2'}
        context = SanitizationContext(None, None, None)
        output = yield chain.sanitize(context, data)

        sani1.sanitize.assert_called_once_with(context, data)
        sani2.sanitize.assert_called_once_with(context, {'foo': 'bar'})
        self.assertEqual(output, {'hey': 'ho'})

    def test_differentTable(self):
        """
        Sanitizers must have the same table.
        """
        sani1 = MagicMock()
        sani1.table = 'foo'
        sani2 = MagicMock()
        sani2.table = 'bar'
        self.assertRaises(Exception, SaniChain, [sani1, sani2])

class crudFromSpecTest(TestCase):

    def assertWriteable(self, crud, expected):
        """
        Assert that the given fields are the complete set of writeable fields.
        """
        dummy = {}
        for c in crud.readset.table.columns:
            dummy[c.name] = 'dummy'
        d = crud.sanitizer.sanitize(
            SanitizationContext(None, None, None),
            dummy)
        output = self.successResultOf(d)
        self.assertEqual(set(output.keys()), set(expected),
            "Expected these fields to be writeable: %r" % (expected,))
        return output

    def assertCreateWriteable(self, crud, expected):
        """
        Assert that the given fields are the complete set of writeable fields
        when creating and that none of them are writeable when updating.
        """
        dummy = {}
        for c in crud.readset.table.columns:
            dummy[c.name] = 'dummy'
        d = crud.sanitizer.sanitize(
            SanitizationContext(None, 'create', None),
            dummy)
        output = self.successResultOf(d)
        self.assertEqual(set(output), set(expected),
            "Expected these fields to be writeable during create: %r" % (
            expected,))

        d = crud.sanitizer.sanitize(
            SanitizationContext(None, 'update', None),
            dummy)
        output = self.successResultOf(d)
        writeable = set(output) & set(expected)
        self.assertEqual(writeable, set(),
            "Expected fields not to be writeable during update: %r" % (
            writeable))
        return output

    def test_table_attr(self):
        """
        You can set the table_attr.
        """
        class Base:
            table = families
        crud = crudFromSpec(Base, table_attr='foo', table_map={'foo':'bar'})
        self.assertEqual(crud.table_attr, 'foo')
        self.assertEqual(crud.table_map, {'foo':'bar'})

    def test_defaults(self):
        """
        By default, all columns are readable and all are writeable
        """
        class Base:
            table = families
        crud = crudFromSpec(Base)

        self.assertEqual(crud.table_attr, None)
        self.assertEqual(crud.table_map, {})

        # readset
        self.assertTrue(isinstance(crud.readset, Readset))
        self.assertEqual(crud.readset.table, families)
        self.assertEqual(crud.readset.readable_columns, list(families.columns),
            "All columns should be readable by default")
        self.assertEqual(crud.readset.references, {})

        # sanitizer
        self.assertEqual(crud.sanitizer.table, families)
        self.assertWriteable(crud, [])

    def test_readable(self):
        """
        You can specify the list of readable columns.
        """
        class Base:
            table = families
            readable = [
                'id',
            ]
        crud = crudFromSpec(Base)
        self.assertEqual(crud.readset.readable, set(['id']))
        self.assertWriteable(crud, [])

    def test_writeable(self):
        """
        You can specify the list of writeable columns.
        """
        class Base:
            table = families
            writeable = [
                'id',
            ]
        crud = crudFromSpec(Base)
        self.assertEqual(crud.readset.readable_columns, list(families.columns))
        self.assertWriteable(crud, ['id'])

    def test_writeable_all(self):
        """
        You can say that all fields are writeable.
        """
        class Base:
            table = families
            writeable = 'ALL'
        crud = crudFromSpec(Base)
        self.assertEqual(crud.readset.readable_columns, list(families.columns))
        self.assertWriteable(crud, [x.name for x in families.columns])

    def test_create_writeable(self):
        """
        You can specify that a set of fields are writeable only when creating.
        """
        class Base:
            table = families
            create_writeable = [
                'surname',
            ]
        crud = crudFromSpec(Base)
        self.assertCreateWriteable(crud, ['surname'])

    def test_references(self):
        """
        You can specify a hash of references.
        """
        ref = Ref(Readset(people), families.c.id == people.c.family_id)
        class Base:
            table = families
            references = {
                'foo': ref,
            }
        crud = crudFromSpec(Base)
        self.assertEqual(crud.readset.references['foo'], ref)

    def test_sanitizer(self):
        """
        You can specify a sanitizer
        """
        class Base:
            table = families
            writeable = ['surname']
            sanitizer = Sanitizer(table)
            @sanitizer.sanitizeField('surname')
            def surname(self, context, data, fieldname):
                return 'sanitized surname'
        crud = crudFromSpec(Base)
        output = self.assertWriteable(crud, ['surname'])
        self.assertEqual(output['surname'], 'sanitized surname')


text:
/* DOES THIS HELP AUTOSIZING? */
.sharing .projects {
	height: auto !important;
}

.sharing .projects .tabTitle {

	background-color: #264eea;
	color: #FFF;
	/*color: #264eea;*/
	/*background-color: #DAF0F2;*/
	text-align: center !important;
	vertical-align: middle;
	font-size: 20px;
	font-stretch: expanded;
	font-weight: bold;
}

.sharing .projects .label {
	text-align:	center !important;
	font-weight: bolder;
	font-size: 18px;
	font-family: Verdana;
	font-size: 14px;
	font-style: oblique;
	height: 20px;
	vertical-align: bottom !important;
	background: #EEE;
}

.sharing .projects .addProjectButton {
	font-size: 14px;
	color: #224;
}
.sharing .projects .name,
.sharing .projects .description,
.sharing .projects .notes
{
	height: 20px;
	font-size: 14px;
	color: #444;
	text-align: left !important;
	vertical-align: middle !important;
	font-style: oblique;
	font-weight: bolder !important;
	padding-top: 4px;
}

.sharing .projects .invalid ,
.sharing .projects .description .dijitTextArea .invalid,
.sharing .projects .notes .dijitTextArea .invalid
{
	border: 2px solid #F00 !important;
}

.sharing .projects .dragSource .notes .default
{
	color: #555;
}

.sharing .projects .editProjectRow {
	width: 100%;
	height: 100%;
}

.sharing .projects .dragSource
{
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius:8pt;
	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	/*margin-top: 5px;*/
	width: 120px;
	height: 260px;
	min-height: 100px;

	text-align: left !important;
	/*color: #339;*/
	/*color: darkred;*/
	/*font-weight: bold;*/

	font-family: Verdana;
	font-size: 12px;
	border-color: #333;

	/* NEEDED SO THAT SCROLLBAR WILL SHOW */
	display: block !important;
	overflow:auto !important;
}

.sharing .projects .dragSource .name {
	font-size: 14px;
	color: darkred;
	font-weight: bolder;
	text-align: left !important;

	background-image: url(../../../plugins/sharing/images/project-18.png);
	text-indent: 22px;
	background-repeat: no-repeat;
	height: 18px;
}

.sharing .projects .dragSource .description {
	color: #222;
	font-size: 14px;
	text-align: left !important;
	background: #EFEFEF;
}

.sharing .projects .dragSource .notes {
	color: #000;
	font-weight: normal;
	font-size: 12px;
	text-align: left !important;
	background: #EFEFEF;
	height: 18px !important;
}

.sharing .projects .trash {
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius:8pt;
	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	margin-top: 5px;
	width: 150px;
	height: 60px;
	text-align: center;
	vertical-align: middle;
}

.sharing .projects .trashIcon {
	height: 100%;
	width: 100px;
	margin-left: auto;
	margin-right: auto;

	background-image: url(../../../plugins/sharing/images/trash-60.png);
	background-repeat: no-repeat;

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.fs.azure;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.classification.InterfaceAudience;

import com.microsoft.azure.storage.AccessCondition;
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.RetryPolicyFactory;
import com.microsoft.azure.storage.StorageCredentials;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.StorageUri;
import com.microsoft.azure.storage.blob.BlobListingDetails;
import com.microsoft.azure.storage.blob.BlobProperties;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.BlockEntry;
import com.microsoft.azure.storage.blob.BlockListingFilter;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlobDirectory;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.CloudPageBlob;
import com.microsoft.azure.storage.blob.CopyState;
import com.microsoft.azure.storage.blob.DeleteSnapshotsOption;
import com.microsoft.azure.storage.blob.ListBlobItem;
import com.microsoft.azure.storage.blob.PageRange;

/**
 * A real implementation of the Azure interaction layer that just redirects
 * calls to the Windows Azure storage SDK.
 */
@InterfaceAudience.Private
class StorageInterfaceImpl extends StorageInterface {
  private CloudBlobClient serviceClient;
  private RetryPolicyFactory retryPolicyFactory;
  private int timeoutIntervalInMs;

  private void updateRetryPolicy() {
    if (serviceClient != null && retryPolicyFactory != null) {
      serviceClient.getDefaultRequestOptions().setRetryPolicyFactory(retryPolicyFactory);
    }
  }

  private void updateTimeoutInMs() {
    if (serviceClient != null && timeoutIntervalInMs > 0) {
      serviceClient.getDefaultRequestOptions().setTimeoutIntervalInMs(timeoutIntervalInMs);
    }
  }

  @Override
  public void setRetryPolicyFactory(final RetryPolicyFactory retryPolicyFactory) {
    this.retryPolicyFactory = retryPolicyFactory;
    updateRetryPolicy();
  }

  @Override
  public void setTimeoutInMs(int timeoutInMs) {
    timeoutIntervalInMs = timeoutInMs;
    updateTimeoutInMs();
  }

  @Override
  public void createBlobClient(CloudStorageAccount account) {
    serviceClient = account.createCloudBlobClient();
    updateRetryPolicy();
    updateTimeoutInMs();
  }

  @Override
  public void createBlobClient(URI baseUri) {
    createBlobClient(baseUri, (StorageCredentials)null);
  }

  @Override
  public void createBlobClient(URI baseUri, StorageCredentials credentials) {
    serviceClient = new CloudBlobClient(baseUri, credentials);
    updateRetryPolicy();
    updateTimeoutInMs();
  }

  @Override
  public StorageCredentials getCredentials() {
    return serviceClient.getCredentials();
  }

  @Override
  public CloudBlobContainerWrapper getContainerReference(String uri)
      throws URISyntaxException, StorageException {
    return new CloudBlobContainerWrapperImpl(
        serviceClient.getContainerReference(uri));
  }

  //
  // WrappingIterator
  //

  /**
   * This iterator wraps every ListBlobItem as they come from the listBlobs()
   * calls to their proper wrapping objects.
   */
  private static class WrappingIterator implements Iterator<ListBlobItem> {
    private final Iterator<ListBlobItem> present;

    public WrappingIterator(Iterator<ListBlobItem> present) {
      this.present = present;
    }

    public static Iterable<ListBlobItem> wrap(
        final Iterable<ListBlobItem> present) {
      return new Iterable<ListBlobItem>() {
        @Override
        public Iterator<ListBlobItem> iterator() {
          return new WrappingIterator(present.iterator());
        }
      };
    }

    @Override
    public boolean hasNext() {
      return present.hasNext();
    }

    @Override
    public ListBlobItem next() {
      ListBlobItem unwrapped = present.next();
      if (unwrapped instanceof CloudBlobDirectory) {
        return new CloudBlobDirectoryWrapperImpl((CloudBlobDirectory) unwrapped);
      } else if (unwrapped instanceof CloudBlockBlob) {
        return new CloudBlockBlobWrapperImpl((CloudBlockBlob) unwrapped);
      } else if (unwrapped instanceof CloudPageBlob) {
        return new CloudPageBlobWrapperImpl((CloudPageBlob) unwrapped);
      } else {
        return unwrapped;
      }
    }

    @Override
    public void remove() {
      present.remove();
    }
  }

  //
  // CloudBlobDirectoryWrapperImpl
  //
  @InterfaceAudience.Private
  static class CloudBlobDirectoryWrapperImpl extends CloudBlobDirectoryWrapper {
    private final CloudBlobDirectory directory;

    public CloudBlobDirectoryWrapperImpl(CloudBlobDirectory directory) {
      this.directory = directory;
    }

    @Override
    public URI getUri() {
      return directory.getUri();
    }

    @Override
    public Iterable<ListBlobItem> listBlobs(String prefix,
        boolean useFlatBlobListing, EnumSet<BlobListingDetails> listingDetails,
        BlobRequestOptions options, OperationContext opContext)
        throws URISyntaxException, StorageException {
      return WrappingIterator.wrap(directory.listBlobs(prefix,
          useFlatBlobListing, listingDetails, options, opContext));
    }

    @Override
    public CloudBlobContainer getContainer() throws URISyntaxException,
        StorageException {
      return directory.getContainer();
    }

    @Override
    public CloudBlobDirectory getParent() throws URISyntaxException,
        StorageException {
      return directory.getParent();
    }

    @Override
    public StorageUri getStorageUri() {
      return directory.getStorageUri();
    }

  }

  //
  // CloudBlobContainerWrapperImpl
  //
  @InterfaceAudience.Private
  static class CloudBlobContainerWrapperImpl extends CloudBlobContainerWrapper {
    private final CloudBlobContainer container;

    public CloudBlobContainerWrapperImpl(CloudBlobContainer container) {
      this.container = container;
    }

    @Override
    public String getName() {
      return container.getName();
    }

    @Override
    public boolean exists(OperationContext opContext) throws StorageException {
      return container.exists(AccessCondition.generateEmptyCondition(), null,
          opContext);
    }

    @Override
    public void create(OperationContext opContext) throws StorageException {
      container.create(null, opContext);
    }

    @Override
    public HashMap<String, String> getMetadata() {
      return container.getMetadata();
    }

    @Override
    public void setMetadata(HashMap<String, String> metadata) {
      container.setMetadata(metadata);
    }

    @Override
    public void downloadAttributes(OperationContext opContext)
        throws StorageException {
      container.downloadAttributes(AccessCondition.generateEmptyCondition(),
          null, opContext);
    }

    @Override
    public void uploadMetadata(OperationContext opContext)
        throws StorageException {
      container.uploadMetadata(AccessCondition.generateEmptyCondition(), null,
          opContext);
    }

    @Override
    public CloudBlobDirectoryWrapper getDirectoryReference(String relativePath)
        throws URISyntaxException, StorageException {

      CloudBlobDirectory dir = container.getDirectoryReference(relativePath);
      return new CloudBlobDirectoryWrapperImpl(dir);
    }

    @Override
    public CloudBlobWrapper getBlockBlobReference(String relativePath)
        throws URISyntaxException, StorageException {

      return new CloudBlockBlobWrapperImpl(container.getBlockBlobReference(relativePath));
    }

    @Override
    public CloudBlobWrapper getPageBlobReference(String relativePath)
        throws URISyntaxException, StorageException {
      return new CloudPageBlobWrapperImpl(
          container.getPageBlobReference(relativePath));
    }

  }

  abstract static class CloudBlobWrapperImpl implements CloudBlobWrapper {
    private final CloudBlob blob;

    @Override
    public CloudBlob getBlob() {
      return blob;
    }

    public URI getUri() {
      return getBlob().getUri();
    }

    protected CloudBlobWrapperImpl(CloudBlob blob) {
      this.blob = blob;
    }

    @Override
    public HashMap<String, String> getMetadata() {
      return getBlob().getMetadata();
    }

    @Override
    public void delete(OperationContext opContext, SelfRenewingLease lease)
        throws StorageException {
      getBlob().delete(DeleteSnapshotsOption.NONE, getLeaseCondition(lease),
          null, opContext);
    }

    /**
     * Return and access condition for this lease, or else null if
     * there's no lease.
     */
    private AccessCondition getLeaseCondition(SelfRenewingLease lease) {
      AccessCondition leaseCondition = null;
      if (lease != null) {
        leaseCondition = AccessCondition.generateLeaseCondition(lease.getLeaseID());
      }
      return leaseCondition;
    }

    @Override
    public boolean exists(OperationContext opContext)
        throws StorageException {
      return getBlob().exists(null, null, opContext);
    }

    @Override
    public void downloadAttributes(
        OperationContext opContext) throws StorageException {
      getBlob().downloadAttributes(null, null, opContext);
    }

    @Override
    public BlobProperties getProperties() {
      return getBlob().getProperties();
    }

    @Override
    public void setMetadata(HashMap<String, String> metadata) {
      getBlob().setMetadata(metadata);
    }

    @Override
    public InputStream openInputStream(
        BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
      return getBlob().openInputStream(null, options, opContext);
    }

    public OutputStream openOutputStream(
        BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
      return ((CloudBlockBlob) getBlob()).openOutputStream(null, options, opContext);
    }

    public void upload(InputStream sourceStream, OperationContext opContext)
        throws StorageException, IOException {
      getBlob().upload(sourceStream, 0, null, null, opContext);
    }

    @Override
    public CloudBlobContainer getContainer() throws URISyntaxException,
        StorageException {
      return getBlob().getContainer();
    }

    @Override
    public CloudBlobDirectory getParent() throws URISyntaxException,
        StorageException {
      return getBlob().getParent();
    }

    @Override
    public void uploadMetadata(OperationContext opContext)
        throws StorageException {
      uploadMetadata(null, null, opContext);
    }

    @Override
    public void uploadMetadata(AccessCondition accessConditions, BlobRequestOptions options,
        OperationContext opContext) throws StorageException{
      getBlob().uploadMetadata(accessConditions, options, opContext);
    }

    public void uploadProperties(OperationContext opContext, SelfRenewingLease lease)
        throws StorageException {

      // Include lease in request if lease not null.
      getBlob().uploadProperties(getLeaseCondition(lease), null, opContext);
    }

    @Override
    public int getStreamMinimumReadSizeInBytes() {
        return getBlob().getStreamMinimumReadSizeInBytes();
    }

    @Override
    public void setStreamMinimumReadSizeInBytes(int minimumReadSizeBytes) {
      getBlob().setStreamMinimumReadSizeInBytes(minimumReadSizeBytes);
    }

    @Override
    public void setWriteBlockSizeInBytes(int writeBlockSizeBytes) {
      getBlob().setStreamWriteSizeInBytes(writeBlockSizeBytes);
    }

    @Override
    public StorageUri getStorageUri() {
      return getBlob().getStorageUri();
    }

    @Override
    public CopyState getCopyState() {
      return getBlob().getCopyState();
    }

    @Override
    public void startCopyFromBlob(CloudBlobWrapper sourceBlob, BlobRequestOptions options,
        OperationContext opContext)
            throws StorageException, URISyntaxException {
      getBlob().startCopy(sourceBlob.getBlob().getQualifiedUri(),
          null, null, options, opContext);
    }

    @Override
    public void downloadRange(long offset, long length, OutputStream outStream,
        BlobRequestOptions options, OperationContext opContext)
            throws StorageException, IOException {

      getBlob().downloadRange(offset, length, outStream, null, options, opContext);
    }

    @Override
    public SelfRenewingLease acquireLease() throws StorageException {
      return new SelfRenewingLease(this);
    }
  }

  //
  // CloudBlockBlobWrapperImpl
  //

  static class CloudBlockBlobWrapperImpl extends CloudBlobWrapperImpl implements CloudBlockBlobWrapper {
    public CloudBlockBlobWrapperImpl(CloudBlockBlob blob) {
      super(blob);
    }

    public OutputStream openOutputStream(
        BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
      return ((CloudBlockBlob) getBlob()).openOutputStream(null, options, opContext);
    }

    public void upload(InputStream sourceStream, OperationContext opContext)
        throws StorageException, IOException {
      getBlob().upload(sourceStream, 0, null, null, opContext);
    }

    public void uploadProperties(OperationContext opContext)
        throws StorageException {
      getBlob().uploadProperties(null, null, opContext);
    }

    @Override
    public List<BlockEntry> downloadBlockList(BlockListingFilter filter, BlobRequestOptions options,
        OperationContext opContext) throws IOException, StorageException {
      return ((CloudBlockBlob) getBlob()).downloadBlockList(filter, null, options, opContext);

    }

    @Override
    public void uploadBlock(String blockId, InputStream sourceStream,
        long length, BlobRequestOptions options,
        OperationContext opContext) throws IOException, StorageException {
      ((CloudBlockBlob) getBlob()).uploadBlock(blockId, sourceStream, length, null, options, opContext);
    }

    @Override
    public void commitBlockList(List<BlockEntry> blockList, AccessCondition accessCondition, BlobRequestOptions options,
        OperationContext opContext) throws IOException, StorageException {
      ((CloudBlockBlob) getBlob()).commitBlockList(blockList, accessCondition, options, opContext);
    }
  }

  static class CloudPageBlobWrapperImpl extends CloudBlobWrapperImpl implements CloudPageBlobWrapper {
    public CloudPageBlobWrapperImpl(CloudPageBlob blob) {
      super(blob);
    }

    public void create(final long length, BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
      ((CloudPageBlob) getBlob()).create(length, null, options, opContext);
    }

    public void uploadPages(final InputStream sourceStream, final long offset,
        final long length, BlobRequestOptions options, OperationContext opContext)
        throws StorageException, IOException {
      ((CloudPageBlob) getBlob()).uploadPages(sourceStream, offset, length, null,
          options, opContext);
    }

    public ArrayList<PageRange> downloadPageRanges(BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
      return ((CloudPageBlob) getBlob()).downloadPageRanges(
          null, options, opContext);
    }
  }
}


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

Product Details

			<?php
			$arr=array('Product Name','Model Name','Description','Quantity','Price','Added Date');
			$count=0;

			foreach($user_modal as $row) {
			?>

<?=$arr[0]?>

						<?=$row->p_name?>

<?=$arr[1]?>

						<?=$row->p_model?>

<?=$arr[2]?>

						<?php echo html_entity_decode($row->p_description, ENT_QUOTES);?>

<?=$arr[3]?>

						<?=$row->p_quantity?>

<?=$arr[4]?>

						¥<?=$row->price?>

<?=$arr[5]?>

						<?=$row->add_date?>

			<?php
			$count++;
			}
			?>

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


text:
var assert = require("assert")
  , should = require('should')
  , Vantage = require('../../')
  , http = require('http')
  , _ = require('lodash')
  , chalk = require("chalk")
  ;

module.exports = function(vantage) {

  vantage
    .command('foo')
    .description('Should return "bar".')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log('bar');
        resolve();
      });
    });

  vantage
    .command("fuzzy")
    .description("Should return 'wuzzy'.")
    .action(function(args, cb) {
      var self = this;
      return new Promise(function(resolve, reject){
        self.log("wuzzy");
        resolve();
      });
    });

  vantage
    .command('optional [arg]')
    .description('Should optionally return an arg.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log(args.arg || '');
        resolve();
      });
    });

  vantage
    .command('port')
    .description('Returns port.')
    .action(function(args, cb){
      this.log(this.server._port);
      cb(void 0, this.parent.server._port);
    });

  vantage
    .command('i want')
    .description('Negative args.')
    .option('-N, --no-cheese', 'No chease please.')
    .action(function(args, cb){
      this.log(args.options.cheese);
      cb();
    });

  vantage
    .command('required <arg>')
    .description('Must return an arg.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log(args.arg);
        resolve();
      });
    });

  vantage
    .command('fail me <arg>')
    .description('Must return an arg.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        if (args.arg == 'not') {
          resolve('we are happy');
        } else {
          reject('we are not happy.');
        }
      });
    });

  vantage
    .command('deep command [arg]')
    .description('Tests execution of deep command.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log(args.arg);
        resolve();
      });
    });

  vantage
    .command('very deep command [arg]')
    .description('Tests execution of three-deep command.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log(args.arg);
        resolve();
      });
    });

  vantage
    .command('count <number>')
    .description('Tests execution of three-deep command.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){
        self.log(args.number);
        resolve();
      });
    });

  vantage
    .command('very complicated deep command [arg]')
    .option('-r', 'Test Option.')
    .option('-a', 'Test Option.')
    .option('-d', 'Test Option.')
    .option('-s, --sleep', 'Test Option.')
    .option('-t', 'Test Option.')
    .option('-i [param]', 'Test Option.')
    .description('Tests execution of three-deep command.')
    .action(function(args, cb){
      var self = this;
      return new Promise(function(resolve, reject){

        var str = '';
        str = (args.options.r === true) ? str + 'r' : str;
        str = (args.options.a === true) ? str + 'a' : str;
        str = (args.options.d === true) ? str + 'd' : str;
        str = (args.options.t === true) ? str + 't' : str;
        str = (args.options.i === 'j') ? str + args.options.i : str;
        str = (args.options.sleep === 'well') ? str + args.options.sleep : str;
        str = str + (args.arg || '');

        self.log(str);
        resolve();
      });
    });

}


text:
package matcher

import (
	"regexp"
	"strings"

	routepb "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
	matcher "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
)

// HeaderMatcher converts a key, value string pair to a corresponding HeaderMatcher.
func HeaderMatcher(k, v string) *routepb.HeaderMatcher {
	// We must check "*" first to make sure we'll generate a non empty value in the prefix/suffix case.
	// Empty prefix/suffix value is invalid in HeaderMatcher.
	if v == "*" {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_PresentMatch{
				PresentMatch: true,
			},
		}
	} else if strings.HasPrefix(v, "*") {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_SuffixMatch{
				SuffixMatch: v[1:],
			},
		}
	} else if strings.HasSuffix(v, "*") {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_PrefixMatch{
				PrefixMatch: v[:len(v)-1],
			},
		}
	}
	return &routepb.HeaderMatcher{
		Name: k,
		HeaderMatchSpecifier: &routepb.HeaderMatcher_ExactMatch{
			ExactMatch: v,
		},
	}
}

// HostMatcherWithRegex creates a host matcher for a host using regex for proxies before 1.11.
func HostMatcherWithRegex(k, v string) *routepb.HeaderMatcher {
	var regex string
	if v == "*" {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_PresentMatch{
				PresentMatch: true,
			},
		}
	} else if strings.HasPrefix(v, "*") {
		regex = `.*` + regexp.QuoteMeta(v[1:])
	} else if strings.HasSuffix(v, "*") {
		regex = regexp.QuoteMeta(v[:len(v)-1]) + `.*`
	} else {
		regex = regexp.QuoteMeta(v)
	}
	return &routepb.HeaderMatcher{
		Name: k,
		HeaderMatchSpecifier: &routepb.HeaderMatcher_SafeRegexMatch{
			SafeRegexMatch: &matcher.RegexMatcher{
				EngineType: &matcher.RegexMatcher_GoogleRe2{
					GoogleRe2: &matcher.RegexMatcher_GoogleRE2{},
				},
				Regex: `(?i)` + regex,
			},
		},
	}
}

// HostMatcher creates a host matcher for a host.
func HostMatcher(k, v string) *routepb.HeaderMatcher {
	// We must check "*" first to make sure we'll generate a non empty value in the prefix/suffix case.
	// Empty prefix/suffix value is invalid in HeaderMatcher.
	if v == "*" {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_PresentMatch{
				PresentMatch: true,
			},
		}
	} else if strings.HasPrefix(v, "*") {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_StringMatch{
				StringMatch: &matcher.StringMatcher{
					IgnoreCase: true,
					MatchPattern: &matcher.StringMatcher_Suffix{
						Suffix: v[1:],
					},
				},
			},
		}
	} else if strings.HasSuffix(v, "*") {
		return &routepb.HeaderMatcher{
			Name: k,
			HeaderMatchSpecifier: &routepb.HeaderMatcher_StringMatch{
				StringMatch: &matcher.StringMatcher{
					IgnoreCase: true,
					MatchPattern: &matcher.StringMatcher_Prefix{
						Prefix: v[:len(v)-1],
					},
				},
			},
		}
	}
	return &routepb.HeaderMatcher{
		Name: k,
		HeaderMatchSpecifier: &routepb.HeaderMatcher_StringMatch{
			StringMatch: &matcher.StringMatcher{
				IgnoreCase: true,
				MatchPattern: &matcher.StringMatcher_Exact{
					Exact: v,
				},
			},
		},
	}
}

// PathMatcher creates a path matcher for a path.
func PathMatcher(path string) *matcher.PathMatcher {
	return &matcher.PathMatcher{
		Rule: &matcher.PathMatcher_Path{
			Path: StringMatcher(path),
		},
	}
}


text:
function [] = plot_distribution(fit)

number_of_components = numel(fit.components);

COLORS = get(groot,'DefaultAxesColorOrder');

fig = figure();
fig.Units = 'centimeters';
fig.PaperUnits = 'centimeters';
fig.Position = [0 0 12 9];
fig.PaperPosition = [0 0 12 9];

ax1 = subplot('Position',[0.15 0.20 0.8 0.75]);
ax1.FontSize = 12;
ax1.Box = 'on';
ax1.XLabel.String = 'T (s)';
ax1.YLabel.String = 'Probability';
ax1.XScale = 'log';

minT = inf;
maxT = 0;

for current_component = 1:number_of_components
    switch fit.components{current_component}.model
        case 'exponential'
            minT = min(minT, fit.components{current_component}.T);
            maxT = max(maxT, fit.components{current_component}.T);
        case 'stretchedexponential'
            minT = min(minT, fit.components{current_component}.T);
            maxT = max(maxT, fit.components{current_component}.T);
        case 'lognormal'
            minT = min(minT, logninv(1e-6, fit.components{current_component}.mu, fit.components{current_component}.sigma));
            maxT = max(maxT, logninv(1-1e-6, fit.components{current_component}.mu, fit.components{current_component}.sigma));
        case 'inversegamma' % NB the 'P' values for the inversion are 'inverted', P -> 1 - P, evaluated for the gamma, not the inversegamma
            minT = min(minT, 1 / gaminv(1-1e-6, fit.components{current_component}.alpha, 1 / fit.components{current_component}.beta));
            maxT = max(maxT, 1 / gaminv(1e-6, fit.components{current_component}.alpha, 1 / fit.components{current_component}.beta));
    end
end

minT = 0.5 * minT;
maxT = 2.0 * maxT;

TT = logspace(log10(minT),log10(maxT),10000);
y = zeros(size(TT));

for current_component = 1:number_of_components
    switch fit.components{current_component}.model
        case 'exponential'
            hl = line(ones(1,2) * fit.components{current_component}.T,[0 fit.components{current_component}.theta]);
            hl.Color = COLORS(1, :);
        case 'stretchedexponential'
            hl = line(ones(1,2) * fit.components{current_component}.T,[0 fit.components{current_component}.theta]);
            hl.Color = COLORS(1, :);
        case 'lognormal'
            y = y + fit.components{current_component}.theta * lognpdf(TT,fit.components{current_component}.mu,fit.components{current_component}.sigma);
        case 'inversegamma'
            y = y + fit.components{current_component}.theta * inversegamma_pdf(TT, fit.components{current_component}.alpha, fit.components{current_component}.beta);
    end
end
hl = line(TT, y / max(y));
hl.Color = COLORS(1, :);

end


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

#include "panopticon.h"

#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <uv.h>

#include "process.h"
#include "stats.h"

#ifdef COLLECT_STATS
stats_t stats = {};
#endif

extern const char *__progname;

static void usage(void) {
  fprintf(stderr, "Usage: %s [OPTIONS]\n", __progname);
  fprintf(stderr, "Version: %s\n", PACKAGE_STRING);
  fprintf(stderr, "\n");
  fprintf(stderr, " -d, --debug        be more verbose.\n");
  fprintf(stderr, " -h, --help         display help and exit\n");
  fprintf(stderr, " -v, --version      print version and exit\n");
  fprintf(stderr, "\n");
  fprintf(stderr, "see manual page " PACKAGE "(8) for more information\n");
}

void signal_handler(uv_signal_t *handle, int signum) {
  printf("Signal received: %d\n", signum);
  uv_signal_stop(handle);
}

void timer_handler(uv_timer_t *handle) {
  printf("Timing out\n");
  exit(0);
}

int main(int argc, char *argv[]) {
  int debug = 1;
  int ch;

  static struct option long_options[] = {{"debug", no_argument, 0, 'd'},
                                         {"help", no_argument, 0, 'h'},
                                         {"version", no_argument, 0, 'v'},
                                         {0}};
  while (1) {
    int option_index = 0;
    ch = getopt_long(argc, argv, "hvdD:", long_options, &option_index);
    if (ch == -1)
      break;
    switch (ch) {
    case 'h':
      usage();
      exit(0);
      break;
    case 'v':
      fprintf(stdout, "%s\n", PACKAGE_VERSION);
      exit(0);
      break;
    case 'd':
      debug++;
      break;
    case 'D':
      log_accept(optarg);
      break;
    default:
      fprintf(stderr, "unknown option `%c'\n", ch);
      usage();
      exit(1);
    }
  }

  log_init(debug, __progname);

  process_list_t *p = process_list_new(geteuid());
  process_list_processes(&p);
  sleep(1);
  process_list_t *p1 = process_list_new(geteuid());
  process_list_processes(&p1);

  process_usage_list_t *n = process_get_usage(p, p1);

  process_t *elt = NULL;
  process_usage_t *uelt = NULL;
  int count = 0;

  printf("ts: %ld d: %ld\n", n->timestamp, n->measure_delta);
  DL_FOREACH(n->usages, uelt) process_usage_print(uelt);
  //DL_FOREACH(p->processes, elt) process_print(elt);
  printf("ts: %ld\n", p->timestamp);
  DL_COUNT(p->processes, elt, count);

  printf("found %d processes\n", count);

#ifdef COLLECT_STATS
  dump_stats(stats);
#endif

  uv_loop_t *loop = malloc(sizeof(uv_loop_t));
  uv_loop_init(loop);

  log_info("main", "hello world!");

  uv_signal_t sig_int;
  uv_signal_init(loop, &sig_int);
  uv_signal_start(&sig_int, signal_handler, SIGINT);

  uv_timer_t timer;
  uv_timer_init(loop, &timer);
  uv_timer_start(&timer, timer_handler, 1000, 0);

  uv_run(loop, UV_RUN_DEFAULT);

  uv_loop_close(loop);
  free(loop);

  return EXIT_SUCCESS;
}


text:
package org.cee.webreader.client.list;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HasEnabled;

public class MultiSelectListPresenter<K> {

    private final MultiSelectListModel<K> multiModel;

    private final ContentModel<K> contentModel;

    private final ListView sourceView;

    private final ListView selectionView;

    private final Map<K, HasEnabled> sourceItems;

    public MultiSelectListPresenter(final MultiSelectListModel<K> multiModel, final ContentModel<K> contentModel, final ListView sourceView, final ListView selectionView) {
        this.multiModel = multiModel;
        this.contentModel = contentModel;
        this.sourceView = sourceView;
        this.selectionView = selectionView;
        this.sourceItems = new HashMap<K, HasEnabled>();

        multiModel.addListChangedHandler(new ListChangedHandler<K>() {
            public void onContentListChanged(ListChangedEvent<K> event) {
                fillSourceList(event.getValues());
            }
        });

        multiModel.addSelectionListChangedHandler(new SelectionListChangedHandler<K>() {
            public void onSelectionListChanged(SelectionListChangedEvent<K> event) {
                fillSelectionList(event.getKeys());
            }
        });
    }

    protected void fillSourceList(List<K> keys) {
        sourceView.removeAll();
        sourceItems.clear();
        for (final K key : keys) {
            ListItemView item = sourceView.addItem();
            contentModel.getContentDescription(item, key);
            item.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    addSelection(key);
                }
            });
            sourceItems.put(key, item);
        }
    }

    protected void fillSelectionList(List<K> keys) {
        selectionView.removeAll();
        for (Entry<K, HasEnabled> entry : sourceItems.entrySet()) {
			entry.getValue().setEnabled(true);
		}
        for (final K key : keys) {
            ListItemView item = selectionView.addItem();
            contentModel.getContentDescription(item, key);
            item.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    removeSelection(key);
                }
            });
            sourceItems.get(key).setEnabled(false);
        }
    }

    protected void addSelection(K key) {
        multiModel.addSelection(key);
        sourceItems.get(key).setEnabled(false);
    }

    protected void removeSelection(K key) {
        multiModel.removeSelection(key);
        sourceItems.get(key).setEnabled(true);
    }
}


text:
#ifndef BERRYIINTROPART_H_
#define BERRYIINTROPART_H_

#include <berryObject.h>
#include <berryMacros.h>

#include <berryIMemento.h>
#include <berryIPropertyChangeListener.h>
#include <berryUIException.h>

#include "berryIIntroSite.h"

#include <QObject>

namespace berry {

/**
 * The intro part is a visual component within the workbench responsible for
 * introducing the product to new users. The intro part is typically shown the
 * first time a product is started up.
 *

 * The intro part implementation is contributed to the workbench via the
 * org.blueberry.ui.intro extension point.  There can be several
 * intro part implementations, and associations between intro part
 * implementations and products. The workbench will only make use of the intro
 * part implementation for the current product (as given by
 * {@link berry::Platform#GetProduct()}. There is at most one
 * intro part instance in the entire workbench, and it resides in exactly one
 * workbench window at a time.
 *

 *

 * This interface in not intended to be directly implemented. Rather, clients
 * providing a intro part implementation should subclass
 * {@link berry::IntroPart}.
 *

 *
 * @see IIntroManager#ShowIntro(IWorkbenchWindow::Pointer, bool)
 * @noimplement This interface is not intended to be implemented by clients.
 */
struct BERRY_UI IIntroPart : public virtual Object { // IAdaptable {

  berryInterfaceMacro(IIntroPart, berry);

  ~IIntroPart();

    /**
   * The property id for getTitleImage and
   * getTitle.
   *
   * @since 3.2 this property now covers changes to getTitle in
   *        addition to getTitleImage
   */
   //static const int PROP_TITLE = IWorkbenchPart::PROP_TITLE;

    /**
   * Returns the site for this intro part.
   *
   * @return the intro site
   */
   virtual IIntroSite::Pointer GetIntroSite() const = 0;

    /**
     * Initializes this intro part with the given intro site. A memento is
     * passed to the part which contains a snapshot of the part state from a
     * previous session. Where possible, the part should try to recreate that
     * state.
     *

     * This method is automatically called by the workbench shortly after
     * part construction.  It marks the start of the intro's lifecycle. Clients
     * must not call this method.
     *

     *
     * @param site the intro site
     * @param memento the intro part state or null if there is no previous
     * saved state
     * @exception PartInitException if this part was not initialized
     * successfully
     */
    virtual void Init(IIntroSite::Pointer site, IMemento::Pointer memento)
            throw(PartInitException) = 0;

    /**
     * Sets the standby state of this intro part. An intro part should render
     * itself differently in the full and standby modes. In standby mode, the
     * part should be partially visible to the user but otherwise allow them
     * to work. In full mode, the part should be fully visible and be the center
     * of the user's attention.
     *

     * This method is automatically called by the workbench at appropriate
     * times. Clients must not call this method directly (call
     * {@link IIntroManager#setIntroStandby(IIntroPart, boolean)} instead.
     *

     *
     * @param standby true to put this part in its partially
     * visible standy mode, and false to make it fully visible
     */
    virtual void StandbyStateChanged(bool standby) = 0;

    /**
     * Saves the object state within a memento.
     *

     * This method is automatically called by the workbench at appropriate
     * times. Clients must not call this method directly.
     *

     *
     * @param memento a memento to receive the object state
     */
    virtual void SaveState(IMemento::Pointer memento) = 0;

    /**
     * Adds a listener for changes to properties of this intro part.
     * Has no effect if an identical listener is already registered.
     *

     * The properties ids are as follows:
     *

     *
IIntroPart.PROP_TITLE

     *

     *

     *
     * @param listener a property listener
     */
    virtual void AddPropertyListener(IPropertyChangeListener::Pointer listener) = 0;

    /**
     * Creates the SWT controls for this intro part.
     *

     * Clients should not call this method (the workbench calls this method when
     * it needs to, which may be never).
     *

     *

     * For implementors this is a multi-step process:
     *

     *
Create one or more controls within the parent.

     *
Set the parent layout as needed.

     *
Register any global actions with the IActionService.

     *
Register any popup menus with the IActionService.

     *
Register a selection provider with the ISelectionService
     *     (optional).

     *

     *

     *
     * @param parent the parent control
     */
    virtual void CreatePartControl(void* parent) = 0;

    /**
     * Returns the title image of this intro part.  If this value changes
     * the part must fire a property listener event with
     * {@link IIntroPart#PROP_TITLE}.
     *

     * The title image is usually used to populate the title bar of this part's
     * visual container. Since this image is managed by the part itself, callers
     * must not dispose the returned image.
     *

     *
     * @return the title image
     */
    virtual void* GetTitleImage() const = 0;

    /**
     * Returns the title of this intro part. If this value changes
     * the part must fire a property listener event with
     * {@link IIntroPart#PROP_TITLE}.
     *

     * The title is used to populate the title bar of this part's visual
     * container.
     *

     *
     * @return the intro part title (not null)
     * @since 3.2
     */
    virtual std::string GetPartName() const = 0;

    /**
     * Removes the given property listener from this intro part.
     * Has no affect if an identical listener is not registered.
     *
     * @param listener a property listener
     */
    virtual void RemovePropertyListener(IPropertyChangeListener::Pointer listener) = 0;

    /**
     * Asks this part to take focus within the workbench.
     *

     * Clients should not call this method (the workbench calls this method at
     * appropriate times).  To have the workbench activate a part, use
     * {@link IIntroManager#showIntro(IWorkbenchWindow, boolean)}.
     *

     */
    virtual void SetFocus() = 0;
};

}

Q_DECLARE_INTERFACE(berry::IIntroPart, "org.blueberry.IIntroPart")

#endif /* BERRYIINTROPART_H_ */


text:
require 'singleton'

module CheckTaskr

  class JobsAction
    attr_accessor :name

    @@default_error_code = nil
    @@default_error_msg = nil
    def self.setup(options={})
      @@default_error_code = options[:default_error_code]
      @@default_error_msg = options[:default_error_msg]
    end
  end

  class JobsConfiguration

    include Singleton
    include Log4r

    attr_accessor :sleep_time, :results, :listen_port, :locked
    attr_reader :load_paths, :actions

    def initialize
      @actions = []
      @sleep_time = 8
      @results = Hash.new
      @listen_port = 4567
      @locked = false
    end

    def add_item(item)
      if @items.nil?
        @items = Array.new
      end
      @items.add(item)
    end

    def lock
      @locked = true
    end

    def unlock
      @locked = false
    end

    def self.init(options = {})
      _instance = self.instance
      _instance.sleep_time = options[:sleep_time] || 8
      _instance.listen_port = options[:port] || 4567
      if block_given?
        yield _instance
      end
    end

    def execute_all
      log = Log4r::Logger['default']
      return if @locked
      results = Hash.new
      had_error = false

      fail_actions = run_actions(@actions, results)

      # 如果有失败,过0.1秒后重试失败的
      if fail_actions.size > 0
        sleep(0.1)
        fail_actions2 = run_actions(fail_actions, results)
        if fail_actions2.size > 0
          # 还失败的话,过1秒后重新试一次
          sleep(1)
          run_actions(fail_actions2, results)
        end
      end
      @results.clear
      @results = results
    end

    def run_actions(actions, results)
      fail_actions = []
      log = Log4r::Logger['default']
      actions.each do |action|
        hash = action.execute
        unless hash.nil?
          if hash["ip"].nil? && hash[:ip].nil?
            hash.each do |k, v|
              unless (v["ip"].nil? && v[:ip].nil?)
                results["#{action.name}_#{k}"] = v
              end
            end
          else
            results[action.name] = hash
          end
          state_code = hash[:stat] || hash['stat']
          if !"0".eql?(state_code) && !0.eql?(state_code)
            log.error "#{Time.now}:#{hash.to_json}"
            fail_actions << action
          end
        end
      end
      fail_actions
    end

    def load_from_file(file, name=nil)
      file = find_file_in_load_path(file) unless File.file?(file)
      string = File.read(file)
      instance_eval(string, name || "<eval>")
    end

    # set log level
    def log_level(level)
      log = Log4r::Logger['default']
      log.level = level
    end

    # process hosts from options
    def process_hosts(options)
      log = Log4r::Logger['default']
      hosts = options.delete(:hosts)
      if block_given?
        if hosts.nil?
          throw Exception.new("Must include :hosts option")
        end
        if hosts.class.eql?(String)
          yield hosts
        else
          hosts.each do |host|
            yield host
          end
        end
      end
    end

    private

    def find_file_in_load_path(file)
      [".", File.expand_path(File.join(File.dirname(__FILE__), "../recipes"))].each do |path|
        ["", ".rb"].each do |ext|
          name = File.join(path, "#{file}#{ext}")
          return name if File.file?(name)
        end
      end

      raise LoadError, "no such file to load -- #{file}"
    end

  end

end


text:
import gulp from 'gulp';
import consolidate from 'gulp-consolidate';
import config from '../config';

import 'require-yaml';

gulp.task('list-pages', function() {
  delete require.cache[require.resolve('../../' + config.src.pagelist)]
    const pages = require('../../' + config.src.pagelist);
    return gulp
      .src(__dirname + '/index/index.html')
      .pipe(consolidate('lodash', {
        pages: pages
      }))
      .pipe(gulp.dest(config.dest.html));
});

const build = gulp => gulp.parallel('list-pages');
const watch = gulp => () => gulp.watch(config.src.root+'/*', gulp.series('list-pages'));

module.exports.build = build;
module.exports.watch = watch;


text:
package org.dfhu.thpwa.context;

import spark.Request;
import spark.Response;

public class ThSession {
  private final Request req;
  private final Response res;

  private ThSession(Request req, Response res) {
    this.req = req;
    this.res = res;
  }

  public Request getReq() {
    return req;
  }

  public Response getRes() {
    return res;
  }

  /** Stub not implemented */
  public void logout() {
  }

  static ThSession newInstance(Request req, Response res) {
    return new ThSession(req, res);
  }
}


text:
cd `dirname $0`
cd ..

pushd ../maihama-base
mvn -e install

pushd ../maihama-common
rm -f target/maihama-common.jar
mvn -e install -Dmaven.test.skip=true
popd


text:
package org.pro.ygcms.application;

import java.util.List;
import java.util.Set;
import  org.pro.ygcms.core.domain.ftp.CmsFtp;

public interface CmsFtpApplication {

	public CmsFtp getCmsFtp(String id);

	public void creatCmsFtp(CmsFtp cmsFtp);

	public void updateCmsFtp(CmsFtp cmsFtp);

	public void removeCmsFtp(CmsFtp cmsFtp);

	public void removeCmsFtps(Set<CmsFtp> cmsFtps);

	public List<CmsFtp> findAllCmsFtp();

}


text:
var Mods = require('/modules');
var $$ = require(Mods.styles);

var MyFish = require(Mods.fish);
var MyEnemy = require(Mods.enemy);

module.exports = function() {

	var win = Ti.UI.createWindow($$.win);
	win.opacity = 1;
	win.backgroundImage = 'ui/images/bg.jpg';

	var close = Ti.UI.createButton({
		title:'Cerrar',
		top:5,right:5,
		backgroundImage:'none'
	});
	win.add(close);
	close.addEventListener('click', function() {
		var dialog = Ti.UI.createAlertDialog({
			title:'Cerrar',
			message:'¿Seguro que deseas abandonar la partida?',
			buttonNames:['Sí', 'No'],
			cancel:1
		});

		dialog.show();

		dialog.addEventListener('click', function(e) {
			if (e.index === 0) {
				win.close();
			}
		});
	});

	points = Ti.UI.createLabel({
		bottom:5,
		left:5,
		color:'white',
		text:0
	});

	win.add(points);

	var fish = new MyFish();

	win.add(fish);

	function loseFunction() {
		var dead = Ti.Media.createSound({
			url:'ui/sounds/eructos.mp3',
			time:30.5
		});
		dead.play();
		Ti.UI.createAlertDialog({
			title:'¡Has perdido!',
			message:'¡Te han comido! Inténtalo de nuevo',
			ok:'Vale'
		}).show();
		win.close();
	}

	var audio = Ti.Media.createSound({
		url:'ui/sounds/rot.mp3',
		time:1
	});
	audio.play();
	audio.pause();

	function eatFunction(level) {

		audio.play();
		audio.time = 1;

		var currentpoints = parseInt(points.text) + 1;
		if (currentpoints == 10) {
			fish.width = parseInt(fish.width) + 10;
			fish.height = parseInt(fish.height) + 10;
			points.text = 0;
			if (fish.width == 90) {
				Ti.UI.createAlertDialog({
					title:'¡Victoria!',
					message:'¡Enhorabuena! Te has comido a todos los peces del océano, ¡GORD@!',
					ok:'Vale'
				}).show();
				win.close();
			}
		} else {
			points.text = currentpoints;
		}

	}

	var interval = setInterval(function() {

		var random = Math.floor(Math.random() * 5);

		var enemy = new MyEnemy({
			level:random,
			fish:fish,
			cb_lose:loseFunction,
			cb_eat:eatFunction,
			win:win
		});

		win.add(enemy);

	}, 800);

	win.addEventListener('close', function() {
		clearInterval(interval);
	});

	return win;

};