text:
import unittest2

class Test__BlobIterator(unittest2.TestCase):

    def _getTargetClass(self):
        from gcloud.storage.bucket import _BlobIterator
        return _BlobIterator

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_ctor(self):
        connection = _Connection()
        client = _Client(connection)
        bucket = _Bucket()
        iterator = self._makeOne(bucket, client=client)
        self.assertTrue(iterator.bucket is bucket)
        self.assertTrue(iterator.client is client)
        self.assertEqual(iterator.path, '%s/o' % bucket.path)
        self.assertEqual(iterator.page_number, 0)
        self.assertEqual(iterator.next_page_token, None)
        self.assertEqual(iterator.prefixes, set())

    def test_get_items_from_response_empty(self):
        connection = _Connection()
        client = _Client(connection)
        bucket = _Bucket()
        iterator = self._makeOne(bucket, client=client)
        blobs = list(iterator.get_items_from_response({}))
        self.assertEqual(blobs, [])
        self.assertEqual(iterator.prefixes, set())

    def test_get_items_from_response_non_empty(self):
        from gcloud.storage.blob import Blob
        BLOB_NAME = 'blob-name'
        response = {'items': [{'name': BLOB_NAME}], 'prefixes': ['foo']}
        connection = _Connection()
        client = _Client(connection)
        bucket = _Bucket()
        iterator = self._makeOne(bucket, client=client)
        blobs = list(iterator.get_items_from_response(response))
        self.assertEqual(len(blobs), 1)
        blob = blobs[0]
        self.assertTrue(isinstance(blob, Blob))
        self.assertEqual(blob.name, BLOB_NAME)
        self.assertEqual(iterator.prefixes, set(['foo']))

    def test_get_items_from_response_cumulative_prefixes(self):
        from gcloud.storage.blob import Blob
        BLOB_NAME = 'blob-name1'
        response1 = {'items': [{'name': BLOB_NAME}], 'prefixes': ['foo']}
        response2 = {
            'items': [],
            'prefixes': ['foo', 'bar'],
        }
        connection = _Connection()
        client = _Client(connection)
        bucket = _Bucket()
        iterator = self._makeOne(bucket, client=client)
        # Parse first response.
        blobs = list(iterator.get_items_from_response(response1))
        self.assertEqual(len(blobs), 1)
        blob = blobs[0]
        self.assertTrue(isinstance(blob, Blob))
        self.assertEqual(blob.name, BLOB_NAME)
        self.assertEqual(iterator.prefixes, set(['foo']))
        # Parse second response.
        blobs = list(iterator.get_items_from_response(response2))
        self.assertEqual(len(blobs), 0)
        self.assertEqual(iterator.prefixes, set(['foo', 'bar']))

class Test_Bucket(unittest2.TestCase):

    def _makeOne(self, client=None, name=None, properties=None):
        from gcloud.storage.bucket import Bucket
        if client is None:
            connection = _Connection()
            client = _Client(connection)
        bucket = Bucket(client, name=name)
        bucket._properties = properties or {}
        return bucket

    def test_ctor(self):
        NAME = 'name'
        properties = {'key': 'value'}
        bucket = self._makeOne(name=NAME, properties=properties)
        self.assertEqual(bucket.name, NAME)
        self.assertEqual(bucket._properties, properties)
        self.assertFalse(bucket._acl.loaded)
        self.assertTrue(bucket._acl.bucket is bucket)
        self.assertFalse(bucket._default_object_acl.loaded)
        self.assertTrue(bucket._default_object_acl.bucket is bucket)

    def test_blob(self):
        from gcloud.storage.blob import Blob

        BUCKET_NAME = 'BUCKET_NAME'
        BLOB_NAME = 'BLOB_NAME'
        CHUNK_SIZE = 1024 * 1024

        bucket = self._makeOne(name=BUCKET_NAME)
        blob = bucket.blob(BLOB_NAME, chunk_size=CHUNK_SIZE)
        self.assertTrue(isinstance(blob, Blob))
        self.assertTrue(blob.bucket is bucket)
        self.assertTrue(blob.client is bucket.client)
        self.assertEqual(blob.name, BLOB_NAME)
        self.assertEqual(blob.chunk_size, CHUNK_SIZE)

    def test_exists_miss(self):
        from gcloud.exceptions import NotFound

        class _FakeConnection(object):

            _called_with = []

            @classmethod
            def api_request(cls, *args, **kwargs):
                cls._called_with.append((args, kwargs))
                raise NotFound(args)

        BUCKET_NAME = 'bucket-name'
        bucket = self._makeOne(name=BUCKET_NAME)
        client = _Client(_FakeConnection)
        self.assertFalse(bucket.exists(client=client))
        expected_called_kwargs = {
            'method': 'GET',
            'path': bucket.path,
            'query_params': {
                'fields': 'name',
            },
            '_target_object': None,
        }
        expected_cw = [((), expected_called_kwargs)]
        self.assertEqual(_FakeConnection._called_with, expected_cw)

    def test_exists_hit(self):
        class _FakeConnection(object):

            _called_with = []

            @classmethod
            def api_request(cls, *args, **kwargs):
                cls._called_with.append((args, kwargs))
                # exists() does not use the return value
                return object()

        BUCKET_NAME = 'bucket-name'
        bucket = self._makeOne(name=BUCKET_NAME)
        client = _Client(_FakeConnection)
        self.assertTrue(bucket.exists(client=client))
        expected_called_kwargs = {
            'method': 'GET',
            'path': bucket.path,
            'query_params': {
                'fields': 'name',
            },
            '_target_object': None,
        }
        expected_cw = [((), expected_called_kwargs)]
        self.assertEqual(_FakeConnection._called_with, expected_cw)

    def test_create_hit(self):
        BUCKET_NAME = 'bucket-name'
        DATA = {'name': BUCKET_NAME}
        connection = _Connection(DATA)
        PROJECT = 'PROJECT'
        client = _Client(connection, project=PROJECT)
        bucket = self._makeOne(client=client, name=BUCKET_NAME)
        bucket.create()

        kw, = connection._requested
        self.assertEqual(kw['method'], 'POST')
        self.assertEqual(kw['path'], '/b')
        self.assertEqual(kw['query_params'], {'project': PROJECT})
        self.assertEqual(kw['data'], DATA)

    def test_acl_property(self):
        from gcloud.storage.acl import BucketACL
        bucket = self._makeOne()
        acl = bucket.acl
        self.assertTrue(isinstance(acl, BucketACL))
        self.assertTrue(acl is bucket._acl)

    def test_default_object_acl_property(self):
        from gcloud.storage.acl import DefaultObjectACL
        bucket = self._makeOne()
        acl = bucket.default_object_acl
        self.assertTrue(isinstance(acl, DefaultObjectACL))
        self.assertTrue(acl is bucket._default_object_acl)

    def test_path_no_name(self):
        bucket = self._makeOne()
        self.assertRaises(ValueError, getattr, bucket, 'path')

    def test_path_w_name(self):
        NAME = 'name'
        bucket = self._makeOne(name=NAME)
        self.assertEqual(bucket.path, '/b/%s' % NAME)

    def test_get_blob_miss(self):
        NAME = 'name'
        NONESUCH = 'nonesuch'
        connection = _Connection()
        client = _Client(connection)
        bucket = self._makeOne(name=NAME)
        result = bucket.get_blob(NONESUCH, client=client)
        self.assertTrue(result is None)
        kw, = connection._requested
        self.assertEqual(kw['method'], 'GET')
        self.assertEqual(kw['path'], '/b/%s/o/%s' % (NAME, NONESUCH))

    def test_get_blob_hit(self):
        NAME = 'name'
        BLOB_NAME = 'blob-name'
        connection = _Connection({'name': BLOB_NAME})
        client = _Client(connection)
        bucket = self._makeOne(name=NAME)
        blob = bucket.get_blob(BLOB_NAME, client=client)
        self.assertTrue(blob.bucket is bucket)
        self.assertEqual(blob.name, BLOB_NAME)
        kw, = connection._requested
        self.assertEqual(kw['method'], 'GET')
        self.assertEqual(kw['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))

    def test_list_blobs_defaults(self):
        NAME = 'name'
        connection = _Connection({'items': []})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        iterator = bucket.list_blobs()
        blobs = list(iterator)
        self.assertEqual(blobs, [])
        kw, = connection._requested
        self.assertEqual(kw['method'], 'GET')
        self.assertEqual(kw['path'], '/b/%s/o' % NAME)
        self.assertEqual(kw['query_params'], {'projection': 'noAcl'})

    def test_list_blobs_w_all_arguments(self):
        NAME = 'name'
        MAX_RESULTS = 10
        PAGE_TOKEN = 'ABCD'
        PREFIX = 'subfolder'
        DELIMITER = '/'
        VERSIONS = True
        PROJECTION = 'full'
        FIELDS = 'items/contentLanguage,nextPageToken'
        EXPECTED = {
            'maxResults': 10,
            'pageToken': PAGE_TOKEN,
            'prefix': PREFIX,
            'delimiter': DELIMITER,
            'versions': VERSIONS,
            'projection': PROJECTION,
            'fields': FIELDS,
        }
        connection = _Connection({'items': []})
        client = _Client(connection)
        bucket = self._makeOne(name=NAME)
        iterator = bucket.list_blobs(
            max_results=MAX_RESULTS,
            page_token=PAGE_TOKEN,
            prefix=PREFIX,
            delimiter=DELIMITER,
            versions=VERSIONS,
            projection=PROJECTION,
            fields=FIELDS,
            client=client,
        )
        blobs = list(iterator)
        self.assertEqual(blobs, [])
        kw, = connection._requested
        self.assertEqual(kw['method'], 'GET')
        self.assertEqual(kw['path'], '/b/%s/o' % NAME)
        self.assertEqual(kw['query_params'], EXPECTED)

    def test_list_blobs(self):
        NAME = 'name'
        connection = _Connection({'items': []})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        iterator = bucket.list_blobs()
        blobs = list(iterator)
        self.assertEqual(blobs, [])
        kw, = connection._requested
        self.assertEqual(kw['method'], 'GET')
        self.assertEqual(kw['path'], '/b/%s/o' % NAME)
        self.assertEqual(kw['query_params'], {'projection': 'noAcl'})

    def test_delete_miss(self):
        from gcloud.exceptions import NotFound
        NAME = 'name'
        connection = _Connection()
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        self.assertRaises(NotFound, bucket.delete)
        expected_cw = [{
            'method': 'DELETE',
            'path': bucket.path,
            '_target_object': None,
        }]
        self.assertEqual(connection._deleted_buckets, expected_cw)

    def test_delete_hit(self):
        NAME = 'name'
        GET_BLOBS_RESP = {'items': []}
        connection = _Connection(GET_BLOBS_RESP)
        connection._delete_bucket = True
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        result = bucket.delete(force=True)
        self.assertTrue(result is None)
        expected_cw = [{
            'method': 'DELETE',
            'path': bucket.path,
            '_target_object': None,
        }]
        self.assertEqual(connection._deleted_buckets, expected_cw)

    def test_delete_force_delete_blobs(self):
        NAME = 'name'
        BLOB_NAME1 = 'blob-name1'
        BLOB_NAME2 = 'blob-name2'
        GET_BLOBS_RESP = {
            'items': [
                {'name': BLOB_NAME1},
                {'name': BLOB_NAME2},
            ],
        }
        DELETE_BLOB1_RESP = DELETE_BLOB2_RESP = {}
        connection = _Connection(GET_BLOBS_RESP, DELETE_BLOB1_RESP,
                                 DELETE_BLOB2_RESP)
        connection._delete_bucket = True
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        result = bucket.delete(force=True)
        self.assertTrue(result is None)
        expected_cw = [{
            'method': 'DELETE',
            'path': bucket.path,
            '_target_object': None,
        }]
        self.assertEqual(connection._deleted_buckets, expected_cw)

    def test_delete_force_miss_blobs(self):
        NAME = 'name'
        BLOB_NAME = 'blob-name1'
        GET_BLOBS_RESP = {'items': [{'name': BLOB_NAME}]}
        # Note the connection does not have a response for the blob.
        connection = _Connection(GET_BLOBS_RESP)
        connection._delete_bucket = True
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        result = bucket.delete(force=True)
        self.assertTrue(result is None)
        expected_cw = [{
            'method': 'DELETE',
            'path': bucket.path,
            '_target_object': None,
        }]
        self.assertEqual(connection._deleted_buckets, expected_cw)

    def test_delete_too_many(self):
        NAME = 'name'
        BLOB_NAME1 = 'blob-name1'
        BLOB_NAME2 = 'blob-name2'
        GET_BLOBS_RESP = {
            'items': [
                {'name': BLOB_NAME1},
                {'name': BLOB_NAME2},
            ],
        }
        connection = _Connection(GET_BLOBS_RESP)
        connection._delete_bucket = True
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)

        # Make the Bucket refuse to delete with 2 objects.
        bucket._MAX_OBJECTS_FOR_ITERATION = 1
        self.assertRaises(ValueError, bucket.delete, force=True)
        self.assertEqual(connection._deleted_buckets, [])

    def test_delete_blob_miss(self):
        from gcloud.exceptions import NotFound
        NAME = 'name'
        NONESUCH = 'nonesuch'
        connection = _Connection()
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        self.assertRaises(NotFound, bucket.delete_blob, NONESUCH)
        kw, = connection._requested
        self.assertEqual(kw['method'], 'DELETE')
        self.assertEqual(kw['path'], '/b/%s/o/%s' % (NAME, NONESUCH))

    def test_delete_blob_hit(self):
        NAME = 'name'
        BLOB_NAME = 'blob-name'
        connection = _Connection({})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        result = bucket.delete_blob(BLOB_NAME)
        self.assertTrue(result is None)
        kw, = connection._requested
        self.assertEqual(kw['method'], 'DELETE')
        self.assertEqual(kw['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))

    def test_delete_blobs_empty(self):
        NAME = 'name'
        connection = _Connection()
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.delete_blobs([])
        self.assertEqual(connection._requested, [])

    def test_delete_blobs_hit(self):
        NAME = 'name'
        BLOB_NAME = 'blob-name'
        connection = _Connection({})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.delete_blobs([BLOB_NAME])
        kw = connection._requested
        self.assertEqual(len(kw), 1)
        self.assertEqual(kw[0]['method'], 'DELETE')
        self.assertEqual(kw[0]['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))

    def test_delete_blobs_miss_no_on_error(self):
        from gcloud.exceptions import NotFound
        NAME = 'name'
        BLOB_NAME = 'blob-name'
        NONESUCH = 'nonesuch'
        connection = _Connection({})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        self.assertRaises(NotFound, bucket.delete_blobs, [BLOB_NAME, NONESUCH])
        kw = connection._requested
        self.assertEqual(len(kw), 2)
        self.assertEqual(kw[0]['method'], 'DELETE')
        self.assertEqual(kw[0]['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))
        self.assertEqual(kw[1]['method'], 'DELETE')
        self.assertEqual(kw[1]['path'], '/b/%s/o/%s' % (NAME, NONESUCH))

    def test_delete_blobs_miss_w_on_error(self):
        NAME = 'name'
        BLOB_NAME = 'blob-name'
        NONESUCH = 'nonesuch'
        connection = _Connection({})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        errors = []
        bucket.delete_blobs([BLOB_NAME, NONESUCH], errors.append)
        self.assertEqual(errors, [NONESUCH])
        kw = connection._requested
        self.assertEqual(len(kw), 2)
        self.assertEqual(kw[0]['method'], 'DELETE')
        self.assertEqual(kw[0]['path'], '/b/%s/o/%s' % (NAME, BLOB_NAME))
        self.assertEqual(kw[1]['method'], 'DELETE')
        self.assertEqual(kw[1]['path'], '/b/%s/o/%s' % (NAME, NONESUCH))

    def test_copy_blobs_wo_name(self):
        SOURCE = 'source'
        DEST = 'dest'
        BLOB_NAME = 'blob-name'

        class _Blob(object):
            name = BLOB_NAME
            path = '/b/%s/o/%s' % (SOURCE, BLOB_NAME)

        connection = _Connection({})
        client = _Client(connection)
        source = self._makeOne(client=client, name=SOURCE)
        dest = self._makeOne(client=client, name=DEST)
        blob = _Blob()
        new_blob = source.copy_blob(blob, dest)
        self.assertTrue(new_blob.bucket is dest)
        self.assertEqual(new_blob.name, BLOB_NAME)
        kw, = connection._requested
        COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s' % (SOURCE, BLOB_NAME,
                                                     DEST, BLOB_NAME)
        self.assertEqual(kw['method'], 'POST')
        self.assertEqual(kw['path'], COPY_PATH)

    def test_copy_blobs_w_name(self):
        SOURCE = 'source'
        DEST = 'dest'
        BLOB_NAME = 'blob-name'
        NEW_NAME = 'new_name'

        class _Blob(object):
            name = BLOB_NAME
            path = '/b/%s/o/%s' % (SOURCE, BLOB_NAME)

        connection = _Connection({})
        client = _Client(connection)
        source = self._makeOne(client=client, name=SOURCE)
        dest = self._makeOne(client=client, name=DEST)
        blob = _Blob()
        new_blob = source.copy_blob(blob, dest, NEW_NAME)
        self.assertTrue(new_blob.bucket is dest)
        self.assertEqual(new_blob.name, NEW_NAME)
        kw, = connection._requested
        COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s' % (SOURCE, BLOB_NAME,
                                                     DEST, NEW_NAME)
        self.assertEqual(kw['method'], 'POST')
        self.assertEqual(kw['path'], COPY_PATH)

    def test_rename_blob(self):
        BUCKET_NAME = 'BUCKET_NAME'
        BLOB_NAME = 'blob-name'
        NEW_BLOB_NAME = 'new-blob-name'

        DATA = {'name': NEW_BLOB_NAME}
        connection = _Connection(DATA)
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=BUCKET_NAME)

        class _Blob(object):

            def __init__(self, name, bucket_name):
                self.name = name
                self.path = '/b/%s/o/%s' % (bucket_name, name)
                self._deleted = []

            def delete(self, client=None):
                self._deleted.append(client)

        blob = _Blob(BLOB_NAME, BUCKET_NAME)
        renamed_blob = bucket.rename_blob(blob, NEW_BLOB_NAME, client=client)
        self.assertTrue(renamed_blob.bucket is bucket)
        self.assertEqual(renamed_blob.name, NEW_BLOB_NAME)
        self.assertEqual(blob._deleted, [client])

    def test_etag(self):
        ETAG = 'ETAG'
        properties = {'etag': ETAG}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.etag, ETAG)

    def test_id(self):
        ID = 'ID'
        properties = {'id': ID}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.id, ID)

    def test_location_getter(self):
        NAME = 'name'
        before = {'location': 'AS'}
        bucket = self._makeOne(name=NAME, properties=before)
        self.assertEqual(bucket.location, 'AS')

    def test_location_setter(self):
        NAME = 'name'
        bucket = self._makeOne(name=NAME)
        self.assertEqual(bucket.location, None)
        bucket.location = 'AS'
        self.assertEqual(bucket.location, 'AS')

    def test_lifecycle_rules_getter(self):
        NAME = 'name'
        LC_RULE = {'action': {'type': 'Delete'}, 'condition': {'age': 42}}
        rules = [LC_RULE]
        properties = {'lifecycle': {'rule': rules}}
        bucket = self._makeOne(name=NAME, properties=properties)
        self.assertEqual(bucket.lifecycle_rules, rules)
        # Make sure it's a copy
        self.assertFalse(bucket.lifecycle_rules is rules)

    def test_lifecycle_rules_setter(self):
        NAME = 'name'
        LC_RULE = {'action': {'type': 'Delete'}, 'condition': {'age': 42}}
        rules = [LC_RULE]
        bucket = self._makeOne(name=NAME)
        self.assertEqual(bucket.lifecycle_rules, [])
        bucket.lifecycle_rules = rules
        self.assertEqual(bucket.lifecycle_rules, rules)

    def test_cors_getter(self):
        NAME = 'name'
        CORS_ENTRY = {
            'maxAgeSeconds': 1234,
            'method': ['OPTIONS', 'GET'],
            'origin': ['127.0.0.1'],
            'responseHeader': ['Content-Type'],
        }
        properties = {'cors': [CORS_ENTRY, {}]}
        bucket = self._makeOne(name=NAME, properties=properties)
        entries = bucket.cors
        self.assertEqual(len(entries), 2)
        self.assertEqual(entries[0], CORS_ENTRY)
        self.assertEqual(entries[1], {})
        # Make sure it was a copy, not the same object.
        self.assertFalse(entries[0] is CORS_ENTRY)

    def test_cors_setter(self):
        NAME = 'name'
        CORS_ENTRY = {
            'maxAgeSeconds': 1234,
            'method': ['OPTIONS', 'GET'],
            'origin': ['127.0.0.1'],
            'responseHeader': ['Content-Type'],
        }
        bucket = self._makeOne(name=NAME)

        self.assertEqual(bucket.cors, [])
        bucket.cors = [CORS_ENTRY]
        self.assertEqual(bucket.cors, [CORS_ENTRY])

    def test_get_logging_w_prefix(self):
        NAME = 'name'
        LOG_BUCKET = 'logs'
        LOG_PREFIX = 'pfx'
        before = {
            'logging': {
                'logBucket': LOG_BUCKET,
                'logObjectPrefix': LOG_PREFIX,
            },
        }
        bucket = self._makeOne(name=NAME, properties=before)
        info = bucket.get_logging()
        self.assertEqual(info['logBucket'], LOG_BUCKET)
        self.assertEqual(info['logObjectPrefix'], LOG_PREFIX)

    def test_enable_logging_defaults(self):
        NAME = 'name'
        LOG_BUCKET = 'logs'
        before = {'logging': None}
        bucket = self._makeOne(name=NAME, properties=before)
        self.assertTrue(bucket.get_logging() is None)
        bucket.enable_logging(LOG_BUCKET)
        info = bucket.get_logging()
        self.assertEqual(info['logBucket'], LOG_BUCKET)
        self.assertEqual(info['logObjectPrefix'], '')

    def test_enable_logging(self):
        NAME = 'name'
        LOG_BUCKET = 'logs'
        LOG_PFX = 'pfx'
        before = {'logging': None}
        bucket = self._makeOne(name=NAME, properties=before)
        self.assertTrue(bucket.get_logging() is None)
        bucket.enable_logging(LOG_BUCKET, LOG_PFX)
        info = bucket.get_logging()
        self.assertEqual(info['logBucket'], LOG_BUCKET)
        self.assertEqual(info['logObjectPrefix'], LOG_PFX)

    def test_disable_logging(self):
        NAME = 'name'
        before = {'logging': {'logBucket': 'logs', 'logObjectPrefix': 'pfx'}}
        bucket = self._makeOne(name=NAME, properties=before)
        self.assertTrue(bucket.get_logging() is not None)
        bucket.disable_logging()
        self.assertTrue(bucket.get_logging() is None)

    def test_metageneration(self):
        METAGENERATION = 42
        properties = {'metageneration': METAGENERATION}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.metageneration, METAGENERATION)

    def test_metageneration_unset(self):
        bucket = self._makeOne()
        self.assertEqual(bucket.metageneration, None)

    def test_metageneration_string_val(self):
        METAGENERATION = 42
        properties = {'metageneration': str(METAGENERATION)}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.metageneration, METAGENERATION)

    def test_owner(self):
        OWNER = {'entity': 'project-owner-12345', 'entityId': '23456'}
        properties = {'owner': OWNER}
        bucket = self._makeOne(properties=properties)
        owner = bucket.owner
        self.assertEqual(owner['entity'], 'project-owner-12345')
        self.assertEqual(owner['entityId'], '23456')

    def test_project_number(self):
        PROJECT_NUMBER = 12345
        properties = {'projectNumber': PROJECT_NUMBER}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.project_number, PROJECT_NUMBER)

    def test_project_number_unset(self):
        bucket = self._makeOne()
        self.assertEqual(bucket.project_number, None)

    def test_project_number_string_val(self):
        PROJECT_NUMBER = 12345
        properties = {'projectNumber': str(PROJECT_NUMBER)}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.project_number, PROJECT_NUMBER)

    def test_self_link(self):
        SELF_LINK = 'http://example.com/self/'
        properties = {'selfLink': SELF_LINK}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.self_link, SELF_LINK)

    def test_storage_class(self):
        STORAGE_CLASS = 'http://example.com/self/'
        properties = {'storageClass': STORAGE_CLASS}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.storage_class, STORAGE_CLASS)

    def test_time_created(self):
        import datetime
        from gcloud._helpers import _RFC3339_MICROS
        from gcloud._helpers import UTC
        TIMESTAMP = datetime.datetime(2014, 11, 5, 20, 34, 37, tzinfo=UTC)
        TIME_CREATED = TIMESTAMP.strftime(_RFC3339_MICROS)
        properties = {'timeCreated': TIME_CREATED}
        bucket = self._makeOne(properties=properties)
        self.assertEqual(bucket.time_created, TIMESTAMP)

    def test_time_created_unset(self):
        bucket = self._makeOne()
        self.assertEqual(bucket.time_created, None)

    def test_versioning_enabled_getter_missing(self):
        NAME = 'name'
        bucket = self._makeOne(name=NAME)
        self.assertEqual(bucket.versioning_enabled, False)

    def test_versioning_enabled_getter(self):
        NAME = 'name'
        before = {'versioning': {'enabled': True}}
        bucket = self._makeOne(name=NAME, properties=before)
        self.assertEqual(bucket.versioning_enabled, True)

    def test_versioning_enabled_setter(self):
        NAME = 'name'
        bucket = self._makeOne(name=NAME)
        self.assertFalse(bucket.versioning_enabled)
        bucket.versioning_enabled = True
        self.assertTrue(bucket.versioning_enabled)

    def test_configure_website_defaults(self):
        NAME = 'name'
        UNSET = {'website': {'mainPageSuffix': None,
                             'notFoundPage': None}}
        bucket = self._makeOne(name=NAME)
        bucket.configure_website()
        self.assertEqual(bucket._properties, UNSET)

    def test_configure_website(self):
        NAME = 'name'
        WEBSITE_VAL = {'website': {'mainPageSuffix': 'html',
                                   'notFoundPage': '404.html'}}
        bucket = self._makeOne(name=NAME)
        bucket.configure_website('html', '404.html')
        self.assertEqual(bucket._properties, WEBSITE_VAL)

    def test_disable_website(self):
        NAME = 'name'
        UNSET = {'website': {'mainPageSuffix': None,
                             'notFoundPage': None}}
        bucket = self._makeOne(name=NAME)
        bucket.disable_website()
        self.assertEqual(bucket._properties, UNSET)

    def test_make_public_defaults(self):
        from gcloud.storage.acl import _ACLEntity
        NAME = 'name'
        permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]
        after = {'acl': permissive, 'defaultObjectAcl': []}
        connection = _Connection(after)
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.acl.loaded = True
        bucket.default_object_acl.loaded = True
        bucket.make_public()
        self.assertEqual(list(bucket.acl), permissive)
        self.assertEqual(list(bucket.default_object_acl), [])
        kw = connection._requested
        self.assertEqual(len(kw), 1)
        self.assertEqual(kw[0]['method'], 'PATCH')
        self.assertEqual(kw[0]['path'], '/b/%s' % NAME)
        self.assertEqual(kw[0]['data'], {'acl': after['acl']})
        self.assertEqual(kw[0]['query_params'], {'projection': 'full'})

    def _make_public_w_future_helper(self, default_object_acl_loaded=True):
        from gcloud.storage.acl import _ACLEntity
        NAME = 'name'
        permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]
        after1 = {'acl': permissive, 'defaultObjectAcl': []}
        after2 = {'acl': permissive, 'defaultObjectAcl': permissive}
        if default_object_acl_loaded:
            num_requests = 2
            connection = _Connection(after1, after2)
        else:
            num_requests = 3
            # We return the same value for default_object_acl.reload()
            # to consume.
            connection = _Connection(after1, after1, after2)
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.acl.loaded = True
        bucket.default_object_acl.loaded = default_object_acl_loaded
        bucket.make_public(future=True)
        self.assertEqual(list(bucket.acl), permissive)
        self.assertEqual(list(bucket.default_object_acl), permissive)
        kw = connection._requested
        self.assertEqual(len(kw), num_requests)
        self.assertEqual(kw[0]['method'], 'PATCH')
        self.assertEqual(kw[0]['path'], '/b/%s' % NAME)
        self.assertEqual(kw[0]['data'], {'acl': permissive})
        self.assertEqual(kw[0]['query_params'], {'projection': 'full'})
        if not default_object_acl_loaded:
            self.assertEqual(kw[1]['method'], 'GET')
            self.assertEqual(kw[1]['path'], '/b/%s/defaultObjectAcl' % NAME)
        # Last could be 1 or 2 depending on `default_object_acl_loaded`.
        self.assertEqual(kw[-1]['method'], 'PATCH')
        self.assertEqual(kw[-1]['path'], '/b/%s' % NAME)
        self.assertEqual(kw[-1]['data'], {'defaultObjectAcl': permissive})
        self.assertEqual(kw[-1]['query_params'], {'projection': 'full'})

    def test_make_public_w_future(self):
        self._make_public_w_future_helper(default_object_acl_loaded=True)

    def test_make_public_w_future_reload_default(self):
        self._make_public_w_future_helper(default_object_acl_loaded=False)

    def test_make_public_recursive(self):
        from gcloud.storage.acl import _ACLEntity
        from gcloud.storage.bucket import _BlobIterator
        _saved = []

        class _Blob(object):
            _granted = False

            def __init__(self, bucket, name):
                self._bucket = bucket
                self._name = name

            @property
            def acl(self):
                return self

            # Faux ACL methods
            def all(self):
                return self

            def grant_read(self):
                self._granted = True

            def save(self, client=None):
                _saved.append(
                    (self._bucket, self._name, self._granted, client))

        class _Iterator(_BlobIterator):
            def get_items_from_response(self, response):
                for item in response.get('items', []):
                    yield _Blob(self.bucket, item['name'])

        NAME = 'name'
        BLOB_NAME = 'blob-name'
        permissive = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]
        after = {'acl': permissive, 'defaultObjectAcl': []}
        connection = _Connection(after, {'items': [{'name': BLOB_NAME}]})
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.acl.loaded = True
        bucket.default_object_acl.loaded = True
        bucket._iterator_class = _Iterator
        bucket.make_public(recursive=True)
        self.assertEqual(list(bucket.acl), permissive)
        self.assertEqual(list(bucket.default_object_acl), [])
        self.assertEqual(_saved, [(bucket, BLOB_NAME, True, None)])
        kw = connection._requested
        self.assertEqual(len(kw), 2)
        self.assertEqual(kw[0]['method'], 'PATCH')
        self.assertEqual(kw[0]['path'], '/b/%s' % NAME)
        self.assertEqual(kw[0]['data'], {'acl': permissive})
        self.assertEqual(kw[0]['query_params'], {'projection': 'full'})
        self.assertEqual(kw[1]['method'], 'GET')
        self.assertEqual(kw[1]['path'], '/b/%s/o' % NAME)
        max_results = bucket._MAX_OBJECTS_FOR_ITERATION + 1
        self.assertEqual(kw[1]['query_params'],
                         {'maxResults': max_results, 'projection': 'full'})

    def test_make_public_recursive_too_many(self):
        from gcloud.storage.acl import _ACLEntity

        PERMISSIVE = [{'entity': 'allUsers', 'role': _ACLEntity.READER_ROLE}]
        AFTER = {'acl': PERMISSIVE, 'defaultObjectAcl': []}

        NAME = 'name'
        BLOB_NAME1 = 'blob-name1'
        BLOB_NAME2 = 'blob-name2'
        GET_BLOBS_RESP = {
            'items': [
                {'name': BLOB_NAME1},
                {'name': BLOB_NAME2},
            ],
        }
        connection = _Connection(AFTER, GET_BLOBS_RESP)
        client = _Client(connection)
        bucket = self._makeOne(client=client, name=NAME)
        bucket.acl.loaded = True
        bucket.default_object_acl.loaded = True

        # Make the Bucket refuse to make_public with 2 objects.
        bucket._MAX_OBJECTS_FOR_ITERATION = 1
        self.assertRaises(ValueError, bucket.make_public, recursive=True)

class _Connection(object):
    _delete_bucket = False

    def __init__(self, *responses):
        self._responses = responses
        self._requested = []
        self._deleted_buckets = []

    @staticmethod
    def _is_bucket_path(path):
        if not path.startswith('/b/'):  # pragma: NO COVER
            return False
        # Now just ensure the path only has /b/ and one more segment.
        return path.count('/') == 2

    def api_request(self, **kw):
        from gcloud.exceptions import NotFound
        self._requested.append(kw)

        method = kw.get('method')
        path = kw.get('path', '')
        if method == 'DELETE' and self._is_bucket_path(path):
            self._deleted_buckets.append(kw)
            if self._delete_bucket:
                return
            else:
                raise NotFound('miss')

        try:
            response, self._responses = self._responses[0], self._responses[1:]
        except:
            raise NotFound('miss')
        else:
            return response

class _Bucket(object):
    path = '/b/name'
    name = 'name'

    def __init__(self, client=None):
        self.client = client

class _Client(object):

    def __init__(self, connection, project=None):
        self.connection = connection
        self.project = project


text:
<?php

declare(strict_types=1);

namespace Ray\Compiler;

use PHPUnit\Framework\TestCase;
use Ray\Aop\WeavedInterface;
use Ray\Di\Exception\Unbound;
use Ray\Di\InjectorInterface;
use Ray\Di\NullModule;

use function assert;
use function count;
use function glob;
use function is_object;
use function property_exists;
use function serialize;
use function spl_object_hash;
use function unserialize;

class ScriptInjectorTest extends TestCase
{
    /** @var ScriptInjector */
    private $injector;

    protected function setUp(): void
    {
        deleteFiles(__DIR__ . '/tmp');
        $this->injector = new ScriptInjector(__DIR__ . '/tmp');
    }

    public function testGetInstance(): FakeCar
    {
        $diCompiler = new DiCompiler(new FakeCarModule(), __DIR__ . '/tmp');
        $diCompiler->compile();
        /** @var FakeCar $car */
        $car = $this->injector->getInstance(FakeCarInterface::class);
        $this->assertInstanceOf(FakeCar::class, $car);

        return $car;
    }

    /**
     * @depends testGetInstance
     */
    public function testDefaultValueInjected(FakeCar $car): void
    {
        $this->assertNull($car->null);
    }

    public function testCompileException(): void
    {
        $this->expectException(Unbound::class);
        $script = new ScriptInjector(__DIR__ . '/tmp');
        $script->getInstance('invalid-class'); // @phpstan-ignore-line
    }

    public function testToPrototype(): void
    {
        (new DiCompiler(new FakeToBindPrototypeModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        assert(is_object($instance1) && is_object($instance2));
        $this->assertNotSame(spl_object_hash($instance1), spl_object_hash($instance2));
    }

    public function testToSingleton(): void
    {
        (new DiCompiler(new FakeToBindSingletonModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        $this->assertSame($instance1, $instance2);
    }

    public function testToProviderPrototype(): void
    {
        (new DiCompiler(new FakeToProviderPrototypeModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        $this->assertNotSame($instance1, $instance2);
    }

    public function testToProviderSingleton(): void
    {
        (new DiCompiler(new FakeToProviderSingletonModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        $this->assertSame($instance1, $instance2);
    }

    public function testToInstancePrototype(): void
    {
        (new DiCompiler(new FakeToInstancePrototypeModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        $this->assertNotSame($instance1, $instance2);
    }

    public function testToInstanceSingleton(): void
    {
        (new DiCompiler(new FakeToInstanceSingletonModule(), __DIR__ . '/tmp'))->compile();
        $instance1 = $this->injector->getInstance(FakeRobotInterface::class);
        $instance2 = $this->injector->getInstance(FakeRobotInterface::class);
        $this->assertSame($instance1, $instance2);
    }

    public function testSerializable(): void
    {
        $diCompiler = new DiCompiler(new FakeCarModule(), __DIR__ . '/tmp');
        $diCompiler->compile();
        $injector = unserialize(serialize($this->injector));
        assert($injector instanceof InjectorInterface);
        $car = $injector->getInstance(FakeCarInterface::class);
        $this->assertInstanceOf(ScriptInjector::class, $injector);
        $this->assertInstanceOf(FakeCar::class, $car);
    }

    public function testAop(): void
    {
        $compiler = new DiCompiler(new FakeCarModule(), __DIR__ . '/tmp');
        $compiler->compile();
        $injector = new ScriptInjector(__DIR__ . '/tmp');
        $instance1 = $injector->getInstance(FakeCarInterface::class);
        $instance2 = $injector->getInstance(FakeCar::class);
        $instance3 = $injector->getInstance(FakeCar2::class);
        assert($instance3 instanceof FakeCar2);
        $this->assertInstanceOf(WeavedInterface::class, $instance1);
        $this->assertInstanceOf(WeavedInterface::class, $instance2);
        $this->assertInstanceOf(WeavedInterface::class, $instance3);
        $this->assertInstanceOf(FakeRobot::class, $instance3->robot);
    }

    public function testOnDemandSingleton(): void
    {
        (new DiCompiler(new FakeToBindSingletonModule(), __DIR__ . '/tmp'))->compile();
        $dependSingleton1 = $this->injector->getInstance(FakeDependSingleton::class);
        assert($dependSingleton1 instanceof FakeDependSingleton);
        $dependSingleton2 = $this->injector->getInstance(FakeDependSingleton::class);
        assert($dependSingleton2 instanceof FakeDependSingleton);
        $hash1 = spl_object_hash($dependSingleton1->robot);
        $hash2 = spl_object_hash($dependSingleton2->robot);
        $this->assertSame($hash1, $hash2);
    }

    public function testOnDemandPrototype(): void
    {
        (new DiCompiler(new FakeCarModule(), __DIR__ . '/tmp'))->compile();
        $fakeDependPrototype1 = $this->injector->getInstance(FakeDependPrototype::class);
        assert($fakeDependPrototype1 instanceof FakeDependPrototype);
        $fakeDependPrototype2 = $this->injector->getInstance(FakeDependPrototype::class);
        assert($fakeDependPrototype2 instanceof FakeDependPrototype);
        $hash1 = spl_object_hash($fakeDependPrototype1->car);
        $hash2 = spl_object_hash($fakeDependPrototype2->car);
        $this->assertNotSame($hash1, $hash2);
    }

    public function testOptional(): void
    {
        $optional = $this->injector->getInstance(FakeOptional::class);
        assert($optional instanceof FakeOptional);
        $this->assertNull($optional->robot);
    }

    public function testDependInjector(): void
    {
        $diCompiler = new DiCompiler(new NullModule(), __DIR__ . '/tmp');
        $diCompiler->compile();
        /** @var FakeFactory $factory */
        $factory = $diCompiler->getInstance(FakeFactory::class);
        assert(property_exists($factory, 'injector'));
        $this->assertInstanceOf(InjectorInterface::class, $factory->injector);
        $injector = new ScriptInjector(__DIR__ . '/tmp');
        /** @var FakeFactory $factory */
        $factory = $injector->getInstance(FakeFactory::class);
        $this->assertInstanceOf(InjectorInterface::class, $factory->injector);
    }

    public function testUnbound(): void
    {
        $this->expectException(Unbound::class);
        $this->expectExceptionMessage('NOCLASS-NONAME');
        $injector = new ScriptInjector(__DIR__ . '/tmp');
        $injector->getInstance('NOCLASS', 'NONAME'); // @phpstan-ignore-line
    }

    public function testCompileOnDemand(): void
    {
        $injector = new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeCarModule();
            }
        );
        $car = $injector->getInstance(FakeCar::class);
        $this->assertTrue($car instanceof FakeCar);
    }

    public function testCompileOnDemandAop(): void
    {
        $injector = new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeAopModule();
            }
        );
        $aop = $injector->getInstance(FakeAopInterface::class);
        assert($aop instanceof FakeAopInterface);
        $result = $aop->returnSame(1);
        $this->assertSame(2, $result);
    }

    public function testCompileOnDemandSerialize(): void
    {
        $serialize = serialize(new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeCarModule();
            }
        ));
        $injector = unserialize($serialize);
        assert($injector instanceof InjectorInterface);
        $car = $injector->getInstance(FakeCar::class);
        $this->assertTrue($car instanceof FakeCar);
    }

    public function testCompileOnDemandAopSerialize(): void
    {
        $injector = unserialize(serialize(new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeAopModule();
            }
        )));
        assert($injector instanceof ScriptInjector);
        /** @var FakeAopInterface $aop */
        $aop = $injector->getInstance(FakeAopInterface::class);
        $result = $aop->returnSame(1);
        $this->assertSame(2, $result);
    }

    public function testClear(): void
    {
        $injector = new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeCarModule();
            }
        );
        $injector->getInstance(FakeCar::class);
        $count = count((array) glob(__DIR__ . '/tmp/*.php'));
        $this->assertGreaterThan(1, $count);
        $injector->clear();
        $countAfterClear = count((array) glob(__DIR__ . '/tmp/*.php'));
        $this->assertSame(0, $countAfterClear);
    }

    public function testNullObjectCompile(): ScriptInjector
    {
        $injector = new ScriptInjector(
            __DIR__ . '/tmp',
            static function () {
                return new FakeNullObjectModule();
            }
        );
        $instance = $injector->getInstance(FakeTyreInterface::class);
        $this->assertInstanceOf(FakeTyreInterface::class, $instance);

        return $injector;
    }

    /**
     * @runTestsInSeparateProcesses
     * @depends testNullObjectCompile
     */
    public function testNullObjectCompileCodeRead(ScriptInjector $injector): void
    {
        $instance = $injector->getInstance(FakeTyreInterface::class);
        $this->assertInstanceOf(FakeTyreInterface::class, $instance);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * BuddyPress Admin Slug Functions
 *
 * @package BuddyPress
 * @subpackage CoreAdministration
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

/**
 * Renders the page mapping admin panel.
 *
 * @since BuddyPress (1.6)
 * @todo Use settings API
 * @uses bp_core_admin_component_options()
 */
function bp_core_admin_slugs_settings() {
?>

		<?php screen_icon( 'buddypress'); ?>

<?php bp_core_admin_tabs( __( 'Pages', 'buddypress' ) ); ?>

		<form action="" method="post" id="bp-admin-page-form">

			<?php bp_core_admin_slugs_options(); ?>

				<input class="button-primary" type="submit" name="bp-admin-pages-submit" id="bp-admin-pages-submit" value="<?php esc_attr_e( 'Save Settings', 'buddypress' ) ?>"/>

			<?php wp_nonce_field( 'bp-admin-pages-setup' ); ?>

		</form>

<?php
}

/**
 * Creates reusable markup for page setup on the Components and Pages dashboard panel.
 *
 * @package BuddyPress
 * @since BuddyPress (1.6)
 * @todo Use settings API
 */
function bp_core_admin_slugs_options() {
	global $bp;

	// Get the existing WP pages
	$existing_pages = bp_core_get_directory_page_ids();

	// Set up an array of components (along with component names) that have
	// directory pages.
	$directory_pages = array();

	// Loop through loaded components and collect directories
	if ( is_array( $bp->loaded_components ) ) {
		foreach( $bp->loaded_components as $component_slug => $component_id ) {

			// Only components that need directories should be listed here
			if ( isset( $bp->{$component_id} ) && !empty( $bp->{$component_id}->has_directory ) ) {

				// component->name was introduced in BP 1.5, so we must provide a fallback
				$directory_pages[$component_id] = !empty( $bp->{$component_id}->name ) ? $bp->{$component_id}->name : ucwords( $component_id );
			}
		}
	}

	/** Directory Display *****************************************************/

	$directory_pages = apply_filters( 'bp_directory_pages', $directory_pages );

	if ( !empty( $directory_pages ) ) : ?>

<?php _e( 'Directories', 'buddypress' ); ?>

<?php _e( 'Associate a WordPress Page with each BuddyPress component directory.', 'buddypress' ); ?>

				<?php foreach ( $directory_pages as $name => $label ) : ?>

							<label for="bp_pages[<?php echo esc_attr( $name ) ?>]"><?php echo esc_html( $label ) ?>

							<?php if ( ! bp_is_root_blog() ) switch_to_blog( bp_get_root_blog_id() ); ?>

							<?php echo wp_dropdown_pages( array(
								'name'             => 'bp_pages[' . esc_attr( $name ) . ']',
								'echo'             => false,
								'show_option_none' => __( '- None -', 'buddypress' ),
								'selected'         => !empty( $existing_pages[$name] ) ? $existing_pages[$name] : false
							) ); ?>

							<?php if ( !empty( $existing_pages[$name] ) ) : ?>

								<a href="<?php echo get_permalink( $existing_pages[$name] ); ?>" class="button-secondary" target="_bp"><?php _e( 'View', 'buddypress' ); ?>

							<?php endif; ?>

							<?php if ( ! bp_is_root_blog() ) restore_current_blog(); ?>

				<?php endforeach ?>

				<?php do_action( 'bp_active_external_directories' ); ?>

	<?php

	endif;

	/** Static Display ********************************************************/

	// Static pages
	$static_pages = array(
		'register' => __( 'Register', 'buddypress' ),
		'activate' => __( 'Activate', 'buddypress' ),
	);

	$static_pages = apply_filters( 'bp_static_pages', $static_pages );

	if ( !empty( $static_pages ) ) : ?>

<?php _e( 'Registration', 'buddypress' ); ?>

<?php _e( 'Associate WordPress Pages with the following BuddyPress Registration pages.', 'buddypress' ); ?>

				<?php foreach ( $static_pages as $name => $label ) : ?>

							<label for="bp_pages[<?php echo esc_attr( $name ) ?>]"><?php echo esc_html( $label ) ?>

							<?php if ( ! bp_is_root_blog() ) switch_to_blog( bp_get_root_blog_id() ); ?>

							<?php echo wp_dropdown_pages( array(
								'name'             => 'bp_pages[' . esc_attr( $name ) . ']',
								'echo'             => false,
								'show_option_none' => __( '- None -', 'buddypress' ),
								'selected'         => !empty( $existing_pages[$name] ) ? $existing_pages[$name] : false
							) ) ?>

							<?php if ( !empty( $existing_pages[$name] ) ) : ?>

								<a href="<?php echo get_permalink( $existing_pages[$name] ); ?>" class="button-secondary" target="_bp"><?php _e( 'View', 'buddypress' ); ?>

							<?php endif; ?>

							<?php if ( ! bp_is_root_blog() ) restore_current_blog(); ?>

				<?php endforeach ?>

				<?php do_action( 'bp_active_external_pages' ); ?>

		<?php
	endif;
}

/**
 * Handle saving of the BuddyPress slugs
 *
 * @since BuddyPress (1.6)
 * @todo Use settings API
 */
function bp_core_admin_slugs_setup_handler() {

	if ( isset( $_POST['bp-admin-pages-submit'] ) ) {
		if ( !check_admin_referer( 'bp-admin-pages-setup' ) )
			return false;

		// Then, update the directory pages
		if ( isset( $_POST['bp_pages'] ) ) {

			$directory_pages = array();

			foreach ( (array) $_POST['bp_pages'] as $key => $value ) {
				if ( !empty( $value ) ) {
					$directory_pages[$key] = (int) $value;
				}
			}
			bp_core_update_directory_page_ids( $directory_pages );
		}

		$base_url = bp_get_admin_url( add_query_arg( array( 'page' => 'bp-page-settings', 'updated' => 'true' ), 'admin.php' ) );

		wp_redirect( $base_url );
	}
}
add_action( 'bp_admin_init', 'bp_core_admin_slugs_setup_handler' );


text:
import java.util.Arrays;

public class Main {
  boolean find(String[][] data) {
      // Comment
      return Arrays.stream(data).flatMap(Arrays::stream).allMatch(str -> str.startsWith("xyz"));
  }
}


text:
Doc.Title=THE PARIS DECLARATION

0.sec=OPPORTUNITY FOR BOTTOM-UP ACTION IN FAVOUR OF THE LOW CARBON ECONOMY
Commitments for Action

1.Ti=SUB-NATIONAL GOVERNMENTS

1.0.sec=We, the representatives of the Federated States, Regions and Cities, being close to our citizens and our partners, companies and investors, as well as think tanks involved in the operational implementation of sustainable development, commit to take the following measures:

1.1.Ti=1st Commitment:

1.1.sec=Commit to adopt, support and engage in concrete «bottom-up» lead by local authorities in partnership with businesses and investors, to complement the efforts of Parties in the framework of the intergovernmental negotiation process of the UNFCCC, to reach a global Climate Agreement in Paris in 2015.

1.2.Ti=2nd Commitment:

1.2.sec=Commit to take concretemeasures to fightagainst global warmingwithin such actionprograms,each accordingto our respectivelocal conditions, and taking as an example the objectives (of the European Union and UNSE4ALL for the year 2030: reduction of GHG emissions by 40%, increasing energy efficiency by 40% and increasing renewable energy production by 40%,based on 1990 data).

1.3.Ti=3rd Commitment:

1.3.sec=Commit to extend our action programs to the international community and, where appropriate, to all stakeholders qualified to contribute to enhance the capacity building for local and sub-national governments in all countries, for effective implementation of low carbon infrastructure projects, in particular through Public Private Partnerships (PPP) at the local level, and through training for local decision makers and technical staff on the ground.

1.4.Ti=4th Commitment:

1.4.0.sec=Encourage and support stepping up the efforts made to build financing mechanisms specifically designed to ensure the value chain in delivering bankable low carbon projects for sub-national governments.Such financial schemes will aim at unleashing access to:

1.4.1.sec=Public funding, including pre-investment facilities to cover the costs of feasibility studies (sources of funding will include UN and bilateral agencies,development banks) and public debt funding (national banks,pension funds); and

1.4.2.sec=Private financing,including private equity investors,private investors,sovereign funds and pension funds.

1.5.Ti=5th Commitment:

1.5.sec=Commit to interregional cooperation programs to facilitate the implementation of actions to effectively reduce greenhouse gas emissions (GHGs), increase renewable energy generation, and adopt energy efficiency and energy security measures in all regions of the world, and also through sharing ideas and best practices and direct participation in the valuation of carbon credit exchange.

1.6.Ti=6th Commitment:

1.6.sec=Commit to publicly report and disclose GHG reduction efforts and possibly other local climate actions implemented at the local level in all regions of the world through recognized subnational reporting platforms. In addition, we commit to climate change metrics and benchmarking performance across regions.

1.7.Ti=7th Commitment:

1.7.sec=Mobilize all stakeholders (national,local,private) around projects that build the capacities of young people,as well as on specific training courses leadingtogreenjobs;contribute,throughthis,tothetransitiontothegreeneconomyasanewgrowthmodel,withtransformedproductionpatterns, requiring additional human resources,specific to different areas of sustainable development.

1.=[Z/ol-none/7]

2.Ti=BUSINESS AND FINANCE SECTOR

2.0.sec=We, the representatives of Business and Finance, working closely with Federated States, Regions and Cities as well as think tanks, involved in the operational implementation of sustainable development, commit to take the following measures:

2.1.Ti=1st Commitment:

2.1.sec=Promote, support and engage in a «bottom-up» approach through joint action by local and regional authorities, businesses and investors, in order to complement the efforts of Parties in the framework of the intergovernmental negotiation process of the UNFCCC, to reach a global Climate Agreement in Paris in 2015.

2.2.Ti=2nd Commitment:

2.2.sec=Commit to take concrete measures to fight against global warming, each according to our respective local conditions, working with resource efficiencymeasures,measurestointroducecleanerenergysources,andmeasurestointroducelow-carbonthinking,productandprocessinnovation.

2.3.Ti=3rd Commitment:

2.3.sec=Invest in the development of international capacity building and widely applicable - and useable - solutions for national, sub-national and local governments, for businesses, and for the community at large, to facilitate their implementation of actions and projects to fight against global warming.

2.4.Ti=4th Commitment:

2.4.sec=Support and develop new and innovative financing schemes with the whole finance sector to help: unlock the necessary $1000bn/year to invest in projects to fight climate change, including working with, private investors, sovereign funds and pension funds, private equity and other asset managers; and including the strong collaboration with necessary public funds.

2.5.Ti=5th Commitment:

2.5.sec=Develop our capacity to engage in Public Private Partnership projects to implement solutions for fighting climate change and to support sub-national and local governments, as well as partners within the private and third sector also, to develop their capacity and understanding to create, develop and enhance the implementation of such projects.

2.6.Ti=6th Commitment:

2.6.sec=Commit to publicly report and disclose GHG reduction efforts implemented in the business and finance sector in all regions of the world.

2.=[Z/ol-none/6]

90.Ti=THE ROAD TO PARIS 2015

90.1.0.sec=We, the representatives of the Federated States, Regions and Cities, Companies and Investors, as well as think tanks participating in the World Summit of Regions for Climate (and further events such as the World Climate Summit and the World Green Economy Summit):

90.1.1.sec=Urge that this Declaration is taken into account in the deliberations and results of the Conference of the Parties COP 20, Lima, November 2014 and in the Conference of the Parties COP 21, Paris, December 2015.

90.1.2.sec=Assure the impact and influence of our commitments through our active presence at the COP 20 and COP 21 meetings, in correspondence with the UNFCCC, through direct exchange with the French government during its preparation of the COP 21 meeting, at the World Green Economy Summit 2015, at other events, and finally through the support of sub-national governments business, and civil society in their exchange with their national governments to assure the integration of our commitments in their respective countries' COP agendas.

90.1.=[Z/ol-none/s2]

90.=[Z/ol-none/1]

DocBody={Doc}

=[Z/ol/2]


text:
package com.github.ryanbrainard.richobjects.api.client;

import com.force.api.*;
import com.github.ryanbrainard.richsobjects.api.client.SfdcApiClient;
import com.github.ryanbrainard.richsobjects.api.client.SfdcApiClientProvider;
import com.github.ryanbrainard.richsobjects.api.model.*;
import com.github.ryanbrainard.richsobjects.api.model.QueryResult;

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

/**
 * @author Ryan Brainard
 */
@SuppressWarnings("UnusedDeclaration")
public class ForceApiProvider implements SfdcApiClientProvider {

    @Override
    public SfdcApiClient get(final String accessToken, final String apiEndpoint, /*TODO*/ final String version) {
        return new SfdcApiClient() {

            private final ForceApi api = new ForceApi(new ApiSession()
                    .setAccessToken(accessToken)
                    .setApiEndpoint(apiEndpoint));

            @Override
            public GlobalDescription describeGlobal() {
                return new GlobalDescription() {

                    private final DescribeGlobal srcDescribeGlobal = api.describeGlobal();

                    @Override
                    public String getEncoding() {
                        return srcDescribeGlobal.getEncoding();
                    }

                    @Override
                    public Integer getMaxBatchSize() {
                        return srcDescribeGlobal.getMaxBatchSize();
                    }

                    @Override
                    public List<BasicSObjectDescription> getSObjects() {
                        final List<DescribeSObjectBasic> srcDescs = api.describeGlobal().getSObjects();
                        final List<BasicSObjectDescription> targetDescs = new ArrayList<BasicSObjectDescription>(srcDescs.size());
                        for (final DescribeSObjectBasic d : srcDescs) {
                            targetDescs.add(toBasicSObjectDescription(d));
                        }
                        return targetDescs;
                    }
                };
            }

            @Override
            public BasicSObjectInformation describeSObjectBasic(String type) {
                final DiscoverSObject<Map> disc = api.discoverSObject(type, Map.class);

                return new BasicSObjectInformation() {
                    @Override
                    public BasicSObjectDescription getBasicObjectDescribe() {
                        return toBasicSObjectDescription(disc.getObjectDescribe());
                    }

                    @Override
                    public List<Map<String, ?>> getRecentItems() {
                        return listDeepCast(disc.getRecentItems());
                    }
                };
            }

            @Override
            public SObjectDescription describeSObject(String type) {
                return toSObjectDescription(api.describeSObject(type));
            }

            @Override
            public String createSObject(String type, Map<String, ?> record) {
                return api.createSObject(type, record);
            }

            @Override
            public void updateSObject(String type, String id, Map<String, ?> record) {
                api.updateSObject(type, id, record);
            }

            @Override
            public void deleteSObject(String type, String id) {
                api.deleteSObject(type, id);
            }

            @Override
            public Map<String, ?> getSObject(String type, String id) {
                //noinspection unchecked
                return (Map<String, ?>) api.getSObject(type, id).asMap();
            }

            @Override
            public QueryResult query(String soql) {
                return toQueryResult(api.query(soql));
            }

            @Override
            public QueryResult queryMore(String nextRecordsUrl) {
                return toQueryResult(api.queryMore(nextRecordsUrl));
            }

            @Override
            public String getRawBase64Content(String contentUrl) {
                throw new UnsupportedOperationException();
            }
        };
    }

    protected static QueryResult toQueryResult(final com.force.api.QueryResult<Map> srcQueryResult) {
        return new QueryResult() {
            @Override
            public int getTotalSize() {
                return srcQueryResult.getTotalSize();
            }

            @Override
            public boolean isDone() {
                return srcQueryResult.isDone();
            }

            @Override
            public List<Map<String, ?>> getRecords() {
                return listDeepCast(srcQueryResult.getRecords());
            }

            @Override
            public String getNextRecordsUrl() {
                return srcQueryResult.getNextRecordsUrl();
            }
        };
    }

    private static <S,T> List<T> listDeepCast(List<S> srcRecords) {
        final List<T> tgtRecords = new ArrayList<T>(srcRecords.size());
        for (S record : srcRecords) {
            //noinspection unchecked
            tgtRecords.add((T) record);
        }
        return tgtRecords;
    }

    protected static BasicSObjectDescription toBasicSObjectDescription(final DescribeSObjectBasic src) {
        return _toSObjectDescription(src, null, null);
    }

    protected static SObjectDescription toSObjectDescription(final DescribeSObject src) {
        return _toSObjectDescription(src, src.getFields(), src.getChildRelationships());
    }

    private static SObjectDescription _toSObjectDescription(final DescribeSObjectBasic basic,
                                                            final List<DescribeSObject.Field> fields,
                                                            final List<DescribeSObject.ChildEntity> childRelationships) {
        return new SObjectDescription() {
            public String getName() {
                return basic.getName();
            }

            @Override
            public String getLabel() {
                return basic.getLabel();
            }

            @Override
            public Boolean isCustom() {
                return basic.isCustom();
            }

            @Override
            public String getKeyPrefix() {
                return basic.getKeyPrefix();
            }

            @Override
            public String getLabelPlural() {
                return basic.getLabelPlural();
            }

            @Override
            public Boolean isLayoutable() {
                return basic.isLayoutable();
            }

            @Override
            public Boolean isActivateable() {
                return basic.isActivateable();
            }

            @Override
            public Boolean isUpdateable() {
                return basic.isUpdateable();
            }

            @Override
            public Map<String, String> getUrls() {
                return basic.getUrls();
            }

            @Override
            public Boolean isCreateable() {
                return basic.isCreateable();
            }

            @Override
            public Boolean isDeletable() {
                return basic.isDeletable();
            }

            @Override
            public Boolean isFeedEnabled() {
                return basic.isFeedEnabled();
            }

            @Override
            public Boolean isQueryable() {
                return basic.isQueryable();
            }

            @Override
            public Boolean isReplicateable() {
                return basic.isReplicateable();
            }

            @Override
            public Boolean isRetrieveable() {
                return basic.isRetrieveable();
            }

            @Override
            public Boolean isUndeletable() {
                return basic.isUndeletable();
            }

            @Override
            public Boolean isTriggerable() {
                return basic.isTriggerable();
            }

            @Override
            public Boolean isMergeable() {
                return basic.isMergeable();
            }

            @Override
            public Boolean isDeprecatedAndHidden() {
                return basic.isDeprecatedAndHidden();
            }

            @Override
            public Boolean isCustomSetting() {
                return basic.isCustomSetting();
            }

            @Override
            public Boolean isSearchable() {
                return basic.isSearchable();
            }

            @Override
            public List<Field> getFields() {
                if (fields == null) {
                    return null;
                }

                final List<Field> fs = new ArrayList<Field>(fields.size());
                for (final DescribeSObject.Field f : fields) {
                    fs.add(new Field() {
                        public Integer getLength() {
                            return f.getLength();
                        }

                        public String getName() {
                            return f.getName();
                        }

                        public String getType() {
                            return f.getType();
                        }

                        public String getSoapType() {
                            return f.getSoapType();
                        }

                        public String getDefaultValue() {
                            return f.getDefaultValue();
                        }

                        public String getLabel() {
                            return f.getLabel();
                        }

                        public Boolean isUpdateable() {
                            return f.isUpdateable();
                        }

                        public Boolean isCalculated() {
                            return f.isCalculated();
                        }

                        public Boolean isUnique() {
                            return f.isUnique();
                        }

                        public Boolean isNillable() {
                            return f.isNillable();
                        }

                        public Boolean isCaseSensitive() {
                            return f.isCaseSensitive();
                        }

                        public String getInlineHelpText() {
                            return f.getInlineHelpText();
                        }

                        public Boolean isNameField() {
                            return f.isNameField();
                        }

                        public Boolean isExternalId() {
                            return f.isExternalId();
                        }

                        public Boolean isIdLookup() {
                            return f.isIdLookup();
                        }

                        public Boolean isFilterable() {
                            return f.isFilterable();
                        }

                        public Boolean isCreateable() {
                            return f.isCreateable();
                        }

                        public Boolean isDeprecatedAndHidden() {
                            return f.isDeprecatedAndHidden();
                        }

                        public Boolean isAutoNumber() {
                            return f.isAutoNumber();
                        }

                        public Boolean isDefaultedOnCreate() {
                            return f.isDefaultedOnCreate();
                        }

                        public Boolean isGroupable() {
                            return f.isGroupable();
                        }

                        public String getRelationshipName() {
                            return f.getRelationshipName();
                        }

                        public List<String> getReferenceTo() {
                            return f.getReferenceToEntity();
                        }

                        public Boolean isRestrictedPicklist() {
                            return f.isRestrictedPicklist();
                        }

                        public Boolean isNamePointing() {
                            return f.isNamePointing();
                        }

                        public Boolean isCustom() {
                            return f.isCustom();
                        }

                        public Boolean isHtmlFormatted() {
                            return f.isHtmlFormatted();
                        }

                        public Boolean isDependentPicklist() {
                            return f.isDependentPicklist();
                        }

                        public Boolean isWriteRequiresMasterRead() {
                            return f.isWriteRequiresMasterRead();
                        }

                        public Boolean isSortable() {
                            return f.isSortable();
                        }
                    });
                }

                return fs;
            }

            @Override
            public List<ChildEntity> getChildRelationships() {
                if (childRelationships == null) {
                    return null;
                }

                List<ChildEntity> ces = new ArrayList<ChildEntity>(childRelationships.size());
                for (final DescribeSObject.ChildEntity ce : childRelationships) {
                    ces.add(new ChildEntity() {
                        public String getField() {
                            return ce.getField();
                        }

                        public String getChildSObject() {
                            return ce.getChildSObject();
                        }

                        public String getRelationshipName() {
                            return ce.getRelationshipName();
                        }

                        public Boolean isDeprecatedAndHidden() {
                            return ce.isDeprecatedAndHidden();
                        }

                        public Boolean isCascadeDelete() {
                            return ce.isCascadeDelete();
                        }
                    });
                }

                return ces;
            }
        };
    }
}


text:
import { ISPPageContext, ISPListContext, ITabContext, TabContextCollection } from './interfaces';
import { CommandStore } from './commands/commandCollection';
import { LauncherPanel } from './launcherPanel';

var Tabs : FFTabs = require('sdk/tabs');

class Extension {
	private _modifier: string;
	private _panel: LauncherPanel;
	private _tabContext: TabContextCollection;
	private _commands: CommandStore;

	private get currentContext(): ITabContext {
		return this._tabContext[Tabs.activeTab.id];
	}

	private get currentUrl(): string {
		return Tabs.activeTab.url;
	}

	constructor() {
		this._modifier = '';
		this._tabContext = {};
		this._commands = new CommandStore();
		this._panel = new LauncherPanel();
		this._panel.on('text-entered', (text: string) => this.onTextEntered(text));
		this._panel.on('text-changed', (text: string) => this.onTextChanged(text));

		Tabs.on('ready', (tab: FFTab) => this.onTabReady(tab));
	}

	private onTabReady(tab: FFTab) {
		let worker = tab.attach({
			contentScriptFile: './context.js',
			contentScriptOptions: { tabId: tab.id }
		});

		worker.port.on('context-ready', (context : ITabContext) => this.onContextReady(context));
		worker.port.emit('load-context');
	}

	private onContextReady(context: ITabContext) {
		this._tabContext[context.tabId] = context;
	}

	private onTextEntered(commandText: string) {
		let command = this._commands.getCommand(commandText);

		if (typeof (command) != 'undefined') {
			this._modifier = command.execute(this.currentContext, this._modifier);
			this._panel.emit('modifier-ready', this._modifier);
		}
		if (!this._modifier) {
			this._panel.toggle();
		}
	}

	private onTextChanged(text: string) {
		let context = this.currentContext;
		if (typeof(context) != 'undefined') {
			var commands = this._commands.getSuggestions(text, context, this.currentUrl);
			this._panel.emit('suggestions-ready', commands);
		}
	}

	private getScopeUrl(scope: string, context: ITabContext) {
		if (scope.toLowerCase() == 'web') {
			return context.spPageContextInfo.webAbsoluteUrl;
		}

		if (scope.toLowerCase() == 'site') {
			return context.spPageContextInfo.siteAbsoluteUrl;
		}

		return '';
	}
}

var extension = new Extension();


text:
const config = {
  VERSION: process.env.VERSION,
  SERVER_API_URL: process.env.SERVER_API_URL
};

export default config;

export const SERVER_API_URL = '';

export const messages = {
  DATA_CREATE_SUCCESS_ALERT: 'Data created successfully!',
  DATA_DELETE_SUCCESS_ALERT: 'Data deleted successfully!',
  DATA_UPDATE_ERROR_ALERT: 'Data deleted successfully!'
};

export const APP_DATE_FORMAT = 'DD/MM/YY HH:mm';
export const APP_LOCAL_DATE_FORMAT = 'DD/MM/YYYY';
export const APP_LOCAL_DATETIME_FORMAT = 'YYYY-M-DTh:mm';
export const APP_WHOLE_NUMBER_FORMAT = '0,0';
export const APP_TWO_DIGITS_AFTER_POINT_NUMBER_FORMAT = '0,0.[00]';


text:
from django import forms

from oscar.core.loading import get_model

class WeightBandForm(forms.ModelForm):

    def __init__(self, method, *args, **kwargs):
        super(WeightBandForm, self).__init__(*args, **kwargs)
        self.instance.method = method

    class Meta:
        model = get_model('shipping', 'WeightBand')
        fields = ('upper_limit', 'charge')


text:
const _ = require('underscore')
const {Errors: {APIError}} = require('isomorphic-core')

const IMAPHelpers = {
  async messagesForThreadByFolder(db, threadId) {
    const thread = await db.Thread.findById(threadId)
    if (!thread) {
      throw new APIError(`IMAPHelpers.messagesForThreadByFolder - Can't find thread`, 404)
    }
    const messages = await thread.getMessages()
    return _.groupBy(messages, 'folderId')
  },

  async forEachFolderOfThread({db, imap, threadMessages, callback}) {
    if (!threadMessages.every(m => m.folderImapUID != null)) {
      throw new APIError('All messages in a thread require an IMAP uid to perform an action')
    }
    const {Folder} = db
    const msgsByFolder = _.groupBy(threadMessages, 'folderId')
    const folderIds = Object.keys(msgsByFolder)
    const folders = await Folder.findAll({where: {id: folderIds}})

    for (const folder of folders) {
      const msgsInFolder = msgsByFolder[folder.id]
      if (msgsInFolder.length === 0) { continue }
      const messageImapUIDs = msgsInFolder.map(m => m.folderImapUID)
      const box = await imap.openBox(folder.name, {readOnly: false})
      await callback({folder, messages: msgsInFolder, messageImapUIDs, box})
    }
  },

  async forEachLabelSetOfMessages({messages, callback}) {
    const messagesByLabelSet = new Map()
    const labelIdentifiersByLabelSet = new Map()

    await Promise.all(messages.map(async (message) => {
      const labels = await message.getLabels()
      if (!labels || labels.length === 0) {
        return
      }
      const labelIdentifiers = labels.map(l => l.imapLabelIdentifier())
      const labelSet = (
        labelIdentifiers
        .sort((l1, l2) => {
          if (l1.toLowerCase() === l2.toLowerCase()) {
            return 0
          }
          return l1.toLowerCase() < l2.toLowerCase() ? -1 : 1
        })
        .join('')
      )
      labelIdentifiersByLabelSet.set(labelSet, labelIdentifiers)
      if (messagesByLabelSet.has(labelSet)) {
        const currentMsgs = messagesByLabelSet.get(labelSet)
        messagesByLabelSet.set(labelSet, [...currentMsgs, message])
      } else {
        messagesByLabelSet.set(labelSet, [message])
      }
    }))

    for (const [labelSet, msgs] of messagesByLabelSet) {
      const labelIdentifiers = labelIdentifiersByLabelSet.get(labelSet)
      if (labelIdentifiers.length > 0) {
        await callback({messages: msgs, labelIdentifiers})
      }
    }
  },

  async openMessageBox({messageId, db, imap}) {
    const {Message} = db
    const message = await Message.findById(messageId)
    const folder = await message.getFolder()
    if (!folder) {
      throw new Error(`IMAPHelpers.openMessageBox - message does not have a folder`)
    }
    const box = await imap.openBox(folder.name)
    return {box, message}
  },

  async setLabelsForMessages({db, box, messages, labelIds}) {
    const sentLabel = await db.Label.find({where: {role: 'sent'}});
    if (!sentLabel) {
      throw new APIError('No Sent label present')
    }
    const sentLabelIdentifier = sentLabel.imapLabelIdentifier()
    if (!labelIds || labelIds.length === 0) {
      // If labelIds is empty, we need to get each message's labels and remove
      // them, because an empty array is invalid input for `setLabels`
      return IMAPHelpers.forEachLabelSetOfMessages({
        messages,
        async callback({messages: msgs, labelIdentifiers}) {
          // We can't remove the Sent label in gmail, otherwise the operation will
          // fail silently!
          const labelsToRemove = labelIdentifiers.filter(l => l !== sentLabelIdentifier)
          if (labelsToRemove.length > 0) {
            await box.removeLabels(msgs.map(m => m.folderImapUID), labelsToRemove)
          }
        },
      })
    }

    const labelsToSet = (
      await db.Label.findAll({where: {id: labelIds}})
      .map(label => label.imapLabelIdentifier())
    )
    return IMAPHelpers.forEachLabelSetOfMessages({
      messages,
      async callback({messages: msgs, labelIdentifiers}) {
        const msgLabelsContainSent = labelIdentifiers.find(l => l === sentLabelIdentifier)
        const labelsToSetContainSent = labelsToSet.find(l => l === sentLabelIdentifier)

        let actualLabelsToSet = [...labelsToSet]
        if (!msgLabelsContainSent && labelsToSetContainSent) {
          // We can't try to add the Sent label in gmail, otherwise the operation will
          // fail silently!
          actualLabelsToSet = actualLabelsToSet.filter(l => l !== sentLabelIdentifier)
        }
        if (msgLabelsContainSent && !labelsToSetContainSent) {
          // If we reach this condition, it means that we want to add
          // labelsToSet, but we cant overwrite the Sent label, so we just add it to the
          // labelsToSet
          actualLabelsToSet.push(sentLabel.imapLabelIdentifier())
        }

        if (actualLabelsToSet.length > 0) {
          await box.setLabels(msgs.map(m => m.folderImapUID), actualLabelsToSet)
        }
      },
    })
  },
}
module.exports = IMAPHelpers


text:
extern crate hyper;

use std::io::Read;

use hyper::Client;
use hyper::header::Basic;
use hyper::header::Authorization;

fn main() {
        // Create a client.
        let client = Client::new();
        //let user = String.new("admin");
        let basic = Basic{username: "admin".to_owned(), password: Some("admin".to_owned())};

        //let mut headers = Headers::new();
        //headers.set(auth);
            // Creating an outgoing request.
            let mut res = client.post("https://bleaf4/command-api")
                        // set a header
                        .header(Authorization(basic))
                        .body(r#"{
                                "jsonrpc": "2.0",
                                "method": "runCmds",
                                "params": {
                                    "version": 1,
                                    "cmds": [
                                    "show version"
                                    ],
                                    "format": "json",
                                    "timestamps": false
                                    },
                                "id": "1"
                                  }"#)
                                // let 'er go!
                                .send().unwrap();

                // Read the Response.
                let mut body = String::new();
                res.read_to_string(&mut body).unwrap();

                println!("Response: {}", body);
}


text:
package featureFinder.model;

public class POClass extends SimpleParsedObject {
	private String _package;

	public POClass() {
	}

	@Override
	public String toString() {
		String p = _package;
		if (!p.isEmpty())
			p += '.';
		return "class:" + p + name;
	}

	/** Reverse of toString
	 *
	 * @param str a class identifier, e.g. 'class:a.b.Class'
	 */
	public POClass(String str) {
		String[] p = str.split("[:.]");
		if (p.length < 2 || !p[0].equals("class")) {
			throw new IllegalArgumentException();
		}
		name = p[p.length - 1];
		_package = str.substring(6, str.lastIndexOf('.'));
	}
}


text:
<?php
/**
 *
 *
 *
 *
 */

namespace Cotya\CI_Helper\Magento\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class TravisCISkeletonCreateCommand extends Command
{

    protected function configure()
    {
        $this
            ->setName('travis:skeleton:create')
            ->setDescription('creates a basic skeleton for travis CI')
            ->addOption(
                'force',
                null,
                InputOption::VALUE_NONE,
                'If set, the task will overwrite existing travis file'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $file = '.travis.yml';
        if (!$input->getOption('force')) {
            if (file_exists($file)) {
                $output->writeln("<error>\"$file\" already exists</error>");
                die(1);
            }
        }

        file_put_contents($file, $this->getTemplate());
        $output->writeln("<fg=green>\"$file\" created</fg=green>");

    }

    protected function getTemplate()
    {
        $template = <<<'YAML'
language: php
php:
#  - 5.3
  - 5.5
  - 5.6
env:
  - MAGENTO=1.8.1.0
  - MAGENTO=1.9.1.0
  - MAGENTO=2.0.42.0-beta10
matrix:
  fast_finish: true
  include:
    - php: 5.6
      env: TEST_SUITE=Static
  allow_failures:
    - env: TEST_SUITE=Static
before_install:
  - mkdir test-root/
install:
  - composer install --dev
before_script:
  - php vendor/bin/cotya-setup_travis.php
script:
  - >
    sh -c "if [ '$TEST_SUITE' = 'Static' ]; then
      ./vendor/bin/phpcs -v --standard=PSR2 --ignore="/test-root|/lib|/shell|/vendor|/m1" ./;
    else
      vendor/bin/phpunit
    fi"

YAML;
        return $template;
    }
}


text:
Pup Shape

**School** transmutation (polymorph); **Level** druid 3, sorcerer/wizard 3, witch 3

**Casting Time** 1 standard action

**Component** V, S, M (a rag doll)

**Range** close (25 ft. + 5 ft./2 levels)

**Target** one [animal](monsters/creatureTypes#_animal) or [magical beast](monsters/creatureTypes#_magical-beast).

**Duration** 1 round/level

**Saving Throw** Fortitude negates (and Will special, see text); **Spell Resistance** yes

You transform the subject animal into a Small magical beast, creating a young magical version of itself for a short period of time. While in this form, the target has only 1 HD (maximum hit points), and the target takes a –4 penalty to Strength, Constitution, Intelligence and Wisdom (minimum 1). The creature also gains a +4 size bonus to Dexterity and a +2 natural bonus.

Any nonevil creature that attempts to attack a creature in this form must succeed at a Will saving throw (using the DC of the spell) to overcome feelings of guilt and protectiveness toward the young and innocent-seeming creature. On a failed saving throw, it cannot follow through with the attack, that part of the action is lost, and it can't directly attack the transformed creature for the duration of the spell or until the spell's target attacks it. This part of the spell is a mind-affecting effect. Evil creatures have no qualms about attacking the target of this spell, in fact, some particularly heinous creatures might go out of their ways to do the target harm.


text:
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")

describe "instance_filters plugin" do
  before do
    @c = Class.new(Sequel::Model(:people))
    @c.dataset.quote_identifiers = false
    @c.columns :id, :name, :num
    @c.plugin :instance_filters
    @p = @c.load(:id=>1, :name=>'John', :num=>1)
    DB.sqls
  end

  specify "should raise an error when updating a stale record" do
    @p.update(:name=>'Bob')
    DB.sqls.should == ["UPDATE people SET name = 'Bob' WHERE (id = 1)"]
    @p.instance_filter(:name=>'Jim')
    @p.this.numrows = 0
    proc{@p.update(:name=>'Joe')}.should raise_error(Sequel::Plugins::InstanceFilters::Error)
    DB.sqls.should == ["UPDATE people SET name = 'Joe' WHERE ((id = 1) AND (name = 'Jim'))"]
  end

  specify "should raise an error when destroying a stale record" do
    @p.destroy
    DB.sqls.should == ["DELETE FROM people WHERE id = 1"]
    @p.instance_filter(:name=>'Jim')
    @p.this.numrows = 0
    proc{@p.destroy}.should raise_error(Sequel::Plugins::InstanceFilters::Error)
    DB.sqls.should == ["DELETE FROM people WHERE ((id = 1) AND (name = 'Jim'))"]
  end

  specify "should work when using the prepared_statements plugin" do
    @c.plugin :prepared_statements

    @p.update(:name=>'Bob')
    DB.sqls.should == ["UPDATE people SET name = 'Bob' WHERE (id = 1)"]
    @p.instance_filter(:name=>'Jim')
    @p.this.numrows = 0
    proc{@p.update(:name=>'Joe')}.should raise_error(Sequel::Plugins::InstanceFilters::Error)
    DB.sqls.should == ["UPDATE people SET name = 'Joe' WHERE ((id = 1) AND (name = 'Jim'))"]

    @p = @c.load(:id=>1, :name=>'John', :num=>1)
    @p.this.numrows = 1
    @p.destroy
    DB.sqls.should == ["DELETE FROM people WHERE (id = 1)"]
    @p.instance_filter(:name=>'Jim')
    @p.this.numrows = 0
    proc{@p.destroy}.should raise_error(Sequel::Plugins::InstanceFilters::Error)
    DB.sqls.should == ["DELETE FROM people WHERE ((id = 1) AND (name = 'Jim'))"]

    @c.create.should be_a_kind_of(@c)
  end

  specify "should apply all instance filters" do
    @p.instance_filter(:name=>'Jim')
    @p.instance_filter{num > 2}
    @p.update(:name=>'Bob')
    DB.sqls.should == ["UPDATE people SET name = 'Bob' WHERE ((id = 1) AND (name = 'Jim') AND (num > 2))"]
  end

  specify "should drop instance filters after updating" do
    @p.instance_filter(:name=>'Joe')
    @p.update(:name=>'Joe')
    DB.sqls.should == ["UPDATE people SET name = 'Joe' WHERE ((id = 1) AND (name = 'Joe'))"]
    @p.update(:name=>'Bob')
    DB.sqls.should == ["UPDATE people SET name = 'Bob' WHERE (id = 1)"]
  end

  specify "shouldn't allow instance filters on frozen objects" do
    @p.instance_filter(:name=>'Joe')
    @p.freeze
    proc{@p.instance_filter(:name=>'Jim')}.should raise_error
  end
end


text:
/* $NetBSD: mdsetimage.c,v 1.20 2010/11/06 16:03:23 uebayasi Exp $ */

/*
 * Copyright (c) 1996 Christopher G. Demetriou
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * <<Id: LICENSE_GC,v 1.1 2001/10/01 23:24:05 cgd Exp>>
 */

#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1996\
 Christopher G. Demetriou.  All rights reserved.");
#endif /* not lint */

#ifndef lint
__RCSID("$NetBSD: mdsetimage.c,v 1.20 2010/11/06 16:03:23 uebayasi Exp $");
#endif /* not lint */

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>

#include <err.h>
#include <fcntl.h>
#include <limits.h>
#include <nlist.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "extern.h"

int		main __P((int, char *[]));
static void	usage __P((void)) __dead;
static int	find_md_root __P((const char *, const char *, size_t,
		    const struct nlist *, size_t *, u_int32_t *));

#define	X_MD_ROOT_IMAGE		0
#define	X_MD_ROOT_SIZE		1

int	verbose;
#ifdef NLIST_AOUT
/*
 * Since we can't get the text address from an a.out executable, we
 * need to be able to specify it.  Note: there's no way to test to
 * see if the user entered a valid address!
 */
int	T_flag_specified;	/* the -T flag was specified */
u_long	text_start;		/* Start of kernel text */
#endif /* NLIST_AOUT */

int
main(argc, argv)
	int argc;
	char *argv[];
{
	struct stat ksb, fssb;
	size_t md_root_offset;
	u_int32_t md_root_size;
	const char *kfile, *fsfile;
	char *mappedkfile;
	int ch, kfd, fsfd, rv;
	struct nlist md_root_nlist[3];

	(void)memset(md_root_nlist, 0, sizeof(md_root_nlist));
	N_NAME(&md_root_nlist[X_MD_ROOT_IMAGE]) = "_md_root_image";
	N_NAME(&md_root_nlist[X_MD_ROOT_SIZE]) = "_md_root_size";

	setprogname(argv[0]);

	while ((ch = getopt(argc, argv, "I:S:T:v")) != -1)
		switch (ch) {
		case 'v':
			verbose = 1;
			break;
		case 'I':
			N_NAME(&md_root_nlist[X_MD_ROOT_IMAGE]) = optarg;
			break;
		case 'S':
			N_NAME(&md_root_nlist[X_MD_ROOT_SIZE]) = optarg;
			break;
		case 'T':
#ifdef NLIST_AOUT
			T_flag_specified = 1;
			text_start = strtoul(optarg, NULL, 0);
			break;
#endif /* NLIST_AOUT */
			/* FALLTHROUGH */
		case '?':
		default:
			usage();
	}
	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();
	kfile = argv[0];
	fsfile = argv[1];

	if ((kfd = open(kfile, O_RDWR, 0))  == -1)
		err(1, "open %s", kfile);

	if ((rv = __fdnlist(kfd, md_root_nlist)) != 0)
		errx(1, "could not find symbols in %s", kfile);
	if (verbose)
		fprintf(stderr, "got symbols from %s\n", kfile);

	if (fstat(kfd, &ksb) == -1)
		err(1, "fstat %s", kfile);
	if (ksb.st_size != (size_t)ksb.st_size)
		errx(1, "%s too big to map", kfile);

	if ((mappedkfile = mmap(NULL, ksb.st_size, PROT_READ | PROT_WRITE,
	    MAP_FILE | MAP_SHARED, kfd, 0)) == (caddr_t)-1)
		err(1, "mmap %s", kfile);
	if (verbose)
		fprintf(stderr, "mapped %s\n", kfile);

	if (find_md_root(kfile, mappedkfile, ksb.st_size, md_root_nlist,
	    &md_root_offset, &md_root_size) != 0)
		errx(1, "could not find md root buffer in %s", kfile);

	if ((fsfd = open(fsfile, O_RDONLY, 0)) == -1)
		err(1, "open %s", fsfile);
	if (fstat(fsfd, &fssb) == -1)
		err(1, "fstat %s", fsfile);
	if (fssb.st_size != (size_t)fssb.st_size)
		errx(1, "fs image is too big");
	if (fssb.st_size > md_root_size)
		errx(1, "fs image (%lld bytes) too big for buffer (%lu bytes)",
		    (long long)fssb.st_size, (unsigned long)md_root_size);

	if (verbose)
		fprintf(stderr, "copying image from %s into %s\n", fsfile,
		    kfile);
	if ((rv = read(fsfd, mappedkfile + md_root_offset,
	    fssb.st_size)) != fssb.st_size) {
		if (rv == -1)
			err(1, "read %s", fsfile);
		else
			errx(1, "unexpected EOF reading %s", fsfile);
	}
	if (verbose)
		fprintf(stderr, "done copying image\n");

	close(fsfd);

	munmap(mappedkfile, ksb.st_size);
	close(kfd);

	if (verbose)
		fprintf(stderr, "exiting\n");
	exit(0);
}

static void
usage()
{

	fprintf(stderr,
	    "usage: %s kernel_file fsimage_file\n",
	    getprogname());
	exit(1);
}

struct {
	const char *name;
	int	(*check) __P((const char *, size_t));
	int	(*findoff) __P((const char *, size_t, u_long, size_t *));
} exec_formats[] = {
#ifdef NLIST_AOUT
	{	"a.out",	check_aout,	findoff_aout,	},
#endif
#ifdef NLIST_ECOFF
	{	"ECOFF",	check_ecoff,	findoff_ecoff,	},
#endif
#ifdef NLIST_ELF32
	{	"ELF32",	check_elf32,	findoff_elf32,	},
#endif
#ifdef NLIST_ELF64
	{	"ELF64",	check_elf64,	findoff_elf64,	},
#endif
#ifdef NLIST_COFF
	{	"COFF",		check_coff,	findoff_coff,	},
#endif
};

static int
find_md_root(fname, mappedfile, mappedsize, nl, rootoffp, rootsizep)
	const char *fname, *mappedfile;
	size_t mappedsize;
	const struct nlist *nl;
	size_t *rootoffp;
	u_int32_t *rootsizep;
{
	int i, n;
	size_t rootsizeoff;

	n = sizeof exec_formats / sizeof exec_formats[0];
	for (i = 0; i < n; i++) {
		if ((*exec_formats[i].check)(mappedfile, mappedsize) == 0)
			break;
	}
	if (i == n) {
		warnx("%s: unknown executable format", fname);
		return (1);
	}

	if (verbose) {
		fprintf(stderr, "%s is an %s binary\n", fname,
		    exec_formats[i].name);
#ifdef NLIST_AOUT
		if (T_flag_specified)
			fprintf(stderr, "kernel text loads at 0x%lx\n",
			    text_start);
#endif
	}

	if ((*exec_formats[i].findoff)(mappedfile, mappedsize,
	    nl[X_MD_ROOT_SIZE].n_value, &rootsizeoff) != 0) {
		warnx("couldn't find offset for %s in %s",
		    nl[X_MD_ROOT_SIZE].n_name, fname);
		return (1);
	}
	if (verbose)
		fprintf(stderr, "%s is at offset %#lx in %s\n",
			nl[X_MD_ROOT_SIZE].n_name,
			(unsigned long)rootsizeoff, fname);
	*rootsizep = *(const u_int32_t *)&mappedfile[rootsizeoff];
	if (verbose)
		fprintf(stderr, "%s has value %#x\n",
		    nl[X_MD_ROOT_SIZE].n_name, *rootsizep);

	if ((*exec_formats[i].findoff)(mappedfile, mappedsize,
	    nl[X_MD_ROOT_IMAGE].n_value, rootoffp) != 0) {
		warnx("couldn't find offset for %s in %s",
		    nl[X_MD_ROOT_IMAGE].n_name, fname);
		return (1);
	}
	if (verbose)
		fprintf(stderr, "%s is at offset %#lx in %s\n",
			nl[X_MD_ROOT_IMAGE].n_name,
			(unsigned long)(*rootoffp), fname);

	return (0);
}