text:
import unittest

import mock

try:
    # pylint: disable=unused-import
    import google.cloud.logging._gax
    # pylint: enable=unused-import
except ImportError:  # pragma: NO COVER
    _HAVE_GAX = False
else:
    _HAVE_GAX = True

from google.cloud._testing import _GAXBaseAPI

def _make_credentials():
    # pylint: disable=redefined-outer-name
    import google.auth.credentials
    # pylint: enable=redefined-outer-name

    return mock.Mock(spec=google.auth.credentials.Credentials)

class _Base(object):
    PROJECT = 'PROJECT'
    PROJECT_PATH = 'projects/%s' % (PROJECT,)
    FILTER = 'logName:syslog AND severity>=ERROR'

    def _make_one(self, *args, **kw):
        return self._get_target_class()(*args, **kw)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_LoggingAPI(_Base, unittest.TestCase):
    LOG_NAME = 'log_name'
    LOG_PATH = 'projects/%s/logs/%s' % (_Base.PROJECT, LOG_NAME)

    @staticmethod
    def _get_target_class():
        from google.cloud.logging._gax import _LoggingAPI

        return _LoggingAPI

    def test_ctor(self):
        gax_api = _GAXLoggingAPI()
        client = object()
        api = self._make_one(gax_api, client)
        self.assertIs(api._gax_api, gax_api)
        self.assertIs(api._client, client)

    def test_list_entries_no_paging(self):
        import datetime

        from google.api.monitored_resource_pb2 import MonitoredResource
        from google.gax import INITIAL_PAGE
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry

        from google.cloud._helpers import _datetime_to_pb_timestamp
        from google.cloud._helpers import UTC
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging import DESCENDING
        from google.cloud.logging.client import Client
        from google.cloud.logging.entries import TextEntry
        from google.cloud.logging.logger import Logger

        TOKEN = 'TOKEN'
        TEXT = 'TEXT'
        resource_pb = MonitoredResource(type='global')
        timestamp = datetime.datetime.utcnow().replace(tzinfo=UTC)
        timestamp_pb = _datetime_to_pb_timestamp(timestamp)
        entry_pb = LogEntry(log_name=self.LOG_PATH,
                            resource=resource_pb,
                            timestamp=timestamp_pb,
                            text_payload=TEXT)
        response = _GAXPageIterator([entry_pb], page_token=TOKEN)
        gax_api = _GAXLoggingAPI(_list_log_entries_response=response)
        client = Client(project=self.PROJECT, credentials=_make_credentials(),
                        use_gax=True)
        api = self._make_one(gax_api, client)

        iterator = api.list_entries(
            [self.PROJECT], self.FILTER, DESCENDING)
        entries = list(iterator)
        next_token = iterator.next_page_token

        # First check the token.
        self.assertEqual(next_token, TOKEN)
        # Then check the entries returned.
        self.assertEqual(len(entries), 1)
        entry = entries[0]
        self.assertIsInstance(entry, TextEntry)
        self.assertEqual(entry.payload, TEXT)
        self.assertIsInstance(entry.logger, Logger)
        self.assertEqual(entry.logger.name, self.LOG_NAME)
        self.assertIsNone(entry.insert_id)
        self.assertEqual(entry.timestamp, timestamp)
        self.assertIsNone(entry.labels)
        self.assertIsNone(entry.severity)
        self.assertIsNone(entry.http_request)

        resource_names, projects, filter_, order_by, page_size, options = (
            gax_api._list_log_entries_called_with)
        self.assertEqual(resource_names, [])
        self.assertEqual(projects, [self.PROJECT])
        self.assertEqual(filter_, self.FILTER)
        self.assertEqual(order_by, DESCENDING)
        self.assertEqual(page_size, 0)
        self.assertIs(options.page_token, INITIAL_PAGE)

    def _list_entries_with_paging_helper(self, payload, struct_pb):
        import datetime

        from google.api.monitored_resource_pb2 import MonitoredResource
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry
        from google.cloud._helpers import _datetime_to_pb_timestamp
        from google.cloud._helpers import UTC
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.client import Client
        from google.cloud.logging.entries import StructEntry
        from google.cloud.logging.logger import Logger

        SIZE = 23
        TOKEN = 'TOKEN'
        NEW_TOKEN = 'NEW_TOKEN'
        resource_pb = MonitoredResource(type='global')
        timestamp = datetime.datetime.utcnow().replace(tzinfo=UTC)
        timestamp_pb = _datetime_to_pb_timestamp(timestamp)
        entry_pb = LogEntry(log_name=self.LOG_PATH,
                            resource=resource_pb,
                            timestamp=timestamp_pb,
                            json_payload=struct_pb)
        response = _GAXPageIterator([entry_pb], page_token=NEW_TOKEN)
        gax_api = _GAXLoggingAPI(_list_log_entries_response=response)
        client = Client(project=self.PROJECT, credentials=_make_credentials(),
                        use_gax=True)
        api = self._make_one(gax_api, client)

        iterator = api.list_entries(
            [self.PROJECT], page_size=SIZE, page_token=TOKEN)
        entries = list(iterator)
        next_token = iterator.next_page_token

        # First check the token.
        self.assertEqual(next_token, NEW_TOKEN)
        self.assertEqual(len(entries), 1)
        entry = entries[0]
        self.assertIsInstance(entry, StructEntry)
        self.assertEqual(entry.payload, payload)
        self.assertIsInstance(entry.logger, Logger)
        self.assertEqual(entry.logger.name, self.LOG_NAME)
        self.assertIsNone(entry.insert_id)
        self.assertEqual(entry.timestamp, timestamp)
        self.assertIsNone(entry.labels)
        self.assertIsNone(entry.severity)
        self.assertIsNone(entry.http_request)

        resource_names, projects, filter_, order_by, page_size, options = (
            gax_api._list_log_entries_called_with)
        self.assertEqual(resource_names, [])
        self.assertEqual(projects, [self.PROJECT])
        self.assertEqual(filter_, '')
        self.assertEqual(order_by, '')
        self.assertEqual(page_size, SIZE)
        self.assertEqual(options.page_token, TOKEN)

    def test_list_entries_with_paging(self):
        from google.protobuf.struct_pb2 import Struct
        from google.protobuf.struct_pb2 import Value

        payload = {'message': 'MESSAGE', 'weather': 'sunny'}
        struct_pb = Struct(fields={
            key: Value(string_value=value) for key, value in payload.items()
        })
        self._list_entries_with_paging_helper(payload, struct_pb)

    def test_list_entries_with_paging_nested_payload(self):
        from google.protobuf.struct_pb2 import Struct
        from google.protobuf.struct_pb2 import Value

        payload = {}
        struct_fields = {}
        # Add a simple key.
        key = 'message'
        payload[key] = 'MESSAGE'
        struct_fields[key] = Value(string_value=payload[key])
        # Add a nested key.
        key = 'weather'
        sub_value = {}
        sub_fields = {}
        sub_key = 'temperature'
        sub_value[sub_key] = 75
        sub_fields[sub_key] = Value(number_value=sub_value[sub_key])
        sub_key = 'precipitation'
        sub_value[sub_key] = False
        sub_fields[sub_key] = Value(bool_value=sub_value[sub_key])
        # Update the parent payload.
        payload[key] = sub_value
        struct_fields[key] = Value(struct_value=Struct(fields=sub_fields))
        # Make the struct_pb for our dict.
        struct_pb = Struct(fields=struct_fields)
        self._list_entries_with_paging_helper(payload, struct_pb)

    def _make_log_entry_with_extras(self, labels, iid, type_url, now):
        from google.api.monitored_resource_pb2 import MonitoredResource
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry
        from google.cloud.proto.logging.v2.log_entry_pb2 import (
            LogEntryOperation)
        from google.logging.type.http_request_pb2 import HttpRequest
        from google.logging.type.log_severity_pb2 import WARNING
        from google.protobuf.any_pb2 import Any

        from google.cloud._helpers import _datetime_to_pb_timestamp

        resource_pb = MonitoredResource(
            type='global', labels=labels)
        proto_payload = Any(type_url=type_url)
        timestamp_pb = _datetime_to_pb_timestamp(now)
        request_pb = HttpRequest(
            request_url='http://example.com/requested',
            request_method='GET',
            status=200,
            referer='http://example.com/referer',
            user_agent='AGENT',
            cache_hit=True,
            request_size=256,
            response_size=1024,
            remote_ip='1.2.3.4',
        )
        operation_pb = LogEntryOperation(
            producer='PRODUCER',
            first=True,
            last=True,
            id='OPID',
        )
        entry_pb = LogEntry(log_name=self.LOG_PATH,
                            resource=resource_pb,
                            proto_payload=proto_payload,
                            timestamp=timestamp_pb,
                            severity=WARNING,
                            insert_id=iid,
                            http_request=request_pb,
                            labels=labels,
                            operation=operation_pb)
        return entry_pb

    def test_list_entries_with_extra_properties(self):
        import datetime

        # Import the wrappers to register the type URL for BoolValue
        # pylint: disable=unused-variable
        from google.protobuf import wrappers_pb2
        # pylint: enable=unused-variable

        from google.cloud._helpers import UTC
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.client import Client
        from google.cloud.logging.entries import ProtobufEntry
        from google.cloud.logging.logger import Logger

        NOW = datetime.datetime.utcnow().replace(tzinfo=UTC)
        SIZE = 23
        TOKEN = 'TOKEN'
        NEW_TOKEN = 'NEW_TOKEN'
        SEVERITY = 'WARNING'
        LABELS = {
            'foo': 'bar',
        }
        IID = 'IID'
        bool_type_url = 'type.googleapis.com/google.protobuf.BoolValue'
        entry_pb = self._make_log_entry_with_extras(
            LABELS, IID, bool_type_url, NOW)

        response = _GAXPageIterator([entry_pb], page_token=NEW_TOKEN)
        gax_api = _GAXLoggingAPI(_list_log_entries_response=response)
        client = Client(project=self.PROJECT, credentials=_make_credentials(),
                        use_gax=True)
        api = self._make_one(gax_api, client)

        iterator = api.list_entries(
            [self.PROJECT], page_size=SIZE, page_token=TOKEN)
        entries = list(iterator)
        next_token = iterator.next_page_token

        # First check the token.
        self.assertEqual(next_token, NEW_TOKEN)
        # Then check the entries returned.
        self.assertEqual(len(entries), 1)
        entry = entries[0]
        self.assertIsInstance(entry, ProtobufEntry)
        self.assertEqual(entry.payload, {
            '@type': bool_type_url,
            'value': False,
        })
        self.assertIsInstance(entry.logger, Logger)
        self.assertEqual(entry.logger.name, self.LOG_NAME)
        self.assertEqual(entry.insert_id, IID)
        self.assertEqual(entry.timestamp, NOW)
        self.assertEqual(entry.labels, {'foo': 'bar'})
        self.assertEqual(entry.severity, SEVERITY)
        self.assertEqual(entry.http_request, {
            'requestMethod': entry_pb.http_request.request_method,
            'requestUrl': entry_pb.http_request.request_url,
            'status': entry_pb.http_request.status,
            'requestSize': str(entry_pb.http_request.request_size),
            'responseSize': str(entry_pb.http_request.response_size),
            'referer': entry_pb.http_request.referer,
            'userAgent': entry_pb.http_request.user_agent,
            'remoteIp': entry_pb.http_request.remote_ip,
            'cacheHit': entry_pb.http_request.cache_hit,
        })

        resource_names, projects, filter_, order_by, page_size, options = (
            gax_api._list_log_entries_called_with)
        self.assertEqual(resource_names, [])
        self.assertEqual(projects, [self.PROJECT])
        self.assertEqual(filter_, '')
        self.assertEqual(order_by, '')
        self.assertEqual(page_size, SIZE)
        self.assertEqual(options.page_token, TOKEN)

    def test_write_entries_single(self):
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry

        TEXT = 'TEXT'
        ENTRY = {
            'logName': self.LOG_PATH,
            'resource': {'type': 'global'},
            'textPayload': TEXT,
        }
        gax_api = _GAXLoggingAPI()
        api = self._make_one(gax_api, None)

        api.write_entries([ENTRY])

        entries, log_name, resource, labels, partial_success, options = (
            gax_api._write_log_entries_called_with)
        self.assertEqual(len(entries), 1)

        entry = entries[0]
        self.assertIsInstance(entry, LogEntry)
        self.assertEqual(entry.log_name, self.LOG_PATH)
        self.assertEqual(entry.resource.type, 'global')
        self.assertEqual(entry.labels, {})
        self.assertEqual(entry.text_payload, TEXT)

        self.assertIsNone(log_name)
        self.assertIsNone(resource)
        self.assertIsNone(labels)
        self.assertEqual(partial_success, False)
        self.assertIsNone(options)

    def test_write_entries_w_extra_properties(self):
        # pylint: disable=too-many-statements
        from datetime import datetime
        from google.logging.type.log_severity_pb2 import WARNING
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry
        from google.cloud._helpers import _datetime_to_rfc3339
        from google.cloud._helpers import UTC, _pb_timestamp_to_datetime

        NOW = datetime.utcnow().replace(tzinfo=UTC)
        TEXT = 'TEXT'
        SEVERITY = 'WARNING'
        LABELS = {
            'foo': 'bar',
        }
        IID = 'IID'
        REQUEST_METHOD = 'GET'
        REQUEST_URL = 'http://example.com/requested'
        STATUS = 200
        REQUEST_SIZE = 256
        RESPONSE_SIZE = 1024
        REFERRER_URL = 'http://example.com/referer'
        USER_AGENT = 'Agent/1.0'
        REMOTE_IP = '1.2.3.4'
        REQUEST = {
            'requestMethod': REQUEST_METHOD,
            'requestUrl': REQUEST_URL,
            'status': STATUS,
            'requestSize': REQUEST_SIZE,
            'responseSize': RESPONSE_SIZE,
            'referer': REFERRER_URL,
            'userAgent': USER_AGENT,
            'remoteIp': REMOTE_IP,
            'cacheHit': False,
        }
        PRODUCER = 'PRODUCER'
        OPID = 'OPID'
        OPERATION = {
            'producer': PRODUCER,
            'id': OPID,
            'first': False,
            'last': True,
        }
        ENTRY = {
            'logName': self.LOG_PATH,
            'resource': {'type': 'global'},
            'textPayload': TEXT,
            'severity': SEVERITY,
            'labels': LABELS,
            'insertId': IID,
            'timestamp': _datetime_to_rfc3339(NOW),
            'httpRequest': REQUEST,
            'operation': OPERATION,
        }
        gax_api = _GAXLoggingAPI()
        api = self._make_one(gax_api, None)

        api.write_entries([ENTRY])

        entries, log_name, resource, labels, partial_success, options = (
            gax_api._write_log_entries_called_with)
        self.assertEqual(len(entries), 1)

        entry = entries[0]
        self.assertIsInstance(entry, LogEntry)
        self.assertEqual(entry.log_name, self.LOG_PATH)
        self.assertEqual(entry.resource.type, 'global')
        self.assertEqual(entry.text_payload, TEXT)
        self.assertEqual(entry.severity, WARNING)
        self.assertEqual(entry.labels, LABELS)
        self.assertEqual(entry.insert_id, IID)
        stamp = _pb_timestamp_to_datetime(entry.timestamp)
        self.assertEqual(stamp, NOW)

        request = entry.http_request
        self.assertEqual(request.request_method, REQUEST_METHOD)
        self.assertEqual(request.request_url, REQUEST_URL)
        self.assertEqual(request.status, STATUS)
        self.assertEqual(request.request_size, REQUEST_SIZE)
        self.assertEqual(request.response_size, RESPONSE_SIZE)
        self.assertEqual(request.referer, REFERRER_URL)
        self.assertEqual(request.user_agent, USER_AGENT)
        self.assertEqual(request.remote_ip, REMOTE_IP)
        self.assertEqual(request.cache_hit, False)

        operation = entry.operation
        self.assertEqual(operation.producer, PRODUCER)
        self.assertEqual(operation.id, OPID)
        self.assertFalse(operation.first)
        self.assertTrue(operation.last)

        self.assertIsNone(log_name)
        self.assertIsNone(resource)
        self.assertIsNone(labels)
        self.assertEqual(partial_success, False)
        self.assertIsNone(options)
        # pylint: enable=too-many-statements

    def _write_entries_multiple_helper(self, json_payload, json_struct_pb):
        # pylint: disable=too-many-statements
        import datetime
        from google.logging.type.log_severity_pb2 import WARNING
        from google.cloud.proto.logging.v2.log_entry_pb2 import LogEntry
        from google.protobuf.any_pb2 import Any
        from google.cloud._helpers import _datetime_to_rfc3339
        from google.cloud._helpers import UTC

        TEXT = 'TEXT'
        NOW = datetime.datetime.utcnow().replace(tzinfo=UTC)
        TIMESTAMP_TYPE_URL = 'type.googleapis.com/google.protobuf.Timestamp'
        PROTO = {
            '@type': TIMESTAMP_TYPE_URL,
            'value': _datetime_to_rfc3339(NOW),
        }
        PRODUCER = 'PRODUCER'
        OPID = 'OPID'
        URL = 'http://example.com/'
        ENTRIES = [
            {'textPayload': TEXT,
             'severity': WARNING},
            {'jsonPayload': json_payload,
             'operation': {'producer': PRODUCER, 'id': OPID}},
            {'protoPayload': PROTO,
             'httpRequest': {'requestUrl': URL}},
        ]
        RESOURCE = {
            'type': 'global',
        }
        LABELS = {
            'foo': 'bar',
        }
        gax_api = _GAXLoggingAPI()
        api = self._make_one(gax_api, None)

        api.write_entries(ENTRIES, self.LOG_PATH, RESOURCE, LABELS)

        entries, log_name, resource, labels, partial_success, options = (
            gax_api._write_log_entries_called_with)
        self.assertEqual(len(entries), len(ENTRIES))

        entry = entries[0]
        self.assertIsInstance(entry, LogEntry)
        self.assertEqual(entry.log_name, '')
        self.assertEqual(entry.resource.type, '')
        self.assertEqual(entry.labels, {})
        self.assertEqual(entry.text_payload, TEXT)
        self.assertEqual(entry.severity, WARNING)

        entry = entries[1]
        self.assertIsInstance(entry, LogEntry)
        self.assertEqual(entry.log_name, '')
        self.assertEqual(entry.resource.type, '')
        self.assertEqual(entry.labels, {})
        self.assertEqual(entry.json_payload, json_struct_pb)
        operation = entry.operation
        self.assertEqual(operation.producer, PRODUCER)
        self.assertEqual(operation.id, OPID)

        entry = entries[2]
        self.assertIsInstance(entry, LogEntry)
        self.assertEqual(entry.log_name, '')
        self.assertEqual(entry.resource.type, '')
        self.assertEqual(entry.labels, {})
        proto = entry.proto_payload
        self.assertIsInstance(proto, Any)
        self.assertEqual(proto.type_url, TIMESTAMP_TYPE_URL)
        request = entry.http_request
        self.assertEqual(request.request_url, URL)

        self.assertEqual(log_name, self.LOG_PATH)
        self.assertEqual(resource, RESOURCE)
        self.assertEqual(labels, LABELS)
        self.assertEqual(partial_success, False)
        self.assertIsNone(options)
        # pylint: enable=too-many-statements

    def test_write_entries_multiple(self):
        from google.protobuf.struct_pb2 import Struct
        from google.protobuf.struct_pb2 import Value

        json_payload = {'payload': 'PAYLOAD', 'type': 'json'}
        json_struct_pb = Struct(fields={
            key: Value(string_value=value)
            for key, value in json_payload.items()
        })
        self._write_entries_multiple_helper(json_payload, json_struct_pb)

    def test_write_entries_multiple_nested_payload(self):
        from google.protobuf.struct_pb2 import Struct
        from google.protobuf.struct_pb2 import Value

        json_payload = {}
        struct_fields = {}
        # Add a simple key.
        key = 'hello'
        json_payload[key] = 'me you looking for'
        struct_fields[key] = Value(string_value=json_payload[key])
        # Add a nested key.
        key = 'everything'
        sub_value = {}
        sub_fields = {}
        sub_key = 'answer'
        sub_value[sub_key] = 42
        sub_fields[sub_key] = Value(number_value=sub_value[sub_key])
        sub_key = 'really?'
        sub_value[sub_key] = False
        sub_fields[sub_key] = Value(bool_value=sub_value[sub_key])
        # Update the parent payload.
        json_payload[key] = sub_value
        struct_fields[key] = Value(struct_value=Struct(fields=sub_fields))
        # Make the struct_pb for our dict.
        json_struct_pb = Struct(fields=struct_fields)
        self._write_entries_multiple_helper(json_payload, json_struct_pb)

    def test_logger_delete(self):
        gax_api = _GAXLoggingAPI()
        api = self._make_one(gax_api, None)

        api.logger_delete(self.PROJECT, self.LOG_NAME)

        log_name, options = gax_api._delete_log_called_with
        self.assertEqual(log_name, self.LOG_PATH)
        self.assertIsNone(options)

    def test_logger_delete_not_found(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXLoggingAPI(_delete_not_found=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.logger_delete(self.PROJECT, self.LOG_NAME)

        log_name, options = gax_api._delete_log_called_with
        self.assertEqual(log_name, self.LOG_PATH)
        self.assertIsNone(options)

    def test_logger_delete_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXLoggingAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.logger_delete(self.PROJECT, self.LOG_NAME)

        log_name, options = gax_api._delete_log_called_with
        self.assertEqual(log_name, self.LOG_PATH)
        self.assertIsNone(options)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_SinksAPI(_Base, unittest.TestCase):
    SINK_NAME = 'sink_name'
    SINK_PATH = 'projects/%s/sinks/%s' % (_Base.PROJECT, SINK_NAME)
    DESTINATION_URI = 'faux.googleapis.com/destination'

    @staticmethod
    def _get_target_class():
        from google.cloud.logging._gax import _SinksAPI

        return _SinksAPI

    def test_ctor(self):
        gax_api = _GAXSinksAPI()
        client = object()
        api = self._make_one(gax_api, client)
        self.assertIs(api._gax_api, gax_api)
        self.assertIs(api._client, client)

    def test_list_sinks_no_paging(self):
        import six
        from google.gax import INITIAL_PAGE
        from google.cloud.proto.logging.v2.logging_config_pb2 import LogSink
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.sink import Sink

        TOKEN = 'TOKEN'
        sink_pb = LogSink(name=self.SINK_PATH,
                          destination=self.DESTINATION_URI,
                          filter=self.FILTER)
        response = _GAXPageIterator([sink_pb], page_token=TOKEN)
        gax_api = _GAXSinksAPI(_list_sinks_response=response)
        client = object()
        api = self._make_one(gax_api, client)

        iterator = api.list_sinks(self.PROJECT)
        page = six.next(iterator.pages)
        sinks = list(page)
        token = iterator.next_page_token

        # First check the token.
        self.assertEqual(token, TOKEN)
        # Then check the sinks returned.
        self.assertEqual(len(sinks), 1)
        sink = sinks[0]
        self.assertIsInstance(sink, Sink)
        self.assertEqual(sink.name, self.SINK_PATH)
        self.assertEqual(sink.filter_, self.FILTER)
        self.assertEqual(sink.destination, self.DESTINATION_URI)
        self.assertIs(sink.client, client)

        project, page_size, options = gax_api._list_sinks_called_with
        self.assertEqual(project, self.PROJECT_PATH)
        self.assertEqual(page_size, 0)
        self.assertEqual(options.page_token, INITIAL_PAGE)

    def test_list_sinks_w_paging(self):
        from google.cloud.proto.logging.v2.logging_config_pb2 import LogSink
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.sink import Sink

        TOKEN = 'TOKEN'
        PAGE_SIZE = 42
        sink_pb = LogSink(name=self.SINK_PATH,
                          destination=self.DESTINATION_URI,
                          filter=self.FILTER)
        response = _GAXPageIterator([sink_pb])
        gax_api = _GAXSinksAPI(_list_sinks_response=response)
        client = object()
        api = self._make_one(gax_api, client)

        iterator = api.list_sinks(
            self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN)
        sinks = list(iterator)
        token = iterator.next_page_token

        # First check the token.
        self.assertIsNone(token)
        # Then check the sinks returned.
        self.assertEqual(len(sinks), 1)
        sink = sinks[0]
        self.assertIsInstance(sink, Sink)
        self.assertEqual(sink.name, self.SINK_PATH)
        self.assertEqual(sink.filter_, self.FILTER)
        self.assertEqual(sink.destination, self.DESTINATION_URI)
        self.assertIs(sink.client, client)

        project, page_size, options = gax_api._list_sinks_called_with
        self.assertEqual(project, self.PROJECT_PATH)
        self.assertEqual(page_size, PAGE_SIZE)
        self.assertEqual(options.page_token, TOKEN)

    def test_sink_create_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXSinksAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.sink_create(
                self.PROJECT, self.SINK_NAME, self.FILTER,
                self.DESTINATION_URI)

    def test_sink_create_conflict(self):
        from google.cloud.exceptions import Conflict

        gax_api = _GAXSinksAPI(_create_sink_conflict=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(Conflict):
            api.sink_create(
                self.PROJECT, self.SINK_NAME, self.FILTER,
                self.DESTINATION_URI)

    def test_sink_create_ok(self):
        from google.cloud.proto.logging.v2.logging_config_pb2 import LogSink

        gax_api = _GAXSinksAPI()
        api = self._make_one(gax_api, None)

        api.sink_create(
            self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI)

        parent, sink, options = (
            gax_api._create_sink_called_with)
        self.assertEqual(parent, self.PROJECT_PATH)
        self.assertIsInstance(sink, LogSink)
        self.assertEqual(sink.name, self.SINK_NAME)
        self.assertEqual(sink.filter, self.FILTER)
        self.assertEqual(sink.destination, self.DESTINATION_URI)
        self.assertIsNone(options)

    def test_sink_get_error(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXSinksAPI()
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.sink_get(self.PROJECT, self.SINK_NAME)

    def test_sink_get_miss(self):
        from google.gax.errors import GaxError

        gax_api = _GAXSinksAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.sink_get(self.PROJECT, self.SINK_NAME)

    def test_sink_get_hit(self):
        from google.cloud.proto.logging.v2.logging_config_pb2 import LogSink

        RESPONSE = {
            'name': self.SINK_PATH,
            'filter': self.FILTER,
            'destination': self.DESTINATION_URI,
        }
        sink_pb = LogSink(name=self.SINK_PATH,
                          destination=self.DESTINATION_URI,
                          filter=self.FILTER)
        gax_api = _GAXSinksAPI(_get_sink_response=sink_pb)
        api = self._make_one(gax_api, None)

        response = api.sink_get(self.PROJECT, self.SINK_NAME)

        self.assertEqual(response, RESPONSE)

        sink_name, options = gax_api._get_sink_called_with
        self.assertEqual(sink_name, self.SINK_PATH)
        self.assertIsNone(options)

    def test_sink_update_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXSinksAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.sink_update(
                self.PROJECT, self.SINK_NAME, self.FILTER,
                self.DESTINATION_URI)

    def test_sink_update_miss(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXSinksAPI()
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.sink_update(
                self.PROJECT, self.SINK_NAME, self.FILTER,
                self.DESTINATION_URI)

    def test_sink_update_hit(self):
        from google.cloud.proto.logging.v2.logging_config_pb2 import LogSink

        response = LogSink(name=self.SINK_NAME,
                           destination=self.DESTINATION_URI,
                           filter=self.FILTER)
        gax_api = _GAXSinksAPI(_update_sink_response=response)
        api = self._make_one(gax_api, None)

        api.sink_update(
            self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI)

        sink_name, sink, options = (
            gax_api._update_sink_called_with)
        self.assertEqual(sink_name, self.SINK_PATH)
        self.assertIsInstance(sink, LogSink)
        self.assertEqual(sink.name, self.SINK_PATH)
        self.assertEqual(sink.filter, self.FILTER)
        self.assertEqual(sink.destination, self.DESTINATION_URI)
        self.assertIsNone(options)

    def test_sink_delete_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXSinksAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.sink_delete(self.PROJECT, self.SINK_NAME)

    def test_sink_delete_miss(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXSinksAPI(_sink_not_found=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.sink_delete(self.PROJECT, self.SINK_NAME)

    def test_sink_delete_hit(self):
        gax_api = _GAXSinksAPI()
        api = self._make_one(gax_api, None)

        api.sink_delete(self.PROJECT, self.SINK_NAME)

        sink_name, options = gax_api._delete_sink_called_with
        self.assertEqual(sink_name, self.SINK_PATH)
        self.assertIsNone(options)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_MetricsAPI(_Base, unittest.TestCase):
    METRIC_NAME = 'metric_name'
    METRIC_PATH = 'projects/%s/metrics/%s' % (_Base.PROJECT, METRIC_NAME)
    DESCRIPTION = 'Description'

    @staticmethod
    def _get_target_class():
        from google.cloud.logging._gax import _MetricsAPI

        return _MetricsAPI

    def test_ctor(self):
        gax_api = _GAXMetricsAPI()
        api = self._make_one(gax_api, None)
        self.assertIs(api._gax_api, gax_api)

    def test_list_metrics_no_paging(self):
        import six
        from google.gax import INITIAL_PAGE
        from google.cloud.proto.logging.v2.logging_metrics_pb2 import LogMetric
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.metric import Metric

        TOKEN = 'TOKEN'
        metric_pb = LogMetric(name=self.METRIC_PATH,
                              description=self.DESCRIPTION,
                              filter=self.FILTER)
        response = _GAXPageIterator([metric_pb], page_token=TOKEN)
        gax_api = _GAXMetricsAPI(_list_log_metrics_response=response)
        client = object()
        api = self._make_one(gax_api, client)

        iterator = api.list_metrics(self.PROJECT)
        page = six.next(iterator.pages)
        metrics = list(page)
        token = iterator.next_page_token

        # First check the token.
        self.assertEqual(token, TOKEN)
        # Then check the metrics returned.
        self.assertEqual(len(metrics), 1)
        metric = metrics[0]
        self.assertIsInstance(metric, Metric)
        self.assertEqual(metric.name, self.METRIC_PATH)
        self.assertEqual(metric.filter_, self.FILTER)
        self.assertEqual(metric.description, self.DESCRIPTION)
        self.assertIs(metric.client, client)

        project, page_size, options = gax_api._list_log_metrics_called_with
        self.assertEqual(project, self.PROJECT_PATH)
        self.assertEqual(page_size, 0)
        self.assertEqual(options.page_token, INITIAL_PAGE)

    def test_list_metrics_w_paging(self):
        from google.cloud.proto.logging.v2.logging_metrics_pb2 import LogMetric
        from google.cloud._testing import _GAXPageIterator
        from google.cloud.logging.metric import Metric

        TOKEN = 'TOKEN'
        PAGE_SIZE = 42
        metric_pb = LogMetric(name=self.METRIC_PATH,
                              description=self.DESCRIPTION,
                              filter=self.FILTER)
        response = _GAXPageIterator([metric_pb])
        gax_api = _GAXMetricsAPI(_list_log_metrics_response=response)
        client = object()
        api = self._make_one(gax_api, client)

        iterator = api.list_metrics(
            self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN)
        metrics = list(iterator)
        token = iterator.next_page_token

        # First check the token.
        self.assertIsNone(token)
        # Then check the metrics returned.
        self.assertEqual(len(metrics), 1)
        metric = metrics[0]
        self.assertIsInstance(metric, Metric)
        self.assertEqual(metric.name, self.METRIC_PATH)
        self.assertEqual(metric.filter_, self.FILTER)
        self.assertEqual(metric.description, self.DESCRIPTION)
        self.assertIs(metric.client, client)

        project, page_size, options = gax_api._list_log_metrics_called_with
        self.assertEqual(project, self.PROJECT_PATH)
        self.assertEqual(page_size, PAGE_SIZE)
        self.assertEqual(options.page_token, TOKEN)

    def test_metric_create_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXMetricsAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.metric_create(
                self.PROJECT, self.METRIC_NAME, self.FILTER,
                self.DESCRIPTION)

    def test_metric_create_conflict(self):
        from google.cloud.exceptions import Conflict

        gax_api = _GAXMetricsAPI(_create_log_metric_conflict=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(Conflict):
            api.metric_create(
                self.PROJECT, self.METRIC_NAME, self.FILTER,
                self.DESCRIPTION)

    def test_metric_create_ok(self):
        from google.cloud.proto.logging.v2.logging_metrics_pb2 import LogMetric

        gax_api = _GAXMetricsAPI()
        api = self._make_one(gax_api, None)

        api.metric_create(
            self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION)

        parent, metric, options = (
            gax_api._create_log_metric_called_with)
        self.assertEqual(parent, self.PROJECT_PATH)
        self.assertIsInstance(metric, LogMetric)
        self.assertEqual(metric.name, self.METRIC_NAME)
        self.assertEqual(metric.filter, self.FILTER)
        self.assertEqual(metric.description, self.DESCRIPTION)
        self.assertIsNone(options)

    def test_metric_get_error(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXMetricsAPI()
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.metric_get(self.PROJECT, self.METRIC_NAME)

    def test_metric_get_miss(self):
        from google.gax.errors import GaxError

        gax_api = _GAXMetricsAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.metric_get(self.PROJECT, self.METRIC_NAME)

    def test_metric_get_hit(self):
        from google.cloud.proto.logging.v2.logging_metrics_pb2 import LogMetric

        RESPONSE = {
            'name': self.METRIC_PATH,
            'filter': self.FILTER,
            'description': self.DESCRIPTION,
        }
        metric_pb = LogMetric(name=self.METRIC_PATH,
                              description=self.DESCRIPTION,
                              filter=self.FILTER)
        gax_api = _GAXMetricsAPI(_get_log_metric_response=metric_pb)
        api = self._make_one(gax_api, None)

        response = api.metric_get(self.PROJECT, self.METRIC_NAME)

        self.assertEqual(response, RESPONSE)

        metric_name, options = gax_api._get_log_metric_called_with
        self.assertEqual(metric_name, self.METRIC_PATH)
        self.assertIsNone(options)

    def test_metric_update_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXMetricsAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.metric_update(
                self.PROJECT, self.METRIC_NAME, self.FILTER,
                self.DESCRIPTION)

    def test_metric_update_miss(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXMetricsAPI()
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.metric_update(
                self.PROJECT, self.METRIC_NAME, self.FILTER,
                self.DESCRIPTION)

    def test_metric_update_hit(self):
        from google.cloud.proto.logging.v2.logging_metrics_pb2 import LogMetric

        response = LogMetric(name=self.METRIC_NAME,
                             description=self.DESCRIPTION,
                             filter=self.FILTER)
        gax_api = _GAXMetricsAPI(_update_log_metric_response=response)
        api = self._make_one(gax_api, None)

        api.metric_update(
            self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION)

        metric_name, metric, options = (
            gax_api._update_log_metric_called_with)
        self.assertEqual(metric_name, self.METRIC_PATH)
        self.assertIsInstance(metric, LogMetric)
        self.assertEqual(metric.name, self.METRIC_PATH)
        self.assertEqual(metric.filter, self.FILTER)
        self.assertEqual(metric.description, self.DESCRIPTION)
        self.assertIsNone(options)

    def test_metric_delete_error(self):
        from google.gax.errors import GaxError

        gax_api = _GAXMetricsAPI(_random_gax_error=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(GaxError):
            api.metric_delete(self.PROJECT, self.METRIC_NAME)

    def test_metric_delete_miss(self):
        from google.cloud.exceptions import NotFound

        gax_api = _GAXMetricsAPI(_log_metric_not_found=True)
        api = self._make_one(gax_api, None)

        with self.assertRaises(NotFound):
            api.metric_delete(self.PROJECT, self.METRIC_NAME)

    def test_metric_delete_hit(self):
        gax_api = _GAXMetricsAPI()
        api = self._make_one(gax_api, None)

        api.metric_delete(self.PROJECT, self.METRIC_NAME)

        metric_name, options = gax_api._delete_log_metric_called_with
        self.assertEqual(metric_name, self.METRIC_PATH)
        self.assertIsNone(options)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_make_gax_logging_api(unittest.TestCase):

    def _call_fut(self, client):
        from google.cloud.logging._gax import make_gax_logging_api

        return make_gax_logging_api(client)

    def test_it(self):
        from google.cloud.logging import __version__
        from google.cloud.logging._gax import _LoggingAPI
        from google.cloud.logging._gax import DEFAULT_USER_AGENT

        creds = object()
        client = mock.Mock(_credentials=creds, spec=['_credentials'])
        channels = []
        channel_args = []
        generated_api_kwargs = []
        channel_obj = object()
        generated = object()

        def make_channel(*args):
            channel_args.append(args)
            return channel_obj

        def generated_api(channel=None, **kwargs):
            channels.append(channel)
            generated_api_kwargs.append(kwargs)
            return generated

        host = 'foo.apis.invalid'
        generated_api.SERVICE_ADDRESS = host

        patch = mock.patch.multiple(
            'google.cloud.logging._gax',
            LoggingServiceV2Client=generated_api,
            make_secure_channel=make_channel)
        with patch:
            logging_api = self._call_fut(client)

        self.assertEqual(channels, [channel_obj])
        self.assertEqual(channel_args,
                         [(creds, DEFAULT_USER_AGENT, host)])

        self.assertEqual(len(generated_api_kwargs), 1)
        self.assertEqual(generated_api_kwargs[0]['lib_name'], 'gccl')
        self.assertEqual(generated_api_kwargs[0]['lib_version'], __version__)

        self.assertIsInstance(logging_api, _LoggingAPI)
        self.assertIs(logging_api._gax_api, generated)
        self.assertIs(logging_api._client, client)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_make_gax_metrics_api(unittest.TestCase):

    def _call_fut(self, client):
        from google.cloud.logging._gax import make_gax_metrics_api

        return make_gax_metrics_api(client)

    def test_it(self):
        from google.cloud.logging import __version__
        from google.cloud.logging._gax import _MetricsAPI
        from google.cloud.logging._gax import DEFAULT_USER_AGENT

        creds = object()
        client = mock.Mock(_credentials=creds, spec=['_credentials'])
        channels = []
        channel_args = []
        generated_api_kwargs = []
        channel_obj = object()
        generated = object()

        def make_channel(*args):
            channel_args.append(args)
            return channel_obj

        def generated_api(channel=None, **kwargs):
            channels.append(channel)
            generated_api_kwargs.append(kwargs)
            return generated

        host = 'foo.apis.invalid'
        generated_api.SERVICE_ADDRESS = host

        patch = mock.patch.multiple(
            'google.cloud.logging._gax',
            MetricsServiceV2Client=generated_api,
            make_secure_channel=make_channel)
        with patch:
            metrics_api = self._call_fut(client)

        self.assertEqual(channels, [channel_obj])
        self.assertEqual(channel_args,
                         [(creds, DEFAULT_USER_AGENT, host)])

        self.assertEqual(len(generated_api_kwargs), 1)
        self.assertEqual(generated_api_kwargs[0]['lib_name'], 'gccl')
        self.assertEqual(generated_api_kwargs[0]['lib_version'], __version__)

        self.assertIsInstance(metrics_api, _MetricsAPI)
        self.assertIs(metrics_api._gax_api, generated)
        self.assertIs(metrics_api._client, client)

@unittest.skipUnless(_HAVE_GAX, 'No gax-python')
class Test_make_gax_sinks_api(unittest.TestCase):

    def _call_fut(self, client):
        from google.cloud.logging._gax import make_gax_sinks_api

        return make_gax_sinks_api(client)

    def test_it(self):
        from google.cloud.logging import __version__
        from google.cloud.logging._gax import _SinksAPI
        from google.cloud.logging._gax import DEFAULT_USER_AGENT

        creds = object()
        client = mock.Mock(_credentials=creds, spec=['_credentials'])
        channels = []
        channel_args = []
        generated_api_kwargs = []
        channel_obj = object()
        generated = object()

        def make_channel(*args):
            channel_args.append(args)
            return channel_obj

        def generated_api(channel=None, **kwargs):
            channels.append(channel)
            generated_api_kwargs.append(kwargs)
            return generated

        host = 'foo.apis.invalid'
        generated_api.SERVICE_ADDRESS = host

        patch = mock.patch.multiple(
            'google.cloud.logging._gax',
            ConfigServiceV2Client=generated_api,
            make_secure_channel=make_channel)
        with patch:
            sinks_api = self._call_fut(client)

        self.assertEqual(channels, [channel_obj])
        self.assertEqual(channel_args,
                         [(creds, DEFAULT_USER_AGENT, host)])

        self.assertEqual(len(generated_api_kwargs), 1)
        self.assertEqual(generated_api_kwargs[0]['lib_name'], 'gccl')
        self.assertEqual(generated_api_kwargs[0]['lib_version'], __version__)

        self.assertIsInstance(sinks_api, _SinksAPI)
        self.assertIs(sinks_api._gax_api, generated)
        self.assertIs(sinks_api._client, client)

class _GAXLoggingAPI(_GAXBaseAPI):

    _delete_not_found = False

    def list_log_entries(
            self, resource_names, project_ids, filter_,
            order_by, page_size, options):
        self._list_log_entries_called_with = (
            resource_names, project_ids, filter_,
            order_by, page_size, options)
        return self._list_log_entries_response

    def write_log_entries(self, entries, log_name, resource, labels,
                          partial_success, options):
        self._write_log_entries_called_with = (
            entries, log_name, resource, labels, partial_success, options)

    def delete_log(self, log_name, options):
        from google.gax.errors import GaxError

        self._delete_log_called_with = log_name, options
        if self._random_gax_error:
            raise GaxError('error')
        if self._delete_not_found:
            raise GaxError('notfound', self._make_grpc_not_found())

class _GAXSinksAPI(_GAXBaseAPI):

    _create_sink_conflict = False
    _sink_not_found = False

    def list_sinks(self, parent, page_size, options):
        self._list_sinks_called_with = parent, page_size, options
        return self._list_sinks_response

    def create_sink(self, parent, sink, options):
        from google.gax.errors import GaxError

        self._create_sink_called_with = parent, sink, options
        if self._random_gax_error:
            raise GaxError('error')
        if self._create_sink_conflict:
            raise GaxError('conflict', self._make_grpc_failed_precondition())

    def get_sink(self, sink_name, options):
        from google.gax.errors import GaxError

        self._get_sink_called_with = sink_name, options
        if self._random_gax_error:
            raise GaxError('error')
        try:
            return self._get_sink_response
        except AttributeError:
            raise GaxError('notfound', self._make_grpc_not_found())

    def update_sink(self, sink_name, sink, options=None):
        from google.gax.errors import GaxError

        self._update_sink_called_with = sink_name, sink, options
        if self._random_gax_error:
            raise GaxError('error')
        try:
            return self._update_sink_response
        except AttributeError:
            raise GaxError('notfound', self._make_grpc_not_found())

    def delete_sink(self, sink_name, options=None):
        from google.gax.errors import GaxError

        self._delete_sink_called_with = sink_name, options
        if self._random_gax_error:
            raise GaxError('error')
        if self._sink_not_found:
            raise GaxError('notfound', self._make_grpc_not_found())

class _GAXMetricsAPI(_GAXBaseAPI):

    _create_log_metric_conflict = False
    _log_metric_not_found = False

    def list_log_metrics(self, parent, page_size, options):
        self._list_log_metrics_called_with = parent, page_size, options
        return self._list_log_metrics_response

    def create_log_metric(self, parent, metric, options):
        from google.gax.errors import GaxError

        self._create_log_metric_called_with = parent, metric, options
        if self._random_gax_error:
            raise GaxError('error')
        if self._create_log_metric_conflict:
            raise GaxError('conflict', self._make_grpc_failed_precondition())

    def get_log_metric(self, metric_name, options):
        from google.gax.errors import GaxError

        self._get_log_metric_called_with = metric_name, options
        if self._random_gax_error:
            raise GaxError('error')
        try:
            return self._get_log_metric_response
        except AttributeError:
            raise GaxError('notfound', self._make_grpc_not_found())

    def update_log_metric(self, metric_name, metric, options=None):
        from google.gax.errors import GaxError

        self._update_log_metric_called_with = metric_name, metric, options
        if self._random_gax_error:
            raise GaxError('error')
        try:
            return self._update_log_metric_response
        except AttributeError:
            raise GaxError('notfound', self._make_grpc_not_found())

    def delete_log_metric(self, metric_name, options=None):
        from google.gax.errors import GaxError

        self._delete_log_metric_called_with = metric_name, options
        if self._random_gax_error:
            raise GaxError('error')
        if self._log_metric_not_found:
            raise GaxError('notfound', self._make_grpc_not_found())


text:
Before anything else, thank you. Thank you for taking some of your precious time helping this project move forward.

**Table of contents**

- [Contributing to Js2coffee](#reporting)
  - [Creating a Bug Report](#bugreport)
  - [Behaviour of CoffeeScript](#coffeeScript)
  - [Creating a Pull Request](#pullRequest)
  - [Setting Up a Development Environment](#dev)

## Contributing to Js2coffee
If you've found a bug in Js2coffee, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.

## Creating a Bug Report
If you've found a problem in Js2coffee use the [Issue Tracker](https://github.com/rstacruz/js2coffee/issues). If you find no issue addressing it you can add a new one.

With your bug report, specify:

- **what you did**
- **what happened**
- **what you expected**
- **did you do that in the online editor**
- or did you installed js2coffee via npm, if yes:
- your Js2coffee version `js2coffee -v` or look it up in the package.json
- your node version `node -v`
- your npm version `npm -v`
- your OS, architecture and version

If you've found multiple bugs, which are not reported already, you should create **one issue per bug**.

## Behaviour of CoffeeScript
Remind that CoffeeScript itself has some special restrictions [[1]](http://https://github.com/michaelficarra/CoffeeScriptRedux/wiki/Intentional-Deviation-From-jashkenas-coffee-script)[[2]](http://ceronman.com/2012-09-17/coffeescript-less-typing-bad-readability) and also bugs.
So if your want to report a bug, ensure that it's neither a feature nor a bug of CoffeeScript.

## Creating a Pull Request
As a next step beyond reporting issues, you can help the project resolve existing issues. If you check the Everyone's Issues list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:

For starters, it helps just to **verify bug reports**. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.

If something is very vague, can you help squash it down into something specific? Maybe you can **provide additional information** to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.

Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to **write code** to fix those bugs - whether you end up writing the code yourself or not.

If you need help to create a pull request, read this github help guide: [Creating a pull request](https://help.github.com/articles/creating-a-pull-request)

## Setting Up a Development Environment

1. Fork this repository by clicking on the fork button
2. Clone the forked repository to your machine:
  `git clone https://github.com/<USERNAME>/js2coffee.git`
3. Jump into the new directory `cd js2coffee` and do a `npm install`

Since Js2coffee is written in CoffeeScript, you need to compile it into JavaScript. This project uses DocPad for the build process.
You can use these commands for development:

- `npm run-script compile` - compile and test
- `npm test` - only run the test
- `npm run-script watch` - compile and test changes as they happen

These commands are defined in the `package.json` and those commands in turn are defined in the Cakefile. You can also use `cake` which comes with CoffeeScript.

redpajama_set_name: RedPajamaGithub


text:
use std::{fs::File, io::Write, time::Duration};

use encryption_export::{
    create_backend, DataKeyManager, DataKeyManagerArgs, EncryptionConfig, FileConfig,
    MasterKeyConfig, Result,
};
use kvproto::encryptionpb::EncryptionMethod;
use tikv_util::config::ReadableDuration;

pub fn create_test_key_file(path: &str) {
    let mut file = File::create(path).unwrap();
    file.write_all(b"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\n")
        .unwrap();
}

fn new_test_file_master_key(tmp: &tempfile::TempDir) -> MasterKeyConfig {
    let key_path = tmp.path().join("test_key").to_str().unwrap().to_owned();
    create_test_key_file(&key_path);
    MasterKeyConfig::File {
        config: FileConfig { path: key_path },
    }
}

pub fn new_file_security_config(dir: &tempfile::TempDir) -> EncryptionConfig {
    let master_key_cfg = new_test_file_master_key(dir);
    EncryptionConfig {
        data_encryption_method: EncryptionMethod::Aes256Ctr,
        data_key_rotation_period: ReadableDuration::days(7),
        enable_file_dictionary_log: true,
        file_dictionary_rewrite_threshold: 100000,
        master_key: master_key_cfg.clone(),
        previous_master_key: master_key_cfg,
    }
}

pub fn new_test_key_manager(
    tmp_dir: &tempfile::TempDir,
    method: Option<EncryptionMethod>,
    master_key: Option<MasterKeyConfig>,
    previous_master_key: Option<MasterKeyConfig>,
) -> Result<Option<DataKeyManager>> {
    let default_config = new_test_file_master_key(tmp_dir);
    let master_key = master_key.unwrap_or_else(|| default_config.clone());
    let previous_master_key = previous_master_key.unwrap_or(default_config);
    DataKeyManager::new(
        create_backend(&master_key)?,
        Box::new(move || create_backend(&previous_master_key)),
        DataKeyManagerArgs {
            method: method.unwrap_or(EncryptionMethod::Aes256Ctr),
            rotation_period: Duration::from_secs(60),
            enable_file_dictionary_log: true,
            file_dictionary_rewrite_threshold: 2,
            dict_path: tmp_dir.path().as_os_str().to_str().unwrap().to_string(),
        },
    )
}


text:
#include "tensorflow/core/summary/summary_db_writer.h"

#include "tensorflow/core/summary/schema.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/db/sqlite.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/event.pb.h"

namespace tensorflow {
namespace {

Tensor MakeScalarInt64(int64 x) {
  Tensor t(DT_INT64, TensorShape({}));
  t.scalar<int64>()() = x;
  return t;
}

class FakeClockEnv : public EnvWrapper {
 public:
  FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {}
  void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; }
  uint64 NowMicros() override { return current_millis_ * 1000; }
  uint64 NowSeconds() override { return current_millis_ * 1000; }

 private:
  uint64 current_millis_;
};

class SummaryDbWriterTest : public ::testing::Test {
 protected:
  void SetUp() override {
    TF_ASSERT_OK(Sqlite::Open(":memory:", SQLITE_OPEN_READWRITE, &db_));
    TF_ASSERT_OK(SetupTensorboardSqliteDb(db_));
  }

  void TearDown() override {
    if (writer_ != nullptr) {
      writer_->Unref();
      writer_ = nullptr;
    }
    db_->Unref();
    db_ = nullptr;
  }

  int64 QueryInt(const string& sql) {
    SqliteStatement stmt = db_->PrepareOrDie(sql);
    bool is_done;
    Status s = stmt.Step(&is_done);
    if (!s.ok() || is_done) {
      LOG(ERROR) << s << " due to " << sql;
      return -1;
    }
    return stmt.ColumnInt(0);
  }

  double QueryDouble(const string& sql) {
    SqliteStatement stmt = db_->PrepareOrDie(sql);
    bool is_done;
    Status s = stmt.Step(&is_done);
    if (!s.ok() || is_done) {
      LOG(ERROR) << s << " due to " << sql;
      return -1;
    }
    return stmt.ColumnDouble(0);
  }

  string QueryString(const string& sql) {
    SqliteStatement stmt = db_->PrepareOrDie(sql);
    bool is_done;
    Status s = stmt.Step(&is_done);
    if (!s.ok() || is_done) {
      LOG(ERROR) << s << " due to " << sql;
      return "MISSINGNO";
    }
    return stmt.ColumnString(0);
  }

  FakeClockEnv env_;
  Sqlite* db_ = nullptr;
  SummaryWriterInterface* writer_ = nullptr;
};

TEST_F(SummaryDbWriterTest, WriteHistogram_VerifyTensorValues) {
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "histtest", "test1", "user1", &env_,
                                     &writer_));
  int step = 0;
  std::unique_ptr<Event> e{new Event};
  e->set_step(step);
  e->set_wall_time(123);
  Summary::Value* s = e->mutable_summary()->add_value();
  s->set_tag("normal/myhisto");

  double dummy_value = 10.123;
  HistogramProto* proto = s->mutable_histo();
  proto->Clear();
  proto->set_min(dummy_value);
  proto->set_max(dummy_value);
  proto->set_num(dummy_value);
  proto->set_sum(dummy_value);
  proto->set_sum_squares(dummy_value);

  int size = 3;
  double bucket_limits[] = {-30.5, -10.5, -5.5};
  double bucket[] = {-10, 10, 20};
  for (int i = 0; i < size; i++) {
    proto->add_bucket_limit(bucket_limits[i]);
    proto->add_bucket(bucket[i]);
  }
  TF_ASSERT_OK(writer_->WriteEvent(std::move(e)));
  TF_ASSERT_OK(writer_->Flush());
  writer_->Unref();
  writer_ = nullptr;

  // TODO(nickfelt): implement QueryTensor() to encapsulate this
  // Verify the data
  string result = QueryString("SELECT data FROM Tensors");
  const double* val = reinterpret_cast<const double*>(result.data());
  double histarray[] = {std::numeric_limits<double>::min(),
                        -30.5,
                        -10,
                        -30.5,
                        -10.5,
                        10,
                        -10.5,
                        -5.5,
                        20};
  int histarray_size = 9;
  for (int i = 0; i < histarray_size; i++) {
    EXPECT_EQ(histarray[i], val[i]);
  }
}

TEST_F(SummaryDbWriterTest, NothingWritten_NoRowsCreated) {
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "mad-science", "train", "jart", &env_,
                                     &writer_));
  TF_ASSERT_OK(writer_->Flush());
  writer_->Unref();
  writer_ = nullptr;
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Ids"));
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Users"));
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Experiments"));
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Runs"));
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Tags"));
  EXPECT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Tensors"));
}

TEST_F(SummaryDbWriterTest, TensorsWritten_RowsGetInitialized) {
  SummaryMetadata metadata;
  metadata.set_display_name("display_name");
  metadata.set_summary_description("description");
  metadata.mutable_plugin_data()->set_plugin_name("plugin_name");
  metadata.mutable_plugin_data()->set_content("plugin_data");
  SummaryMetadata metadata_nope;
  metadata_nope.set_display_name("nope");
  metadata_nope.set_summary_description("nope");
  metadata_nope.mutable_plugin_data()->set_plugin_name("nope");
  metadata_nope.mutable_plugin_data()->set_content("nope");
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "mad-science", "train", "jart", &env_,
                                     &writer_));
  env_.AdvanceByMillis(23);
  TF_ASSERT_OK(writer_->WriteTensor(1, MakeScalarInt64(123LL), "taggy",
                                    metadata.SerializeAsString()));
  env_.AdvanceByMillis(23);
  TF_ASSERT_OK(writer_->WriteTensor(2, MakeScalarInt64(314LL), "taggy",
                                    metadata_nope.SerializeAsString()));
  TF_ASSERT_OK(writer_->Flush());

  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Users"));
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Experiments"));
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Runs"));
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Tags"));
  ASSERT_EQ(1000LL, QueryInt("SELECT COUNT(*) FROM Tensors"));

  int64 user_id = QueryInt("SELECT user_id FROM Users");
  int64 experiment_id = QueryInt("SELECT experiment_id FROM Experiments");
  int64 run_id = QueryInt("SELECT run_id FROM Runs");
  int64 tag_id = QueryInt("SELECT tag_id FROM Tags");
  EXPECT_LT(0LL, user_id);
  EXPECT_LT(0LL, experiment_id);
  EXPECT_LT(0LL, run_id);
  EXPECT_LT(0LL, tag_id);

  EXPECT_EQ("jart", QueryString("SELECT user_name FROM Users"));
  EXPECT_EQ(0.023, QueryDouble("SELECT inserted_time FROM Users"));

  EXPECT_EQ(user_id, QueryInt("SELECT user_id FROM Experiments"));
  EXPECT_EQ("mad-science",
            QueryString("SELECT experiment_name FROM Experiments"));
  EXPECT_EQ(0.023, QueryDouble("SELECT inserted_time FROM Experiments"));

  EXPECT_EQ(experiment_id, QueryInt("SELECT experiment_id FROM Runs"));
  EXPECT_EQ("train", QueryString("SELECT run_name FROM Runs"));
  EXPECT_EQ(0.023, QueryDouble("SELECT inserted_time FROM Runs"));

  EXPECT_EQ(run_id, QueryInt("SELECT run_id FROM Tags"));
  EXPECT_EQ("taggy", QueryString("SELECT tag_name FROM Tags"));
  EXPECT_EQ(0.023, QueryDouble("SELECT inserted_time FROM Tags"));

  EXPECT_EQ("display_name", QueryString("SELECT display_name FROM Tags"));
  EXPECT_EQ("plugin_name", QueryString("SELECT plugin_name FROM Tags"));
  EXPECT_EQ("plugin_data", QueryString("SELECT plugin_data FROM Tags"));
  EXPECT_EQ("description", QueryString("SELECT description FROM Descriptions"));

  EXPECT_EQ(tag_id, QueryInt("SELECT series FROM Tensors WHERE step = 1"));
  EXPECT_EQ(0.023,
            QueryDouble("SELECT computed_time FROM Tensors WHERE step = 1"));

  EXPECT_EQ(tag_id, QueryInt("SELECT series FROM Tensors WHERE step = 2"));
  EXPECT_EQ(0.046,
            QueryDouble("SELECT computed_time FROM Tensors WHERE step = 2"));
}

TEST_F(SummaryDbWriterTest, EmptyParentNames_NoParentsCreated) {
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "", "", "", &env_, &writer_));
  TF_ASSERT_OK(writer_->WriteTensor(1, MakeScalarInt64(123LL), "taggy", ""));
  TF_ASSERT_OK(writer_->Flush());
  ASSERT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Users"));
  ASSERT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Experiments"));
  ASSERT_EQ(0LL, QueryInt("SELECT COUNT(*) FROM Runs"));
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Tags"));
  ASSERT_EQ(1000LL, QueryInt("SELECT COUNT(*) FROM Tensors"));
}

TEST_F(SummaryDbWriterTest, WriteEvent_Scalar) {
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "", "", "", &env_, &writer_));
  std::unique_ptr<Event> e{new Event};
  e->set_step(7);
  e->set_wall_time(123.456);
  Summary::Value* s = e->mutable_summary()->add_value();
  s->set_tag("π");
  s->set_simple_value(3.14f);
  s = e->mutable_summary()->add_value();
  s->set_tag("φ");
  s->set_simple_value(1.61f);
  TF_ASSERT_OK(writer_->WriteEvent(std::move(e)));
  TF_ASSERT_OK(writer_->Flush());
  ASSERT_EQ(2LL, QueryInt("SELECT COUNT(*) FROM Tags"));
  ASSERT_EQ(2000LL, QueryInt("SELECT COUNT(*) FROM Tensors"));
  int64 tag1_id = QueryInt("SELECT tag_id FROM Tags WHERE tag_name = 'π'");
  int64 tag2_id = QueryInt("SELECT tag_id FROM Tags WHERE tag_name = 'φ'");
  EXPECT_GT(tag1_id, 0LL);
  EXPECT_GT(tag2_id, 0LL);
  EXPECT_EQ(123.456, QueryDouble(strings::StrCat(
                         "SELECT computed_time FROM Tensors WHERE series = ",
                         tag1_id, " AND step = 7")));
  EXPECT_EQ(123.456, QueryDouble(strings::StrCat(
                         "SELECT computed_time FROM Tensors WHERE series = ",
                         tag2_id, " AND step = 7")));
}

TEST_F(SummaryDbWriterTest, WriteGraph) {
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "", "R", "", &env_, &writer_));
  env_.AdvanceByMillis(23);
  GraphDef graph;
  graph.mutable_library()->add_gradient()->set_function_name("funk");
  NodeDef* node = graph.add_node();
  node->set_name("x");
  node->set_op("Placeholder");
  node = graph.add_node();
  node->set_name("y");
  node->set_op("Placeholder");
  node = graph.add_node();
  node->set_name("z");
  node->set_op("Love");
  node = graph.add_node();
  node->set_name("+");
  node->set_op("Add");
  node->add_input("x");
  node->add_input("y");
  node->add_input("^z");
  node->set_device("tpu/lol");
  std::unique_ptr<Event> e{new Event};
  graph.SerializeToString(e->mutable_graph_def());
  TF_ASSERT_OK(writer_->WriteEvent(std::move(e)));
  TF_ASSERT_OK(writer_->Flush());
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Runs"));
  ASSERT_EQ(1LL, QueryInt("SELECT COUNT(*) FROM Graphs"));
  ASSERT_EQ(4LL, QueryInt("SELECT COUNT(*) FROM Nodes"));
  ASSERT_EQ(3LL, QueryInt("SELECT COUNT(*) FROM NodeInputs"));

  ASSERT_EQ(QueryInt("SELECT run_id FROM Runs"),
            QueryInt("SELECT run_id FROM Graphs"));

  int64 graph_id = QueryInt("SELECT graph_id FROM Graphs");
  EXPECT_GT(graph_id, 0LL);
  EXPECT_EQ(0.023, QueryDouble("SELECT inserted_time FROM Graphs"));

  GraphDef graph2;
  graph2.ParseFromString(QueryString("SELECT graph_def FROM Graphs"));
  EXPECT_EQ(0, graph2.node_size());
  EXPECT_EQ("funk", graph2.library().gradient(0).function_name());

  EXPECT_EQ("x", QueryString("SELECT node_name FROM Nodes WHERE node_id = 0"));
  EXPECT_EQ("y", QueryString("SELECT node_name FROM Nodes WHERE node_id = 1"));
  EXPECT_EQ("z", QueryString("SELECT node_name FROM Nodes WHERE node_id = 2"));
  EXPECT_EQ("+", QueryString("SELECT node_name FROM Nodes WHERE node_id = 3"));

  EXPECT_EQ("Placeholder",
            QueryString("SELECT op FROM Nodes WHERE node_id = 0"));
  EXPECT_EQ("Placeholder",
            QueryString("SELECT op FROM Nodes WHERE node_id = 1"));
  EXPECT_EQ("Love", QueryString("SELECT op FROM Nodes WHERE node_id = 2"));
  EXPECT_EQ("Add", QueryString("SELECT op FROM Nodes WHERE node_id = 3"));

  EXPECT_EQ("", QueryString("SELECT device FROM Nodes WHERE node_id = 0"));
  EXPECT_EQ("", QueryString("SELECT device FROM Nodes WHERE node_id = 1"));
  EXPECT_EQ("", QueryString("SELECT device FROM Nodes WHERE node_id = 2"));
  EXPECT_EQ("tpu/lol",
            QueryString("SELECT device FROM Nodes WHERE node_id = 3"));

  EXPECT_EQ(graph_id,
            QueryInt("SELECT graph_id FROM NodeInputs WHERE idx = 0"));
  EXPECT_EQ(graph_id,
            QueryInt("SELECT graph_id FROM NodeInputs WHERE idx = 1"));
  EXPECT_EQ(graph_id,
            QueryInt("SELECT graph_id FROM NodeInputs WHERE idx = 2"));

  EXPECT_EQ(3LL, QueryInt("SELECT node_id FROM NodeInputs WHERE idx = 0"));
  EXPECT_EQ(3LL, QueryInt("SELECT node_id FROM NodeInputs WHERE idx = 1"));
  EXPECT_EQ(3LL, QueryInt("SELECT node_id FROM NodeInputs WHERE idx = 2"));

  EXPECT_EQ(0LL,
            QueryInt("SELECT input_node_id FROM NodeInputs WHERE idx = 0"));
  EXPECT_EQ(1LL,
            QueryInt("SELECT input_node_id FROM NodeInputs WHERE idx = 1"));
  EXPECT_EQ(2LL,
            QueryInt("SELECT input_node_id FROM NodeInputs WHERE idx = 2"));

  EXPECT_EQ(0LL, QueryInt("SELECT is_control FROM NodeInputs WHERE idx = 0"));
  EXPECT_EQ(0LL, QueryInt("SELECT is_control FROM NodeInputs WHERE idx = 1"));
  EXPECT_EQ(1LL, QueryInt("SELECT is_control FROM NodeInputs WHERE idx = 2"));
}

TEST_F(SummaryDbWriterTest, UsesIdsTable) {
  SummaryMetadata metadata;
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "mad-science", "train", "jart", &env_,
                                     &writer_));
  env_.AdvanceByMillis(23);
  TF_ASSERT_OK(writer_->WriteTensor(1, MakeScalarInt64(123LL), "taggy",
                                    metadata.SerializeAsString()));
  TF_ASSERT_OK(writer_->Flush());
  ASSERT_EQ(4LL, QueryInt("SELECT COUNT(*) FROM Ids"));
  EXPECT_EQ(4LL, QueryInt(strings::StrCat(
                     "SELECT COUNT(*) FROM Ids WHERE id IN (",
                     QueryInt("SELECT user_id FROM Users"), ", ",
                     QueryInt("SELECT experiment_id FROM Experiments"), ", ",
                     QueryInt("SELECT run_id FROM Runs"), ", ",
                     QueryInt("SELECT tag_id FROM Tags"), ")")));
}

TEST_F(SummaryDbWriterTest, SetsRunFinishedTime) {
  SummaryMetadata metadata;
  TF_ASSERT_OK(CreateSummaryDbWriter(db_, "mad-science", "train", "jart", &env_,
                                     &writer_));
  env_.AdvanceByMillis(23);
  TF_ASSERT_OK(writer_->WriteTensor(1, MakeScalarInt64(123LL), "taggy",
                                    metadata.SerializeAsString()));
  TF_ASSERT_OK(writer_->Flush());
  ASSERT_EQ(0.023, QueryDouble("SELECT started_time FROM Runs"));
  ASSERT_EQ(0.0, QueryDouble("SELECT finished_time FROM Runs"));
  env_.AdvanceByMillis(23);
  writer_->Unref();
  writer_ = nullptr;
  ASSERT_EQ(0.023, QueryDouble("SELECT started_time FROM Runs"));
  ASSERT_EQ(0.046, QueryDouble("SELECT finished_time FROM Runs"));
}

}  // namespace
}  // namespace tensorflow


text:
<?xml version='1.0' encoding='UTF-8'?>
<xmcda:XMCDA xmlns:xmcda='http://www.decision-deck.org/2012/XMCDA-2.2.1'
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xsi:schemaLocation='http://www.decision-deck.org/2012/XMCDA-2.2.1 http://www.decision-deck.org/xmcda/_downloads/XMCDA-2.2.1.xsd'>
<alternativesValues>
  <alternativeValue>
    <alternativeID>A</alternativeID>
    <value>
      <real>0.7</real>
    </value>
  </alternativeValue>
  <alternativeValue>
    <alternativeID>B</alternativeID>
    <value>
      <real>0.8</real>
    </value>
  </alternativeValue>
  <alternativeValue>
    <alternativeID>C</alternativeID>
    <value>
      <real>0.6</real>
    </value>
  </alternativeValue>
  <alternativeValue>
    <alternativeID>pMG</alternativeID>
    <value>
      <real>0.7</real>
    </value>
  </alternativeValue>
  <alternativeValue>
    <alternativeID>pBM</alternativeID>
    <value>
      <real>0.4</real>
    </value>
  </alternativeValue>
</alternativesValues>
</xmcda:XMCDA>


text:
using System;
using System.Collections.Generic;

namespace Basement.OEPFramework.Futures.Coroutine
{
    public class CoroutineFuture<T1> : CoroutineFutureBase
    {
        private Func<T1, IEnumerator<IFuture>> _func;

        private readonly T1 param1;

        public CoroutineFuture(Func<T1, IEnumerator<IFuture>> func, T1 param1)
        {
            this.param1 = param1;
            _func = func;
        }

        protected override void OnRun()
        {
            enumerator = _func(param1);
            Next(null);
        }

        protected override void OnComplete()
        {
            base.OnComplete();
            _func = null;
        }
    }
}


text:
@interface CJWProgressHUD : MBProgressHUD

+(CJWProgressHUD *)showTemporaryAt:(UIView *)view text:(NSString *)text;
+(CJWProgressHUD *)showDefaultAt:(UIView *)view text:(NSString *)text;

@end

@interface UIView (CJWProgressHUD)

-(void)showHUDwith:(NSString *)text;
-(void)hideHUD;
-(void)showTemporary:(NSString *)text;
-(void)hideAllHUD;
-(void)showLoading;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Diagnostics.Runtime;
using Raven.Client.Indexes;

namespace DumpMemorySummarizer.Indexes
{
	public class GcRootsCountByKindAndType : AbstractIndexCreationTask<GcRoot, GcRootsCountByKindAndType.RootKindAndTypeResult>
	{
		public class RootKindAndTypeResult
		{
			public GCRootKind Kind { get; set; }

			public string Type { get; set; }

			public int Count { get; set; }
		}

		public GcRootsCountByKindAndType()
		{
			Map = docs => from root in docs
				select new
				{
					Kind = root.RootKind,
					Type = root.TypeName,
					Count = 1
				};

			Reduce = results => from result in results
				group result by new { result.Kind, result.Type }
				into g
				select new
				{
					g.Key.Kind, g.Key.Type,
					Count = g.Sum(x => x.Count)
				};

		}
	}
}


text:
echo Getting latest bits...
git pull

echo "Copying login.sh file to root..."
cp login.sh ~/

echo Starting Mini Mobile Device Lab Client

cd PiLab

echo ""
echo Starting Monitor...
forever start monitor.js

echo ""
echo Starting ADB Server with sudo
sudo adb start-server

# echo ""
# echo Installing and updating node modules
# npm install

echo ""
echo Starting MMDL Client
node simple.js

echo ""
echo Rebooting simple in 5 seconds
sleep 5
sudo reboot


text:
package com.google.cloud.dataflow.sdk.coders;

import com.google.cloud.dataflow.sdk.values.KV;
import com.google.common.collect.ImmutableMap;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

/**
 * Test case for {@link KvCoder}.
 */
@RunWith(JUnit4.class)
public class KvCoderTest {

  private static final Map<Coder<?>, Iterable<?>> TEST_DATA =
      new ImmutableMap.Builder<Coder<?>, Iterable<?>>()
      .put(VarIntCoder.of(),
          Arrays.asList(-1, 0, 1, 13, Integer.MAX_VALUE, Integer.MIN_VALUE))
      .put(BigEndianLongCoder.of(),
          Arrays.asList(-1L, 0L, 1L, 13L, Long.MAX_VALUE, Long.MIN_VALUE))
      .put(StringUtf8Coder.of(),
          Arrays.asList("", "hello", "goodbye", "1"))
      .put(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()),
          Arrays.asList(KV.of("", -1), KV.of("hello", 0), KV.of("goodbye", Integer.MAX_VALUE)))
      .put(ListCoder.of(VarLongCoder.of()),
          Arrays.asList(
              Arrays.asList(1L, 2L, 3L),
              Collections.emptyList()))
       .build();

  @Test
  public void testDecodeEncodeEqual() throws Exception {
    for (Map.Entry<Coder<?>, Iterable<?>> entry : TEST_DATA.entrySet()) {
      // The coder and corresponding values must be the same type.
      // If someone messes this up in the above test data, the test
      // will fail anyhow (unless the coder magically works on data
      // it does not understand).
      @SuppressWarnings("unchecked")
      Coder<Object> coder = (Coder<Object>) entry.getKey();
      Iterable<?> values = entry.getValue();
      for (Object value : values) {
        CoderProperties.coderDecodeEncodeEqual(coder, value);
      }
    }
  }
}


text:
'use strict';

angular.module('module.core').config(function($stateProvider, USER_ROLES) {
  $stateProvider
    .state('app', {
      abstract: true,
      url: '/app',
      templateUrl: 'modules/core/views/layouts/app.html',
      controller: 'AppCtrl as app',
      data: {
        authorizedRoles: [USER_ROLES.registered],
        authRequired: true
      }
    })
    .state('page', {
      abstract: true,
      url: '/page',
      templateUrl: 'modules/core/views/layouts/page.html',
      controller: 'PageCtrl as page',
      data: {
        authorizedRoles: [USER_ROLES.all],
        authRequired: false
      }
    })
    .state('page.home', {
      url: '/home',
      templateUrl: 'modules/core/views/home.html'
    })
    .state('page.about', {
      url: '/about',
      templateUrl: 'modules/core/views/about.html'
    })
    .state('page.architecture', {
      url: '/architecture',
      templateUrl: 'modules/core/views/architecture.html'
    })
});


text:
/* SPDX-License-Identifier: Apache-2.0 */

/* This file is a temporary workaround for mapping of the generated information
 * to the current driver definitions.  This will be removed when the drivers
 * are modified to handle the generated information, or the mapping of
 * generated data matches the driver definitions.
 */

/* SoC level DTS fixup file */

#define DT_NUM_IRQ_PRIO_BITS               DT_ARM_V7M_NVIC_E000E100_ARM_NUM_IRQ_PRIORITY_BITS

#define DT_UART_MSP432P4XX_NAME            DT_TI_MSP432P4XX_UART_40001000_LABEL
#define DT_UART_MSP432P4XX_BASE_ADDRESS    DT_TI_MSP432P4XX_UART_40001000_BASE_ADDRESS
#define DT_UART_MSP432P4XX_BAUD_RATE       DT_TI_MSP432P4XX_UART_40001000_CURRENT_SPEED

/* End of SoC Level DTS fixup file */


text:
<?php
$i=1;
$aux=$this->mis_funciones->limpia($cuestionarios);//aux contiene los cuestionarios: cuestionario1 cuestionario2 ... sin repetir

if($cuestRespondidos!=null) {
    $limpio = $this->mis_funciones->limpiaTres($cuestRespondidos);
    foreach ($aux as $cuestionario) {?>
        <?php if (in_array($cuestionario, $limpio)) { ?>

Desafío <?php echo $i ?>

                <?php $numero = intval(preg_replace('/[^0-9]+/', '', $cuestionario), 10); ?>

                        <img class="cuestionario center-block borde img-circle zoom tamano-cuest"
                            id="<?php echo $cuestionario ?>"
                            alt="<?php echo $cuestionario ?>"
                            src="<?php echo base_url() . "public/images/icons/test/testHecho.png" ?>"
                            />

        <?php }
        else { ?>

Desafío <?php echo $i ?>

                <?php $numero = intval(preg_replace('/[^0-9]+/', '', $cuestionario), 10); ?>
                        <a href="<?php echo base_url() . "aplicacion/cuestionariofrutaverdura/".$numero?>">

                                <img class="cuestionario center-block img-circle borde zoom cuest tamano-cuest"
                                    id="<?php echo $cuestionario ?>"
                                     alt="<?php echo $cuestionario ?>"
                                    src="<?php echo base_url() . "public/images/icons/test/test.png" ?>"/>

        <?php }
        $i++;
    }
}
else{?>
    <?php foreach($aux as $cuestionario) {?>

Desafío <?php echo $i ?>

            <?php $numero = intval(preg_replace('/[^0-9]+/', '', $cuestionario), 10); ?>
            <a href="<?php echo base_url() . "aplicacion/cuestionariofrutaverdura/".$numero?>">

                    <img class="cuestionario center-block img-circle borde zoom cuest tamano-cuest"
                        id="<?php echo $cuestionario ?>"
                         alt="<?php echo $cuestionario ?>"
                        src="<?php echo base_url() . "public/images/icons/test/test.png" ?>"/>

        <?php
        $i++;
    }?>
<?php }?>


text:
/*global App */

'use strict';
App.module('Base.Views.Movies.Table', function (Table, App, Backbone, Marionette, $) {

  Table.Movie = Marionette.ItemView.extend({
    template: 'movies/table/movie',

    tagName: "tr",

    events:{
      'click td': 'tdClicked'
    },

    tdClicked: function(e) {
      var jTd = $(e.target);
      var jTr = jTd.parent();

      // the ID is on the first column
      var id = jTr.find('td:eq(0)').data('id');

      App.router.navigate('movies/' + id, {trigger: true});
    },

  });

});


text:
SELECT c.id, COUNT(*) AS 'total_messages' FROM chats AS c
INNER JOIN messages AS m
ON c.id = m.chat_id
WHERE m.id < 90
GROUP BY c.id
ORDER BY total_messages DESC, c.id ASC
LIMIT 5;


text:
import { Component } from '@angular/core';
import { PageTwo } from '../page-two/page-two';

@Component({
  templateUrl: 'page-one.html'
})
export class PageOne {
  tabOne = PageTwo;
}


text:
// Copyright © 2010 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * 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.
//    * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 AUTHORS OF THE SOFTWARE 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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VirtualRadar.Interface
{
    /// <summary>
    /// The interface for objects that can generate audio.
    /// </summary>
    public interface IAudio
    {
        /// <summary>
        /// Gets a value indicating that the runtime supports audio.
        /// </summary>
        bool IsSupported { get; }

        /// <summary>
        /// Returns an in-memory WAV file of synthesised speech corresponding to the text passed across.
        /// </summary>
        /// <param name="speechText"></param>
        /// <returns></returns>
        byte[] SpeechToWavBytes(string speechText);
    }
}


text:
package org.apache.drill.common.exceptions;

import org.apache.drill.exec.proto.UserBitShared.DrillPBError;
import org.apache.drill.exec.proto.UserBitShared.DrillPBError.ErrorType;
import org.apache.drill.test.BaseTest;
import org.junit.Assert;
import org.junit.Test;

/**
 * Test various use cases when creating user exceptions
 */
public class TestUserException extends BaseTest {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
      .getLogger("--ignore.as.this.is.for.testing.exceptions--");

  private Exception wrap(UserException uex, int numWraps) {
    Exception ex = uex;
    for (int i = 0; i < numWraps; i++) {
      ex = new Exception("wrap #" + (i+1), ex);
    }

    return ex;
  }

  // make sure system exceptions are created properly
  @Test
  public void testBuildSystemException() {
    String message = "This is an exception";
    UserException uex = UserException.systemError(new Exception(new RuntimeException(message))).build(logger);

    Assert.assertTrue(uex.getOriginalMessage().contains(message));
    Assert.assertTrue(uex.getOriginalMessage().contains("RuntimeException"));

    DrillPBError error = uex.getOrCreatePBError(true);

    Assert.assertEquals(ErrorType.SYSTEM, error.getErrorType());
  }

  @Test
  public void testBuildUserExceptionWithMessage() {
    String message = "Test message";

    UserException uex = UserException.dataWriteError().message(message).build(logger);
    DrillPBError error = uex.getOrCreatePBError(false);

    Assert.assertEquals(ErrorType.DATA_WRITE, error.getErrorType());
    Assert.assertEquals(message, uex.getOriginalMessage());
  }

  @Test
  public void testBuildUserExceptionWithCause() {
    String message = "Test message";

    UserException uex = UserException.dataWriteError(new RuntimeException(message)).build(logger);
    DrillPBError error = uex.getOrCreatePBError(false);

    // cause message should be used
    Assert.assertEquals(ErrorType.DATA_WRITE, error.getErrorType());
    Assert.assertEquals(message, uex.getOriginalMessage());
  }

  @Test
  public void testBuildUserExceptionWithCauseAndMessage() {
    String messageA = "Test message A";
    String messageB = "Test message B";

    UserException uex = UserException.dataWriteError(new RuntimeException(messageA)).message(messageB).build(logger);
    DrillPBError error = uex.getOrCreatePBError(false);

    // passed message should override the cause message
    Assert.assertEquals(ErrorType.DATA_WRITE, error.getErrorType());
    Assert.assertFalse(error.getMessage().contains(messageA)); // messageA should not be part of the context
    Assert.assertEquals(messageB, uex.getOriginalMessage());
  }

  @Test
  public void testBuildUserExceptionWithUserExceptionCauseAndMessage() {
    String messageA = "Test message A";
    String messageB = "Test message B";

    UserException original = UserException.connectionError().message(messageA).build(logger);
    UserException uex = UserException.dataWriteError(wrap(original, 5)).message(messageB).build(logger);

    //builder should return the unwrapped original user exception and not build a new one
    Assert.assertEquals(original, uex);

    DrillPBError error = uex.getOrCreatePBError(false);
    Assert.assertEquals(messageA, uex.getOriginalMessage());
    Assert.assertFalse(error.getMessage().contains(messageB)); // messageB should not be part of the context
  }

  @Test
  public void testBuildUserExceptionWithFormattedMessage() {
    String format = "This is test #%d";

    UserException uex = UserException.connectionError().message(format, 5).build(logger);
    DrillPBError error = uex.getOrCreatePBError(false);

    Assert.assertEquals(ErrorType.CONNECTION, error.getErrorType());
    Assert.assertEquals(String.format(format, 5), uex.getOriginalMessage());
  }

  // make sure wrapped user exceptions are retrieved properly when calling ErrorHelper.wrap()
  @Test
  public void testWrapUserException() {
    UserException uex = UserException.dataReadError().message("this is a data read exception").build(logger);

    Exception wrapped = wrap(uex, 3);
    Assert.assertEquals(uex, UserException.systemError(wrapped).build(logger));
  }

}


text:
```sh
npm install --save react-google-maps # or
yarn add react-google-maps
```


text:
"""
Example to demonstrate simple transpiling and evaluating.
"""

from flexx.pyscript import js, py2js, evaljs, evalpy

def foo(a, b=1, *args):
    print(a)
    return b

# Create jscode object
jscode = js(foo)

# Print some info that we have on the code
print(jscode.name)
print(jscode.pycode)
print(jscode.jscode)

# Convert strings of Python to JS
print(py2js('isinstance(x, str)'))
print(py2js('isinstance(x, Bar)'))

# Evaluate js in nodejs
print(evaljs('10 * 10'))

# Evaluate PyScript in nodejs
print(evalpy('10**10'))


text:
INSERT INTO ${ohdsiSchema}.sec_role_permission(id, role_id, permission_id)
  SELECT NEXT VALUE FOR ${ohdsiSchema}.sec_role_permission_sequence, sr.id, sp.id
  FROM ${ohdsiSchema}.sec_permission SP, ${ohdsiSchema}.sec_role sr
  WHERE sp.value IN (
    'source:daimon:priority:get'
  ) AND sr.name IN ('public');


text:
package opbdevices.opbtimercounter;

import system.opb_device.*;

/**
 * The TCR0 register class.
 */
public final class tcr0 extends OPBRegister
{
 /** The OPB Timer/Counter device to which the register belongs. */
 private opbtimercounter device;
 /** The value of the register. */
 private int tcr0;

 /**
  * Instantiates a new TCR0 register.
  *
  * @param device the OPB Timer/Counter device to which the register will belong.
  */
 public tcr0(opbtimercounter device)
 {
  this.device = device;
 }

 // -----------------------------------
 // methods used to handle the register
 // -----------------------------------

 /**
  * Returns the current value of the register.
  *
  * @return the current value of the register.
  * @see system.opb_device.OPBRegister#get()
  */
 public final int get()
 {
  return tcr0;
 }

 /**
  * Sets the temporary value of the register.
  *
  * @param value the temporary value of the register.
  * @see system.opb_device.OPBRegister#put(int)
  */
 public final void put(int value)
 {
 }

 /**
  * Sets the value of the register.
  *
  * @param tcr0 the value of the register.
  */
 public final void putTCR0(int tcr0)
 {
  this.tcr0 = tcr0;
 }

 /**
  * Updates the register value after completion of the cycle. Checks if the register needs to be updated, if true uses temporary value to update the register value.
  *
  * @see system.opb_device.OPBRegister#update()
  */
 public final void update()
 {
 }

 // -------------------
 // methods auxiliaries
 // -------------------

 /**
  * Returns the OPB Timer/Counter device to which the register belongs.
  *
  * @return the OPB Timer/Counter device to which the register belongs.
  * @see system.opb_device.OPBRegister#getOPBDeviceClass()
  */
 public OPBDevice getOPBDeviceClass()
 {
  return device;
 }

 // -----------------------------------
 // methods used to display information
 // -----------------------------------

 /**
  * Returns the device name to which the register belongs.
  *
  * @return the device name to which the register belongs.
  * @see system.opb_device.OPBRegister#deviceName()
  */
 public String deviceName()
 {
  return device.toString();
 }

 /**
  * Returns the register name.
  *
  * @return the register name.
  * @see java.lang.Object#toString()
  */
 public String toString()
 {
  return "TCR0";
 }
}


text:
"""
File name: test.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2017-01-08
"""

DOMAINS = ['test.com']


text:
from Lexer.types import RESERVED, INT, BOOLEAN, ID

from ..combinators import Reserved, Tag, Rep, Opt
from ..AST.common import Enumeration

def keyword(kw):
    """
    Language keywords parsing (Reserved combinator with 'RESERVED' tag).
    """
    return Reserved(kw, RESERVED)

"""
Integers parsing (Tag combinator with 'INT' tag).
A Process combinator (^ operator) is also used to convert token into an integer.
"""
num = Tag(INT) ^ (lambda i: int(i))

def boolean_parser(flag):
    if flag == 'true':
        return 1
    elif flag == 'false':
        return 0

boolean = Tag(BOOLEAN) ^ boolean_parser

""" Identifiers parsing (Tag combinator with 'ID' tag). """
id = Tag(ID)

def enumeration(alternative_args_parser=None):
    """ Parsing enumeration statement. """
    def process(parsed_list):
        variables = []
        for parsed in parsed_list:
            (variable, _) = parsed
            variables.append(variable)
        return Enumeration(variables)
    if alternative_args_parser:
        args_parser = alternative_args_parser
    else:
        args_parser = id
    return Rep(args_parser + Opt(keyword(','))) ^ process


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind

Namespace Microsoft.CodeAnalysis.VisualBasic

    ''' <summary>
    ''' Causes lookups to assume that the given set of classes are having their
    ''' bases being resolved, so lookups should not check for base classes.
    ''' </summary>
    Friend NotInheritable Class BasesBeingResolvedBinder
        Inherits Binder

        Public Sub New(containingBinder As Binder, basesBeingResolved As BasesBeingResolved)
            MyBase.New(containingBinder, basesBeingResolved)
        End Sub

        Public Overrides Function CheckAccessibility(sym As Symbol,
                                                     <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
                                                     Optional accessThroughType As TypeSymbol = Nothing,
                                                     Optional basesBeingResolved As BasesBeingResolved = Nothing) As AccessCheckResult
            ' Accessibility checking may involve looking at base types. We need to pass this accessibility
            ' checking code any base classes currently being bound so we don't use those.

            ' add basesBeingResolved that was passed in to the ones stored in this binder.
            Dim currentBasesBeingResolved = Me.BasesBeingResolved()

            For Each inheritsBeingResolved In If(basesBeingResolved.InheritsBeingResolvedOpt, ConsList(Of TypeSymbol).Empty)
                currentBasesBeingResolved = currentBasesBeingResolved.PrependInheritsBeingResolved(inheritsBeingResolved)
            Next
            For Each implementsBeingResolved In If(basesBeingResolved.ImplementsBeingResolvedOpt, ConsList(Of TypeSymbol).Empty)
                currentBasesBeingResolved = currentBasesBeingResolved.PrependImplementsBeingResolved(implementsBeingResolved)
            Next

            Return m_containingBinder.CheckAccessibility(sym, useSiteInfo, accessThroughType, currentBasesBeingResolved)
        End Function
    End Class

    Friend Structure BasesBeingResolved
        Public ReadOnly InheritsBeingResolvedOpt As ConsList(Of TypeSymbol)
        Public ReadOnly ImplementsBeingResolvedOpt As ConsList(Of TypeSymbol)

        Public Shared ReadOnly Property Empty As BasesBeingResolved
            Get
                Return New BasesBeingResolved()
            End Get
        End Property

        Public Sub New(inheritsBeingResolved As ConsList(Of TypeSymbol), implementsBeingResolved As ConsList(Of TypeSymbol))
            Me.InheritsBeingResolvedOpt = inheritsBeingResolved
            Me.ImplementsBeingResolvedOpt = implementsBeingResolved
        End Sub

        Public Function PrependInheritsBeingResolved(symbol As TypeSymbol) As BasesBeingResolved
            Return New BasesBeingResolved(If(InheritsBeingResolvedOpt, ConsList(Of TypeSymbol).Empty).Prepend(symbol), ImplementsBeingResolvedOpt)
        End Function

        Public Function PrependImplementsBeingResolved(symbol As TypeSymbol) As BasesBeingResolved
            Return New BasesBeingResolved(InheritsBeingResolvedOpt, If(ImplementsBeingResolvedOpt, ConsList(Of TypeSymbol).Empty).Prepend(symbol))
        End Function
    End Structure

End Namespace


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>

<wicket:extend>
    <wicket:container wicket:id="layout">

            <form role="form" wicket:id="form">

                        Type
                        <select wicket:id="typeField" class="form-control"/>

                        Quantity
                        <input wicket:id="quantityField" type="text" class="form-control"/>

                        Length
                        <input wicket:id="lengthField" type="text" class="form-control"/>

                        Prefix
                        <input wicket:id="prefixField" type="text" class="form-control"/>

                        Suffix
                        <input wicket:id="suffixField" type="text" class="form-control"/>

                    <button wicket:id="generateButton" type="submit" class="btn btn-info">Generate</button>
                    Close

            </form>

    </wicket:container>
</wicket:extend>


text:
package com.amazonaws.services.workdocs.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.workdocs.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ResourceMetadataMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ResourceMetadataMarshaller {

    private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Type").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<String> ORIGINALNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OriginalName").build();
    private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Id").build();
    private static final MarshallingInfo<String> VERSIONID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("VersionId").build();
    private static final MarshallingInfo<StructuredPojo> OWNER_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Owner").build();
    private static final MarshallingInfo<String> PARENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ParentId").build();

    private static final ResourceMetadataMarshaller instance = new ResourceMetadataMarshaller();

    public static ResourceMetadataMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ResourceMetadata resourceMetadata, ProtocolMarshaller protocolMarshaller) {

        if (resourceMetadata == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(resourceMetadata.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getName(), NAME_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getOriginalName(), ORIGINALNAME_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getId(), ID_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getVersionId(), VERSIONID_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getOwner(), OWNER_BINDING);
            protocolMarshaller.marshall(resourceMetadata.getParentId(), PARENTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}