text:
            <md-button class="md-fab md-accent" aria-label="Home">
                <md-icon md-svg-src="/img/home.svg"></md-icon>
            </md-button>

    <md-tabs md-dynamic-height md-border-bottom>
        <md-tab label="Specify">
            <md-content class="md-padding">

                    <md-whiteframe layout="row" flex-sm="85" flex-gt-sm="66" class="md-whiteframe-z3 md-accent" layout="row" style="padding:40px;c">

                                    <md-input-container class="md-icon-float">
                                        Designation
                                        <md-icon md-font-library="material-icons" class="md-accent md-24">perm_contact_calendar</md-icon>
                                    </md-input-container>

                                    <md-input-container class="md-icon-float">
                                        Location
                                        <md-icon md-font-library="material-icons" class="md-accent md-24">pin_drop</md-icon>
                                    </md-input-container>

                                    <md-input-container class="md-icon-float">
                                        Spec
                                        <md-icon md-font-library="material-icons" class="md-accent md-24">assignment</md-icon>
                                    </md-input-container>

                                    <md-input-container class="md-icon-float">
                                        Your Brand
                                        <md-icon md-font-library="material-icons" class="md-accent md-24">favorite</md-icon>
                                    </md-input-container>

                    </md-whiteframe>

            </md-content>
        </md-tab>
    </md-tabs>


text:
from c7n.provider import clouds, Provider

from collections import Counter, namedtuple
from urllib.request import urlopen, urlparse, Request
from urllib.error import HTTPError
import contextlib
import copy
import datetime
import itertools
import logging
import os
import operator
import sys
import time
import threading
import traceback

import boto3

from botocore.validate import ParamValidator
from boto3.s3.transfer import S3Transfer

from c7n.credentials import SessionFactory
from c7n.config import Bag
from c7n.exceptions import ClientError, InvalidOutputConfig, PolicyValidationError
from c7n.log import CloudWatchLogHandler

from .resource_map import ResourceMap

# Import output registries aws provider extends.
from c7n.output import (
    api_stats_outputs,
    blob_outputs,
    log_outputs,
    metrics_outputs,
    tracer_outputs
)

# Output base implementations we extend.
from c7n.output import (
    Metrics,
    DeltaStats,
    BlobOutput,
    LogOutput,
)

from c7n.registry import PluginRegistry
from c7n import credentials, utils

log = logging.getLogger('custodian.aws')

try:
    from aws_xray_sdk.core import xray_recorder, patch
    from aws_xray_sdk.core.context import Context
    HAVE_XRAY = True
except ImportError:
    HAVE_XRAY = False
    class Context: pass  # NOQA

_profile_session = None

DEFAULT_NAMESPACE = "CloudMaid"

def get_profile_session(options):
    global _profile_session
    if _profile_session:
        return _profile_session

    profile = getattr(options, 'profile', None)
    _profile_session = boto3.Session(profile_name=profile)
    return _profile_session

def _default_region(options):
    marker = object()
    value = getattr(options, 'regions', marker)
    if value is marker:
        return

    if len(value) > 0:
        return

    try:
        options.regions = [get_profile_session(options).region_name]
    except Exception:
        log.warning('Could not determine default region')
        options.regions = [None]

    if options.regions[0] is None:
        log.error('No default region set. Specify a default via AWS_DEFAULT_REGION '
                  'or setting a region in ~/.aws/config')
        sys.exit(1)

    log.debug("using default region:%s from boto" % options.regions[0])

def _default_account_id(options):
    if options.account_id:
        return
    elif options.assume_role:
        try:
            options.account_id = options.assume_role.split(':')[4]
            return
        except IndexError:
            pass
    try:
        session = get_profile_session(options)
        options.account_id = utils.get_account_id_from_sts(session)
    except Exception:
        options.account_id = None

def shape_validate(params, shape_name, service):
    session = fake_session()._session
    model = session.get_service_model(service)
    shape = model.shape_for(shape_name)
    validator = ParamValidator()
    report = validator.validate(params, shape)
    if report.has_errors():
        raise PolicyValidationError(report.generate_report())

def get_bucket_region_clientless(bucket, s3_endpoint):
    """Attempt to determine a bucket region without a client

    We can make an unauthenticated HTTP HEAD request to S3 in an attempt to find a bucket's
    region. This avoids some issues with cross-account/cross-region uses of the
    GetBucketPolicy API action. Because bucket names are unique within
    AWS partitions, we can make requests to a single regional S3 endpoint
    and get redirected if a bucket lives in another region within the
    same partition.

    This approach is inspired by some sample code from a Go SDK issue comment,
    which @sean-zou mentioned in #7593:

    https://github.com/aws/aws-sdk-go/issues/720#issuecomment-613038544

    Return a region string, or None if we're unable to determine one.
    """
    region = None
    s3_endpoint_parts = urlparse(s3_endpoint)
    # Use a "path-style" S3 URL here to avoid failing TLS certificate validation
    # on buckets with a dot in the name.
    #
    # According to the following blog post, before deprecating path-style
    # URLs AWS will provide a way for virtual-hosted-style URLs to handle
    # buckets with dots in their names. Using path-style URLs here in
    # the meantime seems reasonable, compared to alternatives like forcing
    # HTTP or ignoring certificate validation.
    #
    # https://aws.amazon.com/blogs/aws/amazon-s3-path-deprecation-plan-the-rest-of-the-story/
    bucket_endpoint = f'https://{s3_endpoint_parts.netloc}/{bucket}'
    request = Request(bucket_endpoint, method='HEAD')
    try:
        # Dynamic use of urllib trips up static analyzers because
        # of the potential to accidentally allow unexpected schemes
        # like file:/. Here we're hardcoding the https scheme, so
        # we can ignore those specific checks.
        # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected # noqa
        response = urlopen(request)  # nosec B310
        region = response.headers.get('x-amz-bucket-region')
    except HTTPError as err:
        # Permission errors or redirects for valid buckets should still contain a
        # header we can use to determine the bucket region.
        region = err.headers.get('x-amz-bucket-region')

    return region

def get_bucket_region(bucket, client):
    """Determine a bucket's region using the GetBucketLocation API action

    Look up a bucket's location constraint and map it to a region name as described in
    https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLocation.html
    """
    location = client.get_bucket_location(Bucket=bucket)['LocationConstraint']

    # Remap region for cases where the location constraint doesn't match
    region = {None: 'us-east-1', 'EU': 'eu-west-1'}.get(location, location)
    return region

class Arn(namedtuple('_Arn', (
        'arn', 'partition', 'service', 'region',
        'account_id', 'resource', 'resource_type', 'separator'))):

    __slots__ = ()

    def __repr__(self):
        return "<arn:%s:%s:%s:%s:%s%s%s>" % (
            self.partition,
            self.service,
            self.region,
            self.account_id,
            self.resource_type,
            self.separator,
            self.resource)

    @classmethod
    def parse(cls, arn):
        if isinstance(arn, Arn):
            return arn
        parts = arn.split(':', 5)
        # a few resources use qualifiers without specifying type
        if parts[2] in ('s3', 'apigateway', 'execute-api'):
            parts.append(None)
            parts.append(None)
        elif '/' in parts[-1]:
            parts.extend(reversed(parts.pop(-1).split('/', 1)))
            parts.append('/')
        elif ':' in parts[-1]:
            parts.extend(reversed(parts.pop(-1).split(':', 1)))
            parts.append(':')
        elif len(parts) == 6:
            parts.append('')
            parts.append('')
        # replace the literal 'arn' string with raw arn
        parts[0] = arn
        return cls(*parts)

class ArnResolver:

    def __init__(self, manager):
        self.manager = manager

    def resolve(self, arns):
        arns = map(Arn.parse, arns)
        a_service = operator.attrgetter('service')
        a_resource = operator.attrgetter('resource_type')
        kfunc = lambda a: (a_service(a), a_resource(a))  # noqa
        arns = sorted(arns, key=kfunc)
        results = {}
        for (service, arn_type), arn_set in itertools.groupby(arns, key=kfunc):
            arn_set = list(arn_set)
            rtype = ArnResolver.resolve_type(arn_set[0])
            rmanager = self.manager.get_resource_manager(rtype)
            if rtype == 'sns':
                resources = rmanager.get_resources(
                    [rarn.arn for rarn in arn_set])
            else:
                resources = rmanager.get_resources(
                    [rarn.resource for rarn in arn_set])
            for rarn, r in zip(rmanager.get_arns(resources), resources):
                results[rarn] = r

            for rarn in arn_set:
                if rarn.arn not in results:
                    results[rarn.arn] = None
        return results

    @staticmethod
    def resolve_type(arn):
        arn = Arn.parse(arn)

        # this would benefit from a class cache {service} -> rtypes
        for type_name, klass in AWS.resources.items():
            if type_name in ('rest-account', 'account') or klass.resource_type.arn is False:
                continue
            if arn.service != (klass.resource_type.arn_service or klass.resource_type.service):
                continue
            if (type_name in ('asg', 'ecs-task') and
                    "%s%s" % (klass.resource_type.arn_type, klass.resource_type.arn_separator)
                    in arn.resource_type):
                return type_name
            elif (klass.resource_type.arn_type is not None and
                    klass.resource_type.arn_type == arn.resource_type):
                return type_name
            elif (klass.resource_type.arn_service == arn.service and
                    klass.resource_type.arn_type == ""):
                return type_name

@metrics_outputs.register('aws')
class MetricsOutput(Metrics):
    """Send metrics data to cloudwatch
    """

    permissions = ("cloudWatch:PutMetricData",)
    retry = staticmethod(utils.get_retry(('Throttling',)))

    def __init__(self, ctx, config=None):
        super(MetricsOutput, self).__init__(ctx, config)
        self.namespace = self.config.get('namespace', DEFAULT_NAMESPACE)
        self.region = self.config.get('region')
        self.destination = (
            self.config.scheme == 'aws' and
            self.config.get('netloc') == 'master') and 'master' or None

    def _format_metric(self, key, value, unit, dimensions):
        d = {
            "MetricName": key,
            "Timestamp": datetime.datetime.utcnow(),
            "Value": value,
            "Unit": unit}
        d["Dimensions"] = [
            {"Name": "Policy", "Value": self.ctx.policy.name},
            {"Name": "ResType", "Value": self.ctx.policy.resource_type}]
        for k, v in dimensions.items():
            # Skip legacy static dimensions if using new capabilities
            if (self.destination or self.region) and k == 'Scope':
                continue
            d['Dimensions'].append({"Name": k, "Value": v})
        if self.region:
            d['Dimensions'].append(
                {'Name': 'Region', 'Value': self.ctx.options.region})
        if self.destination:
            d['Dimensions'].append(
                {'Name': 'Account', 'Value': self.ctx.options.account_id or ''})
        return d

    def _put_metrics(self, ns, metrics):
        if self.destination == 'master':
            watch = self.ctx.session_factory(
                assume=False).client('cloudwatch', region_name=self.region)
        else:
            watch = utils.local_session(
                self.ctx.session_factory).client('cloudwatch', region_name=self.region)
        return self.retry(
            watch.put_metric_data, Namespace=ns, MetricData=metrics)

@log_outputs.register('aws')
class CloudWatchLogOutput(LogOutput):

    log_format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s'

    def __init__(self, ctx, config=None):
        super(CloudWatchLogOutput, self).__init__(ctx, config)
        if self.config['netloc'] == 'master' or not self.config['netloc']:
            self.log_group = self.config['path'].strip('/')
        else:
            # join netloc to path for casual usages of aws://log/group/name
            self.log_group = ("%s/%s" % (
                self.config['netloc'], self.config['path'].strip('/'))).strip('/')
        self.region = self.config.get('region', ctx.options.region)
        self.destination = (
            self.config.scheme == 'aws' and
            self.config.get('netloc') == 'master') and 'master' or None

    def construct_stream_name(self):
        if self.config.get('stream') is None:
            log_stream = self.ctx.policy.name
            if self.config.get('region') is not None:
                log_stream = "{}/{}".format(self.ctx.options.region, log_stream)
            if self.config.get('netloc') == 'master':
                log_stream = "{}/{}".format(self.ctx.options.account_id, log_stream)
        else:
            log_stream = self.config.get('stream').format(
                region=self.ctx.options.region,
                account=self.ctx.options.account_id,
                policy=self.ctx.policy.name,
                now=datetime.datetime.utcnow())
        return log_stream

    def get_handler(self):
        log_stream = self.construct_stream_name()
        params = dict(
            log_group=self.log_group, log_stream=log_stream,
            session_factory=(
                lambda x=None: self.ctx.session_factory(
                    region=self.region, assume=self.destination != 'master')))
        return CloudWatchLogHandler(**params)

    def __repr__(self):
        return "<%s to group:%s stream:%s>" % (
            self.__class__.__name__,
            self.ctx.options.log_group,
            self.ctx.policy.name)

class XrayEmitter:
    # implement https://github.com/aws/aws-xray-sdk-python/issues/51

    def __init__(self):
        self.buf = []
        self.client = None

    def send_entity(self, entity):
        self.buf.append(entity)
        if len(self.buf) > 49:
            self.flush()

    def flush(self):
        buf = self.buf
        self.buf = []
        for segment_set in utils.chunks(buf, 50):
            self.client.put_trace_segments(
                TraceSegmentDocuments=[s.serialize() for s in segment_set])

class XrayContext(Context):
    """Specialized XRay Context for Custodian.

    A context is used as a segment storage stack for currently in
    progress segments.

    We use a customized context for custodian as policy execution
    commonly uses a concurrent.futures threadpool pattern during
    execution for api concurrency. Default xray semantics would use
    thread local storage and treat each of those as separate trace
    executions. We want to aggregate/associate all thread pool api
    executions to the custoidan policy execution. XRay sdk supports
    this via manual code for every thread pool usage, but we don't
    want to explicitly couple xray integration everywhere across the
    codebase. Instead we use a context that is aware of custodian
    usage of threads and associates subsegments therein to the policy
    execution active subsegment.
    """

    def __init__(self, *args, **kw):
        super(XrayContext, self).__init__(*args, **kw)
        self._local = Bag()
        self._current_subsegment = None
        self._main_tid = threading.get_ident()

    def handle_context_missing(self):
        """Custodian has a few api calls out of band of policy execution.

        - Resolving account alias.
        - Cloudwatch Log group/stream discovery/creation (when using -l on cli)

        Also we want to folks to optionally based on configuration using xray
        so default to disabling context missing output.
        """

    # Annotate any segments/subsegments with their thread ids.
    def put_segment(self, segment):
        if getattr(segment, 'thread_id', None) is None:
            segment.thread_id = threading.get_ident()
        super().put_segment(segment)

    def put_subsegment(self, subsegment):
        if getattr(subsegment, 'thread_id', None) is None:
            subsegment.thread_id = threading.get_ident()
        super().put_subsegment(subsegment)

    # Override since we're not just popping the end of the stack, we're removing
    # the thread subsegment from the array by identity.
    def end_subsegment(self, end_time):
        subsegment = self.get_trace_entity()
        if self._is_subsegment(subsegment):
            subsegment.close(end_time)
            self._local.entities.remove(subsegment)
            return True
        else:
            log.warning("No subsegment to end.")
            return False

    # Override get trace identity, any worker thread will find its own subsegment
    # on the stack, else will use the main thread's sub/segment
    def get_trace_entity(self):
        tid = threading.get_ident()
        entities = self._local.get('entities', ())
        for s in reversed(entities):
            if s.thread_id == tid:
                return s
            # custodian main thread won't advance (create new segment)
            # with worker threads still doing pool work.
            elif s.thread_id == self._main_tid:
                return s
        return self.handle_context_missing()

@tracer_outputs.register('xray', condition=HAVE_XRAY)
class XrayTracer:

    emitter = XrayEmitter()

    in_lambda = 'LAMBDA_TASK_ROOT' in os.environ
    use_daemon = 'AWS_XRAY_DAEMON_ADDRESS' in os.environ
    service_name = 'custodian'

    @classmethod
    def initialize(cls, config):
        context = XrayContext()
        sampling = config.get('sample', 'true') == 'true' and True or False
        xray_recorder.configure(
            emitter=cls.use_daemon is False and cls.emitter or None,
            context=context,
            sampling=sampling,
            context_missing='LOG_ERROR')
        patch(['boto3', 'requests'])
        logging.getLogger('aws_xray_sdk.core').setLevel(logging.ERROR)

    def __init__(self, ctx, config):
        self.ctx = ctx
        self.config = config or {}
        self.client = None
        self.metadata = {}

    @contextlib.contextmanager
    def subsegment(self, name):
        segment = xray_recorder.begin_subsegment(name)
        try:
            yield segment
        except Exception as e:
            stack = traceback.extract_stack(limit=xray_recorder.max_trace_back)
            segment.add_exception(e, stack)
            raise
        finally:
            xray_recorder.end_subsegment(time.time())

    def __enter__(self):
        if self.client is None:
            self.client = self.ctx.session_factory(assume=False).client('xray')

        self.emitter.client = self.client

        if self.in_lambda:
            self.segment = xray_recorder.begin_subsegment(self.service_name)
        else:
            self.segment = xray_recorder.begin_segment(
                self.service_name, sampling=True)

        p = self.ctx.policy
        xray_recorder.put_annotation('policy', p.name)
        xray_recorder.put_annotation('resource', p.resource_type)
        if self.ctx.options.account_id:
            xray_recorder.put_annotation('account', self.ctx.options.account_id)

    def __exit__(self, exc_type=None, exc_value=None, exc_traceback=None):
        metadata = self.ctx.get_metadata(('api-stats',))
        metadata.update(self.metadata)
        xray_recorder.put_metadata('custodian', metadata)
        if self.in_lambda:
            xray_recorder.end_subsegment()
            return
        xray_recorder.end_segment()
        if not self.use_daemon:
            self.emitter.flush()
            log.info(
                ('View XRay Trace https://console.aws.amazon.com/xray/home?region=%s#/'
                 'traces/%s' % (self.ctx.options.region, self.segment.trace_id)))
        self.metadata.clear()

@api_stats_outputs.register('aws')
class ApiStats(DeltaStats):

    def __init__(self, ctx, config=None):
        super(ApiStats, self).__init__(ctx, config)
        self.api_calls = Counter()

    def get_snapshot(self):
        return dict(self.api_calls)

    def get_metadata(self):
        return self.get_snapshot()

    def __enter__(self):
        if isinstance(self.ctx.session_factory, credentials.SessionFactory):
            self.ctx.session_factory.set_subscribers((self,))
        self.push_snapshot()

    def __exit__(self, exc_type=None, exc_value=None, exc_traceback=None):
        if isinstance(self.ctx.session_factory, credentials.SessionFactory):
            self.ctx.session_factory.set_subscribers(())

        # With cached sessions, we need to unregister any events subscribers
        # on extant sessions to allow for the next registration.
        utils.local_session(self.ctx.session_factory).events.unregister(
            'after-call.*.*', self._record, unique_id='c7n-api-stats')

        self.ctx.metrics.put_metric(
            "ApiCalls", sum(self.api_calls.values()), "Count")
        self.pop_snapshot()

    def __call__(self, s):
        s.events.register(
            'after-call.*.*', self._record, unique_id='c7n-api-stats')

    def _record(self, http_response, parsed, model, **kwargs):
        self.api_calls["%s.%s" % (
            model.service_model.endpoint_prefix, model.name)] += 1

@blob_outputs.register('s3')
class S3Output(BlobOutput):
    """
    Usage:

    .. code-block:: python

       with S3Output(session_factory, 's3://bucket/prefix'):
           log.info('xyz')  # -> log messages sent to custodian-run.log.gz

    """

    permissions = ('S3:PutObject',)

    def __init__(self, ctx, config):
        super().__init__(ctx, config)
        # can't use a local session as we dont want an unassumed session cached.
        s3_client = self.ctx.session_factory(assume=False).client('s3')

        # Try determining the output bucket region via HTTP requests since
        # that works more consistently in cross-region scenarios. Fall back
        # the GetBucketLocation API if necessary.
        try:
            self.bucket_region = (
                get_bucket_region_clientless(self.bucket, s3_client.meta.endpoint_url) or
                get_bucket_region(self.bucket, s3_client)
            )
        except ClientError as err:
            raise InvalidOutputConfig(
                f'unable to determine a region for output bucket {self.bucket}: {err}') from None
        self.transfer = S3Transfer(
            self.ctx.session_factory(region=self.bucket_region, assume=False).client('s3'))

    def upload_file(self, path, key):
        self.transfer.upload_file(
            path, self.bucket, key,
            extra_args={
                'ACL': 'bucket-owner-full-control',
                'ServerSideEncryption': 'AES256'})

@clouds.register('aws')
class AWS(Provider):

    display_name = 'AWS'
    resource_prefix = 'aws'
    # legacy path for older plugins
    resources = PluginRegistry('resources')
    # import paths for resources
    resource_map = ResourceMap

    def initialize(self, options):
        """
        """
        _default_region(options)
        _default_account_id(options)
        if options.tracer and options.tracer.startswith('xray') and HAVE_XRAY:
            XrayTracer.initialize(utils.parse_url_config(options.tracer))

        return options

    def get_session_factory(self, options):
        return SessionFactory(
            options.region,
            options.profile,
            options.assume_role,
            options.external_id)

    def initialize_policies(self, policy_collection, options):
        """Return a set of policies targetted to the given regions.

        Supports symbolic regions like 'all'. This will automatically
        filter out policies if they are being targetted to a region that
        does not support the service. Global services will target a
        single region (us-east-1 if only all specified, else first
        region in the list).

        Note for region partitions (govcloud and china) an explicit
        region from the partition must be passed in.
        """
        from c7n.policy import Policy, PolicyCollection
        policies = []
        service_region_map, resource_service_map = get_service_region_map(
            options.regions, policy_collection.resource_types, self.type)
        if 'all' in options.regions:
            enabled_regions = {
                r['RegionName'] for r in
                get_profile_session(options).client('ec2').describe_regions(
                    Filters=[{'Name': 'opt-in-status',
                              'Values': ['opt-in-not-required', 'opted-in']}]
                ).get('Regions')}
        for p in policy_collection:
            if 'aws.' in p.resource_type:
                _, resource_type = p.resource_type.split('.', 1)
            else:
                resource_type = p.resource_type
            available_regions = service_region_map.get(
                resource_service_map.get(resource_type), ())

            # its a global service/endpoint, use user provided region
            # or us-east-1.
            if not available_regions and options.regions:
                candidates = [r for r in options.regions if r != 'all']
                candidate = candidates and candidates[0] or 'us-east-1'
                svc_regions = [candidate]
            elif 'all' in options.regions:
                svc_regions = list(set(available_regions).intersection(enabled_regions))
            else:
                svc_regions = options.regions

            for region in svc_regions:
                if available_regions and region not in available_regions:
                    level = ('all' in options.regions and
                             logging.DEBUG or logging.WARNING)
                    # TODO: fixme
                    policy_collection.log.log(
                        level, "policy:%s resources:%s not available in region:%s",
                        p.name, p.resource_type, region)
                    continue
                options_copy = copy.copy(options)
                options_copy.region = str(region)

                if len(options.regions) > 1 or 'all' in options.regions and getattr(
                        options, 'output_dir', None):
                    options_copy.output_dir = join_output(options.output_dir, region)
                policies.append(
                    Policy(p.data, options_copy,
                           session_factory=policy_collection.session_factory()))

        return PolicyCollection(
            # order policies by region to minimize local session invalidation.
            # note relative ordering of policies must be preserved, python sort
            # is stable.
            sorted(policies, key=operator.attrgetter('options.region')),
            options)

def join_output(output_dir, suffix):
    if '{region}' in output_dir:
        return output_dir.rstrip('/')
    if output_dir.endswith('://'):
        return output_dir + suffix
    return output_dir.rstrip('/') + '/%s' % suffix

def fake_session():
    session = boto3.Session(  # nosec nosemgrep
        region_name='us-east-1',
        aws_access_key_id='never',
        aws_secret_access_key='found')
    return session

def get_service_region_map(regions, resource_types, provider='aws'):
    # we're not interacting with the apis just using the sdk meta information.

    session = fake_session()
    normalized_types = []
    for r in resource_types:
        if r.startswith('%s.' % provider):
            normalized_types.append(r[len(provider) + 1:])
        else:
            normalized_types.append(r)
    resource_service_map = {
        r: clouds[provider].resources.get(r).resource_type.service
        for r in normalized_types if r != 'account'}
    # support for govcloud and china, we only utilize these regions if they
    # are explicitly passed in on the cli.
    partition_regions = {}
    for p in ('aws-cn', 'aws-us-gov'):
        for r in session.get_available_regions('s3', partition_name=p):
            partition_regions[r] = p

    partitions = ['aws']
    for r in regions:
        if r in partition_regions:
            partitions.append(partition_regions[r])

    service_region_map = {}
    for s in set(itertools.chain(resource_service_map.values())):
        for partition in partitions:
            service_region_map.setdefault(s, []).extend(
                session.get_available_regions(s, partition_name=partition))
    return service_region_map, resource_service_map

redpajama_set_name: RedPajamaGithub


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet LZCommentView *commentView;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
	[self addCells];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)addCells {
	NSString *name = @"yoavlt";
	UIImage *profileImage = [UIImage imageNamed:@"twitterProfile.jpeg"];

	__weak __typeof(self) weakSelf = self;
	[self dispatchOnMainThread:1 block:^{
		NSString *comment = @"Awesome!";
		LZCommentCell * cell =
		[weakSelf.commentView addCellwithProfileImage:nil name:name comment:comment];
		[cell.mark.imageView setImage:[UIImage imageNamed:@"twitterProfile.jpeg"]];
	}];

	[self dispatchOnMainThread:2 block:^{
		NSString *comment = @"Hooooo!";
		[weakSelf.commentView addCellwithProfileImage:profileImage name:@"Alonsolu Alonsolu Alonsolu" comment:comment];
	}];

	[self dispatchOnMainThread:3 block:^{
		NSString *comment = @"fdfaljdfldjfladsj dfajdslfjadsfja fadsflasdjfals!";
		[weakSelf.commentView addCellwithProfileImage:profileImage name:name comment:comment];
	}];

	[self dispatchOnMainThread:4 block:^{
		NSString *comment = @"一二三四lsds dfsdl fddfjadl jdlfad!";
		[weakSelf.commentView addCellwithProfileImage:profileImage name:name comment:comment];
	}];

}

- (void)dispatchOnMainThread:(NSTimeInterval)delay block:(void(^)())block {
	if (delay == 0) {
		dispatch_async(dispatch_get_main_queue(), ^{
			block();
		});
		return;
	}

	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * (double)NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		block();
	});
}

@end


text:
main = do
  cs <- if True
  then getLine
  else return "computer input"
  putStrLn cs


text:
#ifndef GUCEF_CORE_CTFACTORYBASEWITHPARAM_H
#define GUCEF_CORE_CTFACTORYBASEWITHPARAM_H

/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#include "gucefCORE_ETypes.h"
#include "CICloneable.h"

/*-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_CTFACTORYBASEWITHPARAM_CPP
    #pragma warning( push )
#endif

#pragma warning( disable: 4786 ) // identifier was truncated to 'number' characters
#pragma warning( disable: 4251 ) // 'classname' needs to have dll-interface to be used by clients of class 'classname'
#pragma warning( disable: 4284 )
#pragma warning( disable: 4146 ) // unary minus operator applied to unsigned type, result still unsigned

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

namespace GUCEF {
namespace CORE {

/*-------------------------------------------------------------------------//
//                                                                         //
//      TEMPLATES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

/**
 *  Template for creating an abstract interface for creation and destruction of
 *  objects without specifieing the concrete type
 */
template< class BaseClassType, typename ConstructionParamType >
class CTFactoryBaseWithParam : public CICloneable
{
    public:

    CTFactoryBaseWithParam( void );

    CTFactoryBaseWithParam( const CTFactoryBaseWithParam& src );

    /**
     *  Destuctor with no special behaviour, implemented to
     *  ensure that a virtual destructor is provided.
     */
    virtual ~CTFactoryBaseWithParam();

    CTFactoryBaseWithParam& operator=( const CTFactoryBaseWithParam& src );

    /**
     *  Constructs the concrete factory product
     *
     *  @return pointer to the base class of the constructed factory product
     */
    virtual BaseClassType* Create( const ConstructionParamType& param  ) = 0;

    /**
     *  Destroys the concrete factory product
     *
     *  @param factoryProduct pointer to the base class of the constructed factory product
     */
    virtual void Destroy( BaseClassType* factoryProduct ) = 0;
};

/*-------------------------------------------------------------------------//
//                                                                         //
//      UTILITIES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

template< class BaseClassType, typename ConstructionParamType >
CTFactoryBaseWithParam< BaseClassType, ConstructionParamType >::CTFactoryBaseWithParam( void )
    : CICloneable()
{

}

/*-------------------------------------------------------------------------*/

template< class BaseClassType, typename ConstructionParamType >
CTFactoryBaseWithParam< BaseClassType, ConstructionParamType >::CTFactoryBaseWithParam( const CTFactoryBaseWithParam& src )
    : CICloneable( src )
{

}

/*-------------------------------------------------------------------------*/

template< class BaseClassType, typename ConstructionParamType >
CTFactoryBaseWithParam< BaseClassType, ConstructionParamType >::~CTFactoryBaseWithParam()
{

}

/*-------------------------------------------------------------------------*/

template< class BaseClassType, typename ConstructionParamType >
CTFactoryBaseWithParam< BaseClassType, ConstructionParamType >&
CTFactoryBaseWithParam< BaseClassType, ConstructionParamType >::operator=( const CTFactoryBaseWithParam& src )
{
    if ( &src != this )
    {
        // nothing to do,.. meta-data class
    }
    return *this;
}

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

}; /* namespace CORE */
}; /* namespace GUCEF */

/*-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_CTFACTORYBASEWITHPARAM_CPP
    #pragma warning( pop )
#endif

/*-------------------------------------------------------------------------*/

#endif /* GUCEF_CORE_CTFACTORYBASEWITHPARAM_H ? */


text:
package org.springframework.boot.context.properties.bind;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Answers;
import org.mockito.InOrder;

import org.springframework.boot.context.properties.source.ConfigurationProperty;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MockConfigurationPropertySource;
import org.springframework.core.ResolvableType;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;

/**
 * Tests for {@link ArrayBinder}.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 */
public class ArrayBinderTests {

	private static final Bindable<List<Integer>> INTEGER_LIST = Bindable
			.listOf(Integer.class);

	private static final Bindable<Integer[]> INTEGER_ARRAY = Bindable.of(Integer[].class);

	private List<ConfigurationPropertySource> sources = new ArrayList<>();

	private Binder binder;

	@Before
	public void setup() {
		this.binder = new Binder(this.sources);
	}

	@Test
	public void bindToArrayShouldReturnArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[0]", "1");
		source.put("foo[1]", "2");
		source.put("foo[2]", "3");
		this.sources.add(source);
		Integer[] result = this.binder.bind("foo", INTEGER_ARRAY).get();
		assertThat(result).containsExactly(1, 2, 3);
	}

	@Test
	public void bindToCollectionShouldTriggerOnSuccess() {
		this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1"));
		BindHandler handler = mock(BindHandler.class,
				withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS));
		this.binder.bind("foo", INTEGER_LIST, handler);
		InOrder inOrder = inOrder(handler);
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")),
				eq(Bindable.of(Integer.class)), any(), eq(1));
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")),
				eq(INTEGER_LIST), any(), isA(List.class));
	}

	@Test
	public void bindToArrayShouldReturnPrimitiveArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[0]", "1");
		source.put("foo[1]", "2");
		source.put("foo[2]", "3");
		this.sources.add(source);
		int[] result = this.binder.bind("foo", Bindable.of(int[].class)).get();
		assertThat(result).containsExactly(1, 2, 3);
	}

	@Test
	public void bindToArrayWhenNestedShouldReturnPopulatedArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[0][0]", "1");
		source.put("foo[0][1]", "2");
		source.put("foo[1][0]", "3");
		source.put("foo[1][1]", "4");
		this.sources.add(source);
		ResolvableType type = ResolvableType.forArrayComponent(INTEGER_ARRAY.getType());
		Bindable<Integer[][]> target = Bindable.of(type);
		Integer[][] result = this.binder.bind("foo", target).get();
		assertThat(result).hasSize(2);
		assertThat(result[0]).containsExactly(1, 2);
		assertThat(result[1]).containsExactly(3, 4);
	}

	@Test
	public void bindToArrayWhenNestedListShouldReturnPopulatedArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[0][0]", "1");
		source.put("foo[0][1]", "2");
		source.put("foo[1][0]", "3");
		source.put("foo[1][1]", "4");
		this.sources.add(source);
		ResolvableType type = ResolvableType.forArrayComponent(INTEGER_LIST.getType());
		Bindable<List<Integer>[]> target = Bindable.of(type);
		List<Integer>[] result = this.binder.bind("foo", target).get();
		assertThat(result).hasSize(2);
		assertThat(result[0]).containsExactly(1, 2);
		assertThat(result[1]).containsExactly(3, 4);
	}

	@Test
	public void bindToArrayWhenNotInOrderShouldReturnPopulatedArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[1]", "2");
		source.put("foo[0]", "1");
		source.put("foo[2]", "3");
		this.sources.add(source);
		Integer[] result = this.binder.bind("foo", INTEGER_ARRAY).get();
		assertThat(result).containsExactly(1, 2, 3);
	}

	@Test
	public void bindToArrayWhenNonSequentialShouldThrowException() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[0]", "2");
		source.put("foo[1]", "1");
		source.put("foo[3]", "3");
		this.sources.add(source);
		try {
			this.binder.bind("foo", INTEGER_ARRAY);
			fail("No exception thrown");
		}
		catch (BindException ex) {
			Set<ConfigurationProperty> unbound = ((UnboundConfigurationPropertiesException) ex
					.getCause()).getUnboundProperties();
			assertThat(unbound.size()).isEqualTo(1);
			ConfigurationProperty property = unbound.iterator().next();
			assertThat(property.getName().toString()).isEqualTo("foo[3]");
			assertThat(property.getValue()).isEqualTo("3");
		}
	}

	@Test
	public void bindToArrayWhenNonIterableShouldReturnPopulatedArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo[1]", "2");
		source.put("foo[0]", "1");
		source.put("foo[2]", "3");
		this.sources.add(source.nonIterable());
		Integer[] result = this.binder.bind("foo", INTEGER_ARRAY).get();
		assertThat(result).containsExactly(1, 2, 3);
	}

	@Test
	public void bindToArrayWhenMultipleSourceShouldOnlyUseFirst() {
		MockConfigurationPropertySource source1 = new MockConfigurationPropertySource();
		source1.put("bar", "baz");
		this.sources.add(source1);
		MockConfigurationPropertySource source2 = new MockConfigurationPropertySource();
		source2.put("foo[0]", "1");
		source2.put("foo[1]", "2");
		this.sources.add(source2);
		MockConfigurationPropertySource source3 = new MockConfigurationPropertySource();
		source3.put("foo[0]", "7");
		source3.put("foo[1]", "8");
		source3.put("foo[2]", "9");
		this.sources.add(source3);
		Integer[] result = this.binder.bind("foo", INTEGER_ARRAY).get();
		assertThat(result).containsExactly(1, 2);
	}

	@Test
	public void bindToArrayWhenHasExistingCollectionShouldReplaceAllContents() {
		this.sources.add(new MockConfigurationPropertySource("foo[0]", "1"));
		Integer[] existing = new Integer[2];
		existing[0] = 1000;
		existing[1] = 1001;
		Integer[] result = this.binder
				.bind("foo", INTEGER_ARRAY.withExistingValue(existing)).get();
		assertThat(result).containsExactly(1);
	}

	@Test
	public void bindToArrayWhenNoValueShouldReturnUnbound() {
		this.sources.add(new MockConfigurationPropertySource("faf.bar", "1"));
		BindResult<Integer[]> result = this.binder.bind("foo", INTEGER_ARRAY);
		assertThat(result.isBound()).isFalse();
	}

	@Test
	public void bindToArrayShouldTriggerOnSuccess() {
		this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1"));
		BindHandler handler = mock(BindHandler.class,
				withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS));
		Bindable<Integer[]> target = INTEGER_ARRAY;
		this.binder.bind("foo", target, handler);
		InOrder inOrder = inOrder(handler);
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")),
				eq(Bindable.of(Integer.class)), any(), eq(1));
		inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")),
				eq(target), any(), isA(Integer[].class));
	}

	@Test
	public void bindToArrayWhenCommaListShouldReturnPopulatedArray() {
		this.sources.add(new MockConfigurationPropertySource("foo", "1,2,3"));
		int[] result = this.binder.bind("foo", Bindable.of(int[].class)).get();
		assertThat(result).containsExactly(1, 2, 3);
	}

	@Test
	public void bindToArrayWhenCommaListAndIndexedShouldOnlyUseFirst() {
		MockConfigurationPropertySource source1 = new MockConfigurationPropertySource();
		source1.put("foo", "1,2");
		this.sources.add(source1);
		MockConfigurationPropertySource source2 = new MockConfigurationPropertySource();
		source2.put("foo[0]", "2");
		source2.put("foo[1]", "3");
		int[] result = this.binder.bind("foo", Bindable.of(int[].class)).get();
		assertThat(result).containsExactly(1, 2);
	}

	@Test
	public void bindToArrayWhenIndexedAndCommaListShouldOnlyUseFirst() {
		MockConfigurationPropertySource source1 = new MockConfigurationPropertySource();
		source1.put("foo[0]", "1");
		source1.put("foo[1]", "2");
		this.sources.add(source1);
		MockConfigurationPropertySource source2 = new MockConfigurationPropertySource();
		source2.put("foo", "2,3");
		int[] result = this.binder.bind("foo", Bindable.of(int[].class)).get();
		assertThat(result).containsExactly(1, 2);
	}

	@Test
	public void bindToArrayShouldBindCharArray() {
		this.sources.add(new MockConfigurationPropertySource("foo", "word"));
		char[] result = this.binder.bind("foo", Bindable.of(char[].class)).get();
		assertThat(result).containsExactly("word".toCharArray());
	}

	@Test
	public void bindToArrayWhenEmptyStringShouldReturnEmptyArray() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo", "");
		this.sources.add(source);
		String[] result = this.binder.bind("foo", Bindable.of(String[].class)).get();
		assertThat(result).isNotNull().isEmpty();
	}

	@Test
	public void bindToArrayWhenHasSpacesShouldTrim() {
		MockConfigurationPropertySource source = new MockConfigurationPropertySource();
		source.put("foo", "1,  2,3");
		this.sources.add(source);
		String[] result = this.binder.bind("foo", Bindable.of(String[].class)).get();
		assertThat(result).containsExactly("1", "2", "3");
	}

}


text:
"""
This test checks activation of OP_CHECKDATASIG
"""
import os, random, string
from test_framework.util import findBitcoind, expectException, JSONRPCException
import test_framework.loginit
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import waitFor, satoshi_round, assert_equal, assert_raises_rpc_error, start_node, standardFlags
from test_framework.comptool import TestManager, TestInstance, RejectResult
from test_framework.blocktools import *
from test_framework.script import *

# far into the future
NOV152018_START_TIME = 2000000000

# Error due to invalid opcodes
BAD_OPCODE_ERROR = b'mandatory-script-verify-flag-failed (Opcode missing or not understood)'
RPC_BAD_OPCODE_ERROR = "16: " + \
    BAD_OPCODE_ERROR.decode("utf-8")

class PreviousSpendableOutput():
    def __init__(self, tx=CTransaction(), n=-1):
        self.tx = tx
        self.n = n  # the output we're spending

class CheckDataSigActivationTest(ComparisonTestFramework):
    def __init__(self):
        super().__init__()
        self.num_nodes = 1
        self.setup_clean_chain = True

    def setup_network(self):
        self.nodes = []
        self.nodes.append(start_node(0, self.options.tmpdir,
                                 ['-debug', '-whitelist=127.0.0.1',
                                  "-consensus.forkNov2018Time=%d" % NOV152018_START_TIME]))
        self.is_network_split = False

    def create_checkdatasig_tx(self, count):
        node = self.nodes[0]
        utxos = node.listunspent()
        assert(len(utxos) > 0)
        utxo = utxos[0]
        tx = CTransaction()
        value = int(satoshi_round(utxo["amount"]) * COIN) // count
        tx.vin = [CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]))]
        tx.vout = []

        # test using the signdata rpc
        addr = node.getnewaddress()
        msg = "Joo Janta 200 Super-Chromatic Peril Sensitive Sunglasses"
        message = bytearray(msg.encode())
        rpc = node.signdata(addr, "string", msg,"verbose")

        signature = bytearray.fromhex(rpc["signature"])
        pubkey = bytearray.fromhex(rpc["pubkey"])

        # test with hard-coded values
        #signature = bytearray.fromhex(
        #    '30440220256c12175e809381f97637933ed6ab97737d263eaaebca6add21bced67fd12a402205ce29ecc1369d6fc1b51977ed38faaf41119e3be1d7edfafd7cfaf0b6061bd07')
        #pubkey = bytearray.fromhex(
        #    '038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508')

        for _ in range(count):
            tx.vout.append(CTxOut(value, CScript(
                [signature, message, pubkey, OP_CHECKDATASIG])))
        tx.vout[0].nValue -= min(value/100, 1000) #node.calculate_fee(tx.toHex())
        tx_signed = node.signrawtransaction(tx.toHex())["hex"]
        return tx_signed

    def testDatasigRpc(self):
        node = self.nodes[0]
        # bad address
        expectException(lambda: node.signdata("bad","string", "foo"), JSONRPCException)
        # address I can't sign
        expectException(lambda: node.signdata('bchreg:qq0ndugr327fwxucntduem4t3jvvmjtdevmdry0lqc',"string", "foo"), JSONRPCException)
        addr = node.getnewaddress()
        # bad message format
        expectException(lambda: node.signdata(addr,"bad", "foo"), JSONRPCException)
        expectException(lambda: node.signdata(addr,"hex", "zzbad"), JSONRPCException)
        expectException(lambda: node.signdata(addr,"hash", "ba0d"), JSONRPCException) # its hex but wrong length
        expectException(lambda: node.signdata(addr,"hash", "z"*32), JSONRPCException) # not hex correct length

        # check same sig for same input of different format (works because using rfc6979 deterministic sigs)
        s = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
        sig0 = node.signdata(addr,"string", s)
        sig1 = node.signdata(addr,"hex", hexlify(s.encode()).decode())
        sig2 = node.signdata(addr,"hash", hexlify(sha256(s.encode())).decode())
        assert_equal(sig0, sig1)
        assert_equal(sig0, sig2)

        # good signatures
        node.importprivatekeys("no-rescan", 'cU4WAhpniFvwT8Z13MjNyE1tkzp8n7wDPwwe8WzqqBAejZXq948J')
        sig = node.signdata('bchreg:qq3srvg7hrzf9wu5h33du5l7n3fpx7jw5gdhhk390u',"string", "foo")
        assert_equal(sig, '3045022100C548DFF1354117D260B03E167BD25B5F79F6AB17219CAF5FC9CA1C94F0B9BB3C022049D9521CC04A0AD4DE42F81A1623D1F179A47B21B814AB7FBC2FF192AF023ECF')
        sig2 = node.signdata('bchreg:qq3srvg7hrzf9wu5h33du5l7n3fpx7jw5gdhhk390u',"hex", "0102030405060708090a")
        assert_equal(sig2, '3044022061E179B30A3B6ACD31F21A77ACB162FBB998473ACE4AAA56CC808FFD2415963B0220793AF5402AD9534D2D5F26248421499520E6B571C4BE31B90CBBFF602C0A7FDC')

        # If I use the "hash" format and calculate the sha256 myself, it ought to create the same signature as "signdata"
        assert_equal(sig, node.signdata('bchreg:qq3srvg7hrzf9wu5h33du5l7n3fpx7jw5gdhhk390u',"hash", hexlify(sha256(b"foo")).decode()))

    def run_test(self):
        self.testDatasigRpc()
        self.test = TestManager(self, self.options.tmpdir)
        self.test.add_all_connections(self.nodes)
        # Start up network handling in another thread
        NetworkThread().start()
        self.test.run()

    def get_tests(self):
        node = self.nodes[0]

        # First, we generate some coins to spend.
        node.generate(125)

        # Create various outputs using the OP_CHECKDATASIG
        # to check for activation.
        tx_hex = self.create_checkdatasig_tx(25)
        txid = node.sendrawtransaction(tx_hex)
        assert(txid in set(node.getrawmempool()))

        node.generate(1)
        assert(txid not in set(node.getrawmempool()))

        # register the spendable outputs.
        tx = FromHex(CTransaction(), tx_hex)
        tx.rehash()
        spendable_checkdatasigs = [PreviousSpendableOutput(tx, i)
                                   for i in range(len(tx.vout))]

        def spend_checkdatasig():
            outpoint = spendable_checkdatasigs.pop()
            out = outpoint.tx.vout[outpoint.n]
            tx = CTransaction()
            tx.vin = [CTxIn(COutPoint(outpoint.tx.sha256, outpoint.n))]
            tx.vout = [CTxOut(out.nValue, CScript([])),
                       CTxOut(0, CScript([random.getrandbits(800), OP_RETURN]))]
            tx.vout[0].nValue -= min(tx.vout[0].nValue/100, 1000) # node.calculate_fee(tx)
            tx.rehash()
            return tx

        # Check that transactions using checkdatasig are not accepted yet.
        logging.info("Try to use the checkdatasig opcodes before activation")

        tx0 = spend_checkdatasig()
        tx0_hex = ToHex(tx0)
        assert_raises_rpc_error(-26, RPC_BAD_OPCODE_ERROR,
                                node.sendrawtransaction, tx0_hex)

        # Push MTP forward just before activation.
        logging.info("Pushing MTP just before the activation and check again")
        node.setmocktime(NOV152018_START_TIME)

        # returns a test case that asserts that the current tip was accepted
        def accepted(tip):
            return TestInstance([[tip, True]])

        # returns a test case that asserts that the current tip was rejected
        def rejected(tip, reject=None):
            if reject is None:
                return TestInstance([[tip, False]])
            else:
                return TestInstance([[tip, reject]])

        def next_block(block_time):
            # get block height
            blockchaininfo = node.getblockchaininfo()
            height = int(blockchaininfo['blocks'])

            # create the block
            coinbase = create_coinbase(height)
            coinbase.rehash()
            block = create_block(
                int(node.getbestblockhash(), 16), coinbase, block_time)

            # Do PoW, which is cheap on regnet
            block.solve()
            return block

        for i in range(6):
            b = next_block(NOV152018_START_TIME + i - 1)
            yield accepted(b)

        # Check again just before the activation time
        assert_equal(node.getblockheader(node.getbestblockhash())['mediantime'],
                     NOV152018_START_TIME - 1)
        assert_raises_rpc_error(-26, RPC_BAD_OPCODE_ERROR,
                                node.sendrawtransaction, tx0_hex)

        def add_tx(block, tx):
            block.vtx.append(tx)
            block.hashMerkleRoot = block.calc_merkle_root()
            block.solve()

        b = next_block(NOV152018_START_TIME + 6)
        add_tx(b, tx0)
        yield rejected(b, RejectResult(16, b'bad-blk-signatures'))

        logging.info("Activates checkdatasig")
        fork_block = next_block(NOV152018_START_TIME + 6)
        yield accepted(fork_block)

        assert_equal(node.getblockheader(node.getbestblockhash())['mediantime'],
                     NOV152018_START_TIME)

        tx0id = node.sendrawtransaction(tx0_hex)
        assert(tx0id in set(node.getrawmempool()))

        # Transactions can also be included in blocks.
        nov152018forkblock = next_block(NOV152018_START_TIME + 7)
        add_tx(nov152018forkblock, tx0)
        yield accepted(nov152018forkblock)

        logging.info("Cause a reorg that deactivate the checkdatasig opcodes")

        # Invalidate the checkdatasig block, ensure tx0 gets back to the mempool.
        assert(tx0id not in set(node.getrawmempool()))

        node.invalidateblock(format(nov152018forkblock.sha256, 'x'))
        waitFor(3, lambda: tx0id in set(node.getrawmempool()), "Transaction shoud be included in the mempool")

        node.invalidateblock(format(fork_block.sha256, 'x'))
        waitFor(3, lambda: tx0id not in set(node.getrawmempool()), "Transaction should not be included in the memopool")

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

# Create a convenient function for an interactive python debugging session
def Test():
    t = CheckDataSigActivationTest()
    t.drop_to_pdb = True
    bitcoinConf = {
        "debug": ["blk", "mempool", "net", "req"],
        "logtimemicros": 1
    }

    flags = standardFlags()
    t.main(flags, bitcoinConf, None)


text:
<?php
$PHP_DIR = './src';
require("$PHP_DIR/panda_helper.php");

$html_response = panda_response();
if (is_null($html_response))
  exit;
?>

    <title>P A N D A</title>

panda 6.1.7

      <?php echo $html_response ?>

Talky panda

      <form enctype="multipart/form-data" action="/talk" method="POST">
        <input id="input-txtmsg" name="txtmsg" type="text" size="150" maxlength="300"/>

          <input id="talk-submit" type="submit" disabled="true"/>

      </form>

Broadcast a very important announcement

      <applet
        CODE="com.softsynth.javasonics.recplay.RecorderUploadApplet"
        CODEBASE="<?php echo "$WEB_PUBLIC_DIR/java" ?>"
        ARCHIVE="JavaSonicsListenUp.jar"
        NAME="JavaSonicRecorderUploader"
        WIDTH="400" HEIGHT="120">

        <param name="frameRate" value="11025.0">

        <param name="numChannels" value="1">

        <param name="maxRecordTime" value="20.0">

        <param name="compressorEnable" value="yes">
        <param name="compressorThreshold" value="0.2">
        <param name="compressorNoiseThreshold" value="0.05">
        <param name="compressorCurvature" value="0.05">

        <param name="uploadFileName" value="userfile">

        <param name="uploadURL" value="broadcast">
      </applet>

Add 2 panda

      <form enctype="multipart/form-data" action="/create" method="POST">
        Title<input id="input-title" name="title" type="text"/>

        Image<input id="input-image" name="imagefile" type="file"/>

        Audio<input id="input-audio" name="audiofile" type="file"/>

          <input id="uploader-submit" value="Upload" type="submit" disabled="true"/>

      </form>


text:
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Exercise;

use PhpSchool\PhpWorkshop\Solution\SolutionInterface;

/**
 * Exercises can implement this method if they want to provide some
 * code for the user to start with, eg a failing solution.
 */
interface ProvidesInitialCode
{
    /**
     * Get the exercise solution.
     *
     * @return SolutionInterface
     */
    public function getInitialCode(): SolutionInterface;
}


text:
package org.estatio.module.lease.integtests.invoicing;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.fixturescripts.FixtureScript;

import org.incode.module.base.integtests.VT;
import org.incode.module.docfragment.dom.impl.DocFragmentRepository;

import org.estatio.module.asset.fixtures.person.enums.Person_enum;
import org.estatio.module.asset.fixtures.property.enums.PropertyAndUnitsAndOwnerAndManager_enum;
import org.estatio.module.charge.dom.Charge;
import org.estatio.module.index.dom.Index;
import org.estatio.module.index.dom.IndexRepository;
import org.estatio.module.invoice.dom.Invoice;
import org.estatio.module.invoice.dom.InvoiceItem;
import org.estatio.module.invoice.dom.InvoiceRepository;
import org.estatio.module.invoice.dom.InvoiceRunType;
import org.estatio.module.invoice.dom.InvoiceStatus;
import org.estatio.module.lease.app.InvoiceMenu;
import org.estatio.module.lease.app.InvoiceServiceMenu;
import org.estatio.module.lease.app.LeaseMenu;
import org.estatio.module.lease.app.NumeratorForOutgoingInvoicesMenu;
import org.estatio.module.lease.contributions.Lease_calculate;
import org.estatio.module.lease.dom.InvoicingFrequency;
import org.estatio.module.lease.dom.Lease;
import org.estatio.module.lease.dom.LeaseItem;
import org.estatio.module.lease.dom.LeaseItemType;
import org.estatio.module.lease.dom.LeaseRepository;
import org.estatio.module.lease.dom.LeaseTermForFixed;
import org.estatio.module.lease.dom.LeaseTermForIndexable;
import org.estatio.module.lease.dom.invoicing.InvoiceCalculationSelection;
import org.estatio.module.lease.dom.invoicing.InvoiceForLease;
import org.estatio.module.lease.dom.invoicing.InvoiceForLeaseRepository;
import org.estatio.module.lease.dom.invoicing.InvoiceItemForLease;
import org.estatio.module.lease.dom.invoicing.InvoiceItemForLeaseRepository;
import org.estatio.module.lease.fixtures.breakoptions.enums.BreakOption_enum;
import org.estatio.module.lease.fixtures.invoice.enums.InvoiceForLease_enum;
import org.estatio.module.lease.fixtures.lease.enums.Lease_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForDeposit_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForDiscount_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForEntryFee_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForRent_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForServiceCharge_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForTurnoverRent_enum;
import org.estatio.module.lease.integtests.LeaseModuleIntegTestAbstract;

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

public class InvoiceService_IntegTest extends LeaseModuleIntegTestAbstract {

    private static final LocalDate START_DATE = VT.ld(2013, 11, 7);

    @Inject
    LeaseMenu leaseMenu;

    @Inject
    LeaseRepository leaseRepository;

    @Inject
    InvoiceServiceMenu invoiceService;

    @Inject
    InvoiceRepository invoiceRepository;

    @Inject
    InvoiceForLeaseRepository invoiceForLeaseRepository;

    @Inject
    InvoiceMenu invoiceMenu;

    @Inject
    NumeratorForOutgoingInvoicesMenu estatioNumeratorRepository;

    @Inject
    IndexRepository indexRepository;

    @Inject
    InvoiceItemForLeaseRepository invoiceItemForLeaseRepository;

    Lease lease;
    LeaseItem rItem;
    LeaseItem sItem;
    LeaseItem tItem;
    LeaseItem dItem;

    public static class Lifecycle extends InvoiceService_IntegTest {

        @Before
        public void setupTransactionalData() {
            runFixtureScript(new FixtureScript() {
                @Override
                protected void execute(final ExecutionContext ec) {

                    ec.executeChildren(this,
                            Person_enum.JohnDoeNl,
                            PropertyAndUnitsAndOwnerAndManager_enum.OxfGb,
                            PropertyAndUnitsAndOwnerAndManager_enum.KalNl);

                    ec.executeChildren(this,
                            BreakOption_enum.OxfPoison003Gb_FIXED,
                            BreakOption_enum.OxfPoison003Gb_ROLLING,
                            BreakOption_enum.OxfPoison003Gb_FIXED,
                            BreakOption_enum.OxfPoison003Gb_ROLLING,
                            BreakOption_enum.OxfTopModel001Gb_FIXED,
                            BreakOption_enum.OxfTopModel001Gb_ROLLING);

                    ec.executeChildren(this,
                            InvoiceForLease_enum.OxfPoison003Gb,
                            InvoiceForLease_enum.KalPoison001Nl);

                    ec.executeChildren(this,
                            Lease_enum.OxfPret004Gb,

                            LeaseItemForRent_enum.OxfMiracl005Gb,
                            LeaseItemForServiceCharge_enum.OxfMiracl005Gb,
                            LeaseItemForTurnoverRent_enum.OxfMiracl005Gb,
                            LeaseItemForDiscount_enum.OxfMiracle005bGb,
                            LeaseItemForDeposit_enum.OxfMiracle005bGb);
                }
            });

            lease = leaseRepository.findLeaseByReference("OXF-MIRACL-005");
            rItem = lease.findFirstItemOfType(LeaseItemType.RENT);
            sItem = lease.findFirstItemOfType(LeaseItemType.SERVICE_CHARGE);
            tItem = lease.findFirstItemOfType(LeaseItemType.TURNOVER_RENT);
            dItem = lease.findFirstItemOfType(LeaseItemType.DEPOSIT);
        }

        @Test
        public void fullLifecycle() throws Exception {
            step1_verify();
            step2_calculate();
            step3_approveInvoice();
            step4_indexation();
            step5_normalInvoice();
            step6_retroInvoice();
            step7_terminate();
        }

        public void step1_verify() throws Exception {
            // when
            lease.verifyUntil(VT.ld(2015, 1, 1));
            // then
            assertThat(rItem.getTerms().size(), is(2));
            assertThat(sItem.getTerms().size(), is(2));
            assertThat(tItem.getTerms().size(), is(2));
            assertThat(dItem.getTerms().size(), is(1));

            final LeaseTermForIndexable last = (LeaseTermForIndexable) rItem.getTerms().last();
            final LeaseTermForIndexable first = (LeaseTermForIndexable) rItem.getTerms().first();
            assertNotNull(last.getPrevious());
            assertThat(last.getBaseValue(), is(VT.bd(150000).setScale(2)));
            assertThat(first.getStartDate(), is(VT.ld(2013, 11, 7)));
            assertThat(last.getStartDate(), is(VT.ld(2015, 1, 1)));
            assertThat(invoiceForLeaseRepository.findByLease(lease).size(), is(0));
            assertThat(dItem.getTerms().last().getEffectiveValue(), is(VT.bd(75000).setScale(2)));
        }

        public void step2_calculate() throws Exception {
            assertThat("Before calculation", rItem.getTerms().size(), is(2));
            invoiceService.calculateLegacy(
                    lease, InvoiceRunType.NORMAL_RUN,
                    InvoiceCalculationSelection.ALL_RENT_AND_SERVICE_CHARGE,
                    START_DATE,
                    VT.ld(2013, 10, 1),
                    VT.ld(2015, 4, 1));
            approveInvoicesFor(lease);
            assertThat(totalApprovedOrInvoicedForItem(rItem), is(VT.bd("209918.48")));
            assertThat(totalApprovedOrInvoicedForItem(sItem), is(VT.bd("18103.26")));
            assertThat(invoiceForLeaseRepository.findByLease(lease).size(), is(1));
        }

        public void step3_approveInvoice() throws Exception {
            final List<Invoice> allInvoices = invoiceMenu.allInvoices();
            final Invoice invoice = allInvoices.get(allInvoices.size() - 1);
            //numeratorForOutgoingInvoicesMenu.createInvoiceNumberNumerator(lease.getProperty(), "OXF-%06d", BigInteger.ZERO, invoice.getApplicationTenancy());

            mixin(InvoiceForLease._approve.class, invoice).$$();
            mixin(InvoiceForLease._invoice.class, invoice).$$(VT.ld(2013, 11, 7));

            assertThat(invoice.getInvoiceNumber(), is("OXF-0001"));
            assertThat(invoice.getStatus(), is(InvoiceStatus.INVOICED));
        }

        public void step4_indexation() throws Exception {
            Index index = indexRepository.findByReference("ISTAT-FOI");
            index.newIndexValue(VT.ld(2013, 11, 1), VT.bd(110));
            index.newIndexValue(VT.ld(2014, 12, 1), VT.bd(115));

            transactionService.nextTransaction();

            lease.verifyUntil(VT.ld(2015, 3, 31));
            final LeaseTermForIndexable term = (LeaseTermForIndexable) rItem.findTerm(VT.ld(2015, 1, 1));
            assertThat(term.getIndexationPercentage(), is(VT.bd(4.5)));
            assertThat(term.getIndexedValue(), is(VT.bd("156750.00")));
            assertThat(totalApprovedOrInvoicedForItem(rItem), is(VT.bd("209918.48")));
        }

        public void step5_normalInvoice() throws Exception {
            invoiceService.calculateLegacy(lease, InvoiceRunType.NORMAL_RUN, InvoiceCalculationSelection.ALL_RENT_AND_SERVICE_CHARGE, VT.ld(2015, 4, 1), VT.ld(2015, 4, 1), VT.ld(2015, 4, 1));
            approveInvoicesFor(lease);
            assertThat(totalApprovedOrInvoicedForItem(rItem), is(VT.bd("209918.48")));
        }

        public void step6_retroInvoice() throws Exception {
            invoiceService.calculateLegacy(lease, InvoiceRunType.RETRO_RUN, InvoiceCalculationSelection.ALL_RENT_AND_SERVICE_CHARGE, VT.ld(2015, 4, 1), VT.ld(2015, 4, 1), VT.ld(2015, 4, 1));
            // (156750 - 150000) / = 1687.5 added
            approveInvoicesFor(lease);
            assertThat(invoiceForLeaseRepository.findByLease(lease).size(), is(2));
            assertThat(totalApprovedOrInvoicedForItem(rItem), is(VT.bd("209918.48").add(VT.bd("1687.50"))));
        }

        public void step7_terminate() throws Exception {
            lease.terminate(VT.ld(2014, 6, 30));
        }

        // //////////////////////////////////////

        private BigDecimal totalApprovedOrInvoicedForItem(final LeaseItem leaseItem) {
            BigDecimal total = BigDecimal.ZERO;
            final InvoiceStatus[] allowed = { InvoiceStatus.APPROVED, InvoiceStatus.INVOICED };
            for (final InvoiceStatus invoiceStatus : allowed) {
                final List<InvoiceItemForLease> items = invoiceItemForLeaseRepository.findByLeaseItemAndInvoiceStatus(leaseItem, invoiceStatus);
                for (final InvoiceItemForLease item : items) {
                    total = total.add(item.getNetAmount());
                }
            }
            return total;
        }

        private void approveInvoicesFor(final Lease lease) {
            for (final Invoice invoice : invoiceForLeaseRepository.findByLease(lease)) {
                mixin(InvoiceForLease._approve.class, invoice).$$();
            }
        }
    }

    public static class RetroInvoiceForFixedInAdvanceItem extends InvoiceService_IntegTest {

        @Before
        public void setupTransactionalData() {
            runFixtureScript(new FixtureScript() {
                @Override
                protected void execute(final ExecutionContext ec) {

                    ec.executeChildren(this,
                            Lease_enum.OxfFix006Gb);
                    ec.executeChildren(this,
                            LeaseItemForRent_enum.OxfFix006Gb);
                    ec.executeChildren(this,
                            LeaseItemForEntryFee_enum.OxfFix006Gb);
                }
            });

        }

        @Test
        public void retro_invoicing_fixed_in_advance_item_works() throws Exception {

            // given
            Lease leaseForFix = Lease_enum.OxfFix006Gb.findUsing(serviceRegistry);
            LeaseItem entryFeeItem = leaseForFix.findItemsOfType(LeaseItemType.ENTRY_FEE).get(0);
            LeaseTermForFixed entryFeeTerm = (LeaseTermForFixed) entryFeeItem.getTerms().first();

            Assertions.assertThat(entryFeeItem.getInvoicingFrequency()).isEqualTo(InvoicingFrequency.FIXED_IN_ADVANCE);
            Assertions.assertThat(invoiceForLeaseRepository.findByLease(leaseForFix).isEmpty()).isTrue();
            Assertions.assertThat(entryFeeTerm.getValue()).isEqualTo(VT.bd("5000.00"));

            // when
            wrap(mixin(Lease_calculate.class, leaseForFix)).exec(
                    InvoiceRunType.RETRO_RUN,
                    Collections.singletonList(LeaseItemType.ENTRY_FEE),
                    VT.ld(2018, 1, 1),
                    VT.ld(2018, 1, 1),
                    VT.ld(2018, 1, 2)
                    );

            // then
            Assertions.assertThat(invoiceForLeaseRepository.findByLease(leaseForFix).size()).isEqualTo(1);
            Invoice invoiceForEntryFee = invoiceForLeaseRepository.findByLease(leaseForFix).get(0);
            Assertions.assertThat(invoiceForEntryFee.getTotalNetAmount()).isEqualTo(entryFeeTerm.getValue());

        }

    }

    public static class VatRoundingForItalianInvoices extends InvoiceService_IntegTest {

        @Before
        public void setupTransactionalData() {
            runFixtureScript(new FixtureScript() {
                @Override
                protected void execute(final ExecutionContext ec) {

                    ec.executeChildren(this,
                            LeaseItemForRent_enum.RonTopModel001It);

                }
            });
        }

        @Test
        public void italian_invoice_with_rounding_issues_is_corrected_on_invoicing() throws Exception {

            // given - italian lease with rounding problems
            docFragmentRepository.create("org.estatio.dom.lease.invoicing.ssrs.InvoiceAttributesVM", "description", "/ITA/RON", "");
            docFragmentRepository.create("org.estatio.dom.lease.invoicing.ssrs.InvoiceAttributesVM", "preliminaryLetterDescription", "/ITA/RON", "");
            docFragmentRepository.create("org.estatio.dom.lease.invoicing.ssrs.InvoiceItemAttributesVM", "description", "/ITA/RON", "");

            Lease lease = Lease_enum.RonTopModel001It.findUsing(serviceRegistry);
            mixin(Lease_calculate.class, lease).exec(
                    InvoiceRunType.NORMAL_RUN,
                    Collections.singletonList(LeaseItemType.RENT),
                    VT.ld(2019,1, 1), VT.ld(2019, 1, 1), VT.ld(2019,1,2));

            InvoiceForLease invoice = invoiceForLeaseRepository.findByLease(lease).get(0);
            InvoiceItem rentItem = invoice.getItems().first();
            Charge charge = rentItem.getCharge();
            rentItem.remove();

            InvoiceItem item = mixin(InvoiceForLease._newItem.class, invoice).$$(charge, VT.bd("1"), VT.bd("0.08"), null, null);
            Assertions.assertThat(item.getVatAmount()).isEqualTo(VT.bd("0.02"));
            Assertions.assertThat(item.getGrossAmount()).isEqualTo(VT.bd("0.10"));

            InvoiceItem itemCausingRoundingProblem = mixin(InvoiceForLease._newItem.class, invoice).$$(charge, VT.bd("1"), VT.bd("0.17"), null, null);
            Assertions.assertThat(itemCausingRoundingProblem.getVatAmount()).isEqualTo(VT.bd("0.04"));
            Assertions.assertThat(itemCausingRoundingProblem.getGrossAmount()).isEqualTo(VT.bd("0.21"));

            // when
            mixin(InvoiceForLease._approve.class, invoice).$$();
            // then still not corrected
            Assertions.assertThat(invoice.getItems().first().getVatAmount()).isEqualTo("0.04");
            Assertions.assertThat(invoice.getItems().first().getGrossAmount()).isEqualTo("0.21");

            // when
            mixin(InvoiceForLease._collect.class, invoice).$$();
            // then still not corrected
            Assertions.assertThat(invoice.getItems().first().getVatAmount()).isEqualTo("0.04");
            Assertions.assertThat(invoice.getItems().first().getGrossAmount()).isEqualTo("0.21");

            // when
            mixin(InvoiceForLease._invoice.class, invoice).$$(VT.ld(2019, 1, 1));
            // then the largest amount is corrected
            Assertions.assertThat(invoice.getItems().first().getVatAmount()).isEqualTo("0.03");
            Assertions.assertThat(invoice.getItems().first().getGrossAmount()).isEqualTo("0.20");

        }

        @Inject InvoiceForLeaseRepository invoiceForLeaseRepository;

        @Inject DocFragmentRepository docFragmentRepository;

    }

}


text:
namespace media {
namespace cast {

namespace {
static const uint32 kSendingSsrc = 0x12345678;
static const std::string kCName("test@10.1.1.1");
}  // namespace

class TestRtcpTransport : public PacedPacketSender {
 public:
  TestRtcpTransport()
      : expected_packet_length_(0),
        packet_count_(0) {
  }

  virtual bool SendRtcpPacket(const Packet& packet) OVERRIDE {
    EXPECT_EQ(expected_packet_length_, packet.size());
    EXPECT_EQ(0, memcmp(expected_packet_, &(packet[0]), packet.size()));
    packet_count_++;
    return true;
  }

  virtual bool SendPackets(const PacketList& packets) OVERRIDE {
    return false;
  }

  virtual bool ResendPackets(const PacketList& packets) OVERRIDE {
    return false;
  }

  void SetExpectedRtcpPacket(const uint8* rtcp_buffer, size_t length) {
    expected_packet_length_ = length;
    memcpy(expected_packet_, rtcp_buffer, length);
  }

  int packet_count() const { return packet_count_; }

 private:
  uint8 expected_packet_[kMaxIpPacketSize];
  size_t expected_packet_length_;
  int packet_count_;
};

class RtcpBuilderTest : public ::testing::Test {
 protected:
  RtcpBuilderTest()
      : task_runner_(new test::FakeSingleThreadTaskRunner(&testing_clock_)),
        cast_environment_(new CastEnvironment(&testing_clock_, task_runner_,
            task_runner_, task_runner_, task_runner_, task_runner_,
            GetDefaultCastSenderLoggingConfig())),
        rtcp_builder_(new RtcpBuilder(&test_transport_, kSendingSsrc, kCName)) {
  }

  base::SimpleTestTickClock testing_clock_;
  TestRtcpTransport test_transport_;
  scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_;
  scoped_refptr<CastEnvironment> cast_environment_;
  scoped_ptr<RtcpBuilder> rtcp_builder_;
};

TEST_F(RtcpBuilderTest, RtcpSenderReport) {
  RtcpSenderInfo sender_info;
  sender_info.ntp_seconds = kNtpHigh;
  sender_info.ntp_fraction = kNtpLow;
  sender_info.rtp_timestamp = kRtpTimestamp;
  sender_info.send_packet_count = kSendPacketCount;
  sender_info.send_octet_count = kSendOctetCount;

  // Sender report + c_name.
  TestRtcpPacketBuilder p;
  p.AddSr(kSendingSsrc, 0);
  p.AddSdesCname(kSendingSsrc, kCName);
  test_transport_.SetExpectedRtcpPacket(p.Packet(), p.Length());

  rtcp_builder_->SendRtcpFromRtpSender(RtcpBuilder::kRtcpSr,
                                       &sender_info,
                                       NULL,
                                       NULL,
                                       kSendingSsrc,
                                       kCName);

  EXPECT_EQ(1, test_transport_.packet_count());
}

TEST_F(RtcpBuilderTest, RtcpSenderReportWithDlrr) {
  RtcpSenderInfo sender_info;
  sender_info.ntp_seconds = kNtpHigh;
  sender_info.ntp_fraction = kNtpLow;
  sender_info.rtp_timestamp = kRtpTimestamp;
  sender_info.send_packet_count = kSendPacketCount;
  sender_info.send_octet_count = kSendOctetCount;

  // Sender report + c_name + dlrr.
  TestRtcpPacketBuilder p1;
  p1.AddSr(kSendingSsrc, 0);
  p1.AddSdesCname(kSendingSsrc, kCName);
  p1.AddXrHeader(kSendingSsrc);
  p1.AddXrDlrrBlock(kSendingSsrc);
  test_transport_.SetExpectedRtcpPacket(p1.Packet(), p1.Length());

  RtcpDlrrReportBlock dlrr_rb;
  dlrr_rb.last_rr = kLastRr;
  dlrr_rb.delay_since_last_rr = kDelayLastRr;

  rtcp_builder_->SendRtcpFromRtpSender(
      RtcpBuilder::kRtcpSr | RtcpBuilder::kRtcpDlrr,
      &sender_info,
      &dlrr_rb,
      NULL,
      kSendingSsrc,
      kCName);

  EXPECT_EQ(1, test_transport_.packet_count());
}

TEST_F(RtcpBuilderTest, RtcpSenderReportWithDlrrAndLog) {
  RtcpSenderInfo sender_info;
  sender_info.ntp_seconds = kNtpHigh;
  sender_info.ntp_fraction = kNtpLow;
  sender_info.rtp_timestamp = kRtpTimestamp;
  sender_info.send_packet_count = kSendPacketCount;
  sender_info.send_octet_count = kSendOctetCount;

  // Sender report + c_name + dlrr + sender log.
  TestRtcpPacketBuilder p;
  p.AddSr(kSendingSsrc, 0);
  p.AddSdesCname(kSendingSsrc, kCName);
  p.AddXrHeader(kSendingSsrc);
  p.AddXrDlrrBlock(kSendingSsrc);
  p.AddSenderLog(kSendingSsrc);
  p.AddSenderFrameLog(kRtcpSenderFrameStatusSentToNetwork, kRtpTimestamp);

  test_transport_.SetExpectedRtcpPacket(p.Packet(), p.Length());

  RtcpDlrrReportBlock dlrr_rb;
  dlrr_rb.last_rr = kLastRr;
  dlrr_rb.delay_since_last_rr = kDelayLastRr;

  RtcpSenderFrameLogMessage sender_frame_log;
  sender_frame_log.frame_status = kRtcpSenderFrameStatusSentToNetwork;
  sender_frame_log.rtp_timestamp = kRtpTimestamp;

  RtcpSenderLogMessage sender_log;
  sender_log.push_back(sender_frame_log);

  rtcp_builder_->SendRtcpFromRtpSender(
      RtcpBuilder::kRtcpSr | RtcpBuilder::kRtcpDlrr |
          RtcpBuilder::kRtcpSenderLog,
      &sender_info,
      &dlrr_rb,
      &sender_log,
      kSendingSsrc,
      kCName);

  EXPECT_EQ(1, test_transport_.packet_count());
  EXPECT_TRUE(sender_log.empty());
}

TEST_F(RtcpBuilderTest, RtcpSenderReporWithTooManyLogFrames) {
  RtcpSenderInfo sender_info;
  sender_info.ntp_seconds = kNtpHigh;
  sender_info.ntp_fraction = kNtpLow;
  sender_info.rtp_timestamp = kRtpTimestamp;
  sender_info.send_packet_count = kSendPacketCount;
  sender_info.send_octet_count = kSendOctetCount;

  // Sender report + c_name + sender log.
  TestRtcpPacketBuilder p;
  p.AddSr(kSendingSsrc, 0);
  p.AddSdesCname(kSendingSsrc, kCName);
  p.AddSenderLog(kSendingSsrc);

  for (int i = 0; i < 359; ++i) {
    p.AddSenderFrameLog(kRtcpSenderFrameStatusSentToNetwork,
                        kRtpTimestamp + i * 90);
  }
  test_transport_.SetExpectedRtcpPacket(p.Packet(), p.Length());

  RtcpSenderLogMessage sender_log;
  for (int j = 0; j < 400; ++j) {
    RtcpSenderFrameLogMessage sender_frame_log;
    sender_frame_log.frame_status = kRtcpSenderFrameStatusSentToNetwork;
    sender_frame_log.rtp_timestamp = kRtpTimestamp + j * 90;
    sender_log.push_back(sender_frame_log);
  }

  rtcp_builder_->SendRtcpFromRtpSender(
      RtcpBuilder::kRtcpSr | RtcpBuilder::kRtcpSenderLog,
      &sender_info,
      NULL,
      &sender_log,
      kSendingSsrc,
      kCName);

  EXPECT_EQ(1, test_transport_.packet_count());
  EXPECT_EQ(41u, sender_log.size());
}

}  // namespace cast
}  // namespace media


text:
export default class Descriptor {

    private _contents : number[] = []

    public constructor(obj? : any) {

        if (obj instanceof Array) {
            this._contents = (obj as number[]);
        } else if (typeof obj === 'string') {
            this._contents = (obj as string).split("-").map(x => x === '?' ? -1 : Number(x));
            let strIndex = obj as string;
        }
    }

    toString() : string {
        return this._contents.map(x => x < 0 ? "?" : String(x)).join("-");
    }

    iterator() : DescriptorIterator {
        return new DescriptorIterator(this);
    }

    append(index : number|null) {
        this._contents.push(index === null ? -1 : index);
    }

    at(position : number) : number {
        let index = this._contents[position];

        if (index < 0)
            return null;

        return index;
    }

    get length() : number {
        return this._contents.length;
    }
}

class DescriptorIterator {

    private _descriptor : Descriptor;
    private _position : number = 0;

    public constructor(descriptor:Descriptor) {
        this._descriptor = descriptor;
    }

    public next() : number {

        if (this._position >= this._descriptor.length) {
            throw "no more items";
        }

        let index = this._descriptor.at(this._position);

        this._position += 1;

        return index;
    }
}