text:
import contextlib
import mock

from neutron.tests import base

from neutron_lbaas.common.cert_manager import cert_manager
from neutron_lbaas.common.tls_utils import cert_parser
from neutron_lbaas.services.loadbalancer import data_models
from neutron_lbaas.services.loadbalancer.drivers.haproxy import jinja_cfg
from neutron_lbaas.tests.unit.services.loadbalancer.drivers.haproxy.\
    sample_configs import sample_configs

class TestHaproxyCfg(base.BaseTestCase):
    def test_save_config(self):
        with contextlib.nested(
            mock.patch('neutron_lbaas.services.loadbalancer.'
                       'drivers.haproxy.jinja_cfg.render_loadbalancer_obj'),
            mock.patch('neutron.agent.linux.utils.replace_file')
        ) as (r_t, replace):
            r_t.return_value = 'fake_rendered_template'
            lb = mock.Mock()
            jinja_cfg.save_config('test_conf_path', lb, 'test_sock_path',
                                  'nogroup',
                                  'fake_state_path')
            r_t.assert_called_once_with(lb,
                                        'nogroup',
                                        'test_sock_path',
                                        'fake_state_path')
            replace.assert_called_once_with('test_conf_path',
                                            'fake_rendered_template')

    def test_get_template(self):
        template = jinja_cfg._get_template()
        self.assertEqual('haproxy.loadbalancer.j2', template.name)

    def test_render_template_tls_termination(self):
        lb = sample_configs.sample_loadbalancer_tuple(
            proto='TERMINATED_HTTPS', tls=True, sni=True)

        fe = ("frontend sample_listener_id_1\n"
              "    option tcplog\n"
              "    maxconn 98\n"
              "    option forwardfor\n"
              "    bind 10.0.0.2:443"
              " ssl crt /v2/sample_listener_id_1/fakeCNM.pem"
              " crt /v2/sample_listener_id_1\n"
              "    mode http\n"
              "    default_backend sample_pool_id_1\n\n")
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    redirect scheme https if !{ ssl_fc }\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    timeout check 31\n"
              "    option httpchk GET /index.html\n"
              "    http-check expect rstatus %s\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82"
              " weight 13 check inter 30s fall 3 cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82"
              " weight 13 check inter 30s fall 3 cookie "
              "sample_member_id_2\n\n"
              % sample_configs.PIPED_CODES)
        with mock.patch('os.makedirs'):
            with mock.patch('os.listdir'):
                with mock.patch.object(jinja_cfg, 'utils'):
                    with mock.patch.object(
                            jinja_cfg, '_process_tls_certificates') as crt:
                        crt.return_value = {
                            'tls_cert': lb.listeners[0]
                            .default_tls_container,
                            'sni_certs': [lb.listeners[0]
                                          .sni_containers[0].tls_container]}
                        rendered_obj = jinja_cfg.render_loadbalancer_obj(
                            lb, 'nogroup',
                            '/sock_path',
                            '/v2')
                        self.assertEqual(
                            sample_configs.sample_base_expected_config(
                                frontend=fe, backend=be),
                            rendered_obj)

    def test_render_template_tls_termination_no_sni(self):
        lb = sample_configs.sample_loadbalancer_tuple(
            proto='TERMINATED_HTTPS', tls=True)

        fe = ("frontend sample_listener_id_1\n"
              "    option tcplog\n"
              "    maxconn 98\n"
              "    option forwardfor\n"
              "    bind 10.0.0.2:443"
              " ssl crt /v2/sample_listener_id_1/fakeCNM.pem\n"
              "    mode http\n"
              "    default_backend sample_pool_id_1\n\n")
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    redirect scheme https if !{ ssl_fc }\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    timeout check 31\n"
              "    option httpchk GET /index.html\n"
              "    http-check expect rstatus %s\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_2\n\n"
              % sample_configs.PIPED_CODES)
        with mock.patch('os.makedirs'):
            with mock.patch('neutron.agent.linux.utils.replace_file'):
                with mock.patch('os.listdir'):
                    with mock.patch.object(jinja_cfg, 'utils'):
                        with mock.patch.object(
                                jinja_cfg, '_process_tls_certificates') as crt:
                            crt.return_value = {
                                'tls_cert': lb.listeners[0]
                                .default_tls_container,
                                'sni_certs': []}
                            rendered_obj = jinja_cfg.render_loadbalancer_obj(
                                lb, 'nogroup',
                                '/sock_path',
                                '/v2')
                            self.assertEqual(
                                sample_configs.sample_base_expected_config(
                                    frontend=fe, backend=be),
                                rendered_obj)

    def test_render_template_http(self):
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    timeout check 31\n"
              "    option httpchk GET /index.html\n"
              "    http-check expect rstatus %s\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_2\n\n"
              % sample_configs.PIPED_CODES)
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(
            sample_configs.sample_base_expected_config(backend=be),
            rendered_obj)

    def test_render_template_https(self):
        fe = ("frontend sample_listener_id_1\n"
              "    option tcplog\n"
              "    maxconn 98\n"
              "    bind 10.0.0.2:443\n"
              "    mode tcp\n"
              "    default_backend sample_pool_id_1\n\n")
        be = ("backend sample_pool_id_1\n"
              "    mode tcp\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    timeout check 31\n"
              "    option httpchk GET /index.html\n"
              "    http-check expect rstatus %s\n"
              "    option ssl-hello-chk\n"
              "    server sample_member_id_1 10.0.0.99:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82 "
              "weight 13 check inter 30s fall 3 cookie sample_member_id_2\n\n"
              % sample_configs.PIPED_CODES)
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(proto='HTTPS'),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(sample_configs.sample_base_expected_config(
            frontend=fe, backend=be), rendered_obj)

    def test_render_template_no_monitor_http(self):
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82 weight 13 "
              "cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82 weight 13 "
              "cookie sample_member_id_2\n\n")
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(
                proto='HTTP', monitor=False),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(sample_configs.sample_base_expected_config(
            backend=be), rendered_obj)

    def test_render_template_no_monitor_https(self):
        fe = ("frontend sample_listener_id_1\n"
              "    option tcplog\n"
              "    maxconn 98\n"
              "    bind 10.0.0.2:443\n"
              "    mode tcp\n"
              "    default_backend sample_pool_id_1\n\n")
        be = ("backend sample_pool_id_1\n"
              "    mode tcp\n"
              "    balance roundrobin\n"
              "    cookie SRV insert indirect nocache\n"
              "    server sample_member_id_1 10.0.0.99:82 weight 13 "
              "cookie sample_member_id_1\n"
              "    server sample_member_id_2 10.0.0.98:82 weight 13 "
              "cookie sample_member_id_2\n\n")
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(
                proto='HTTPS', monitor=False),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(sample_configs.sample_base_expected_config(
            frontend=fe, backend=be), rendered_obj)

    def test_render_template_no_persistence_https(self):
        fe = ("frontend sample_listener_id_1\n"
              "    option tcplog\n"
              "    maxconn 98\n"
              "    bind 10.0.0.2:443\n"
              "    mode tcp\n"
              "    default_backend sample_pool_id_1\n\n")
        be = ("backend sample_pool_id_1\n"
              "    mode tcp\n"
              "    balance roundrobin\n"
              "    server sample_member_id_1 10.0.0.99:82 weight 13\n"
              "    server sample_member_id_2 10.0.0.98:82 weight 13\n\n")
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(
                proto='HTTPS', monitor=False, persistence=False),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(sample_configs.sample_base_expected_config(
            frontend=fe, backend=be), rendered_obj)

    def test_render_template_no_persistence_http(self):
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    balance roundrobin\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82 weight 13\n"
              "    server sample_member_id_2 10.0.0.98:82 weight 13\n\n")
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(
                proto='HTTP', monitor=False, persistence=False),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(sample_configs.sample_base_expected_config(
            backend=be), rendered_obj)

    def test_render_template_sourceip_persistence(self):
        be = ("backend sample_pool_id_1\n"
              "    mode http\n"
              "    balance roundrobin\n"
              "    stick-table type ip size 10k\n"
              "    stick on src\n"
              "    timeout check 31\n"
              "    option httpchk GET /index.html\n"
              "    http-check expect rstatus %s\n"
              "    option forwardfor\n"
              "    server sample_member_id_1 10.0.0.99:82 "
              "weight 13 check inter 30s fall 3\n"
              "    server sample_member_id_2 10.0.0.98:82 "
              "weight 13 check inter 30s fall 3\n\n"
              % sample_configs.PIPED_CODES)
        rendered_obj = jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_loadbalancer_tuple(
                persistence_type='SOURCE_IP'),
            'nogroup', '/sock_path', '/v2')
        self.assertEqual(
            sample_configs.sample_base_expected_config(backend=be),
            rendered_obj)

    def test_render_template_appsession_persistence(self):
        with mock.patch('os.makedirs') as md:
            with mock.patch.object(jinja_cfg, 'utils'):
                md.return_value = '/data/dirs/'
                be = ("backend sample_pool_id_1\n"
                      "    mode http\n"
                      "    balance roundrobin\n"
                      "    appsession APP_COOKIE len 56 timeout 3h\n"
                      "    timeout check 31\n"
                      "    option httpchk GET /index.html\n"
                      "    http-check expect rstatus %s\n"
                      "    option forwardfor\n"
                      "    server sample_member_id_1 10.0.0.99:82 "
                      "weight 13 check inter 30s fall 3\n"
                      "    server sample_member_id_2 10.0.0.98:82 "
                      "weight 13 check inter 30s fall 3\n\n"
                      % sample_configs.PIPED_CODES)
                rendered_obj = jinja_cfg.render_loadbalancer_obj(
                    sample_configs.sample_loadbalancer_tuple(
                        persistence_type='APP_COOKIE'),
                    'nogroup', '/sock_path',
                    '/v2')
                self.assertEqual(
                    sample_configs.sample_base_expected_config(backend=be),
                    rendered_obj)

    def test_retrieve_crt_path(self):
        with mock.patch('os.makedirs'):
            with mock.patch('os.path.isdir') as isdir:
                with mock.patch.object(jinja_cfg, '_retrieve_crt_path') as rcp:
                    isdir.return_value = True
                    rcp.return_value = '/v2/loadbalancers/lb_id_1/' \
                                       'cont_id_1.pem'
                    ret = jinja_cfg._retrieve_crt_path(
                        '/v2/loadbalancers', 'lb_id_1', 'cont_id_1')
                    self.assertEqual(
                        '/v2/loadbalancers/lb_id_1/cont_id_1.pem', ret)

    def test_store_listener_crt(self):
        l = sample_configs.sample_listener_tuple(tls=True, sni=True)
        with mock.patch('os.makedirs'):
            with mock.patch('neutron.agent.linux.utils.replace_file'):
                    ret = jinja_cfg._store_listener_crt(
                        '/v2/loadbalancers', l, l.default_tls_container)
                    self.assertEqual(
                        '/v2/loadbalancers/sample_listener_id_1/fakeCNM.pem',
                        ret)

    def test_process_tls_certificates(self):
        sl = sample_configs.sample_listener_tuple(tls=True, sni=True)
        tls = data_models.TLSContainer(primary_cn='fakeCN',
                                       certificate='imaCert',
                                       private_key='imaPrivateKey',
                                       intermediates=['imainter1',
                                                      'imainter2'])
        cert = mock.Mock(spec=cert_manager.Cert)
        cert.get_private_key.return_value = tls.private_key
        cert.get_certificate.return_value = tls.certificate
        cert.get_intermediates.return_value = tls.intermediates

        with contextlib.nested(
            mock.patch.object(jinja_cfg, '_map_cert_tls_container'),
            mock.patch.object(jinja_cfg, '_store_listener_crt'),
            mock.patch.object(cert_parser, 'get_host_names'),
            mock.patch.object(jinja_cfg, 'CERT_MANAGER_PLUGIN')
        ) as (map, store_cert, get_host_names, cert_mgr):
            map.return_value = tls
            cert_mgr_mock = mock.Mock(spec=cert_manager.CertManager)
            cert_mgr_mock.get_cert.return_value = cert
            cert_mgr.CertManager.return_value = cert_mgr_mock
            get_host_names.return_value = {'cn': 'fakeCN'}
            jinja_cfg._process_tls_certificates(sl)

            # Ensure get_cert is called three times
            calls_certs = [
                mock.call(sl.default_tls_container.id),
                mock.call('cont_id_2'),
                mock.call('cont_id_3')]
            cert_mgr_mock.get_cert.call_args_list == calls_certs

            # Ensure store_cert is called three times
            calls_ac = [mock.call('/v2/',
                                  'sample_listener_id_1',
                                  tls),
                        mock.call('/v2/',
                                  'sample_listener_id_1',
                                  tls),
                        mock.call('/v2/',
                                  'sample_listener_id_1',
                                  tls)]
            store_cert.call_args_list == calls_ac

    def test_get_primary_cn(self):
        cert = mock.MagicMock()

        with mock.patch.object(cert_parser, 'get_host_names') as cp:
            cp.return_value = {'cn': 'fakeCN'}
            cn = jinja_cfg._get_primary_cn(cert.get_certificate())
            self.assertEqual('fakeCN', cn)

    def test_map_cert_tls_container(self):
        tls = data_models.TLSContainer(primary_cn='fakeCN',
                                       certificate='imaCert',
                                       private_key='imaPrivateKey',
                                       intermediates=['imainter1',
                                                      'imainter2'])
        cert = mock.MagicMock()
        cert.get_private_key.return_value = tls.private_key
        cert.get_certificate.return_value = tls.certificate
        cert.get_intermediates.return_value = tls.intermediates
        cert.get_private_key_passphrase.return_value = 'passphrase'
        with mock.patch.object(cert_parser, 'get_host_names') as cp:
            with mock.patch.object(cert_parser, 'dump_private_key') as dp:
                cp.return_value = {'cn': 'fakeCN'}
                dp.return_value = 'imaPrivateKey'
                self.assertEqual(tls.primary_cn,
                                 jinja_cfg._map_cert_tls_container(
                                     cert).primary_cn)
                self.assertEqual(tls.certificate,
                                 jinja_cfg._map_cert_tls_container(
                                     cert).certificate)
                self.assertEqual(tls.private_key,
                                 jinja_cfg._map_cert_tls_container(
                                     cert).private_key)
                self.assertEqual(tls.intermediates,
                                 jinja_cfg._map_cert_tls_container(
                                     cert).intermediates)

    def test_build_pem(self):
        expected = 'imainter\nimainter2\nimacert\nimakey'
        tls_tupe = sample_configs.sample_tls_container_tuple(
            certificate='imacert', private_key='imakey',
            intermediates=['imainter', 'imainter2'])
        self.assertEqual(expected, jinja_cfg._build_pem(tls_tupe))

    def test_transform_session_persistence(self):
        in_persistence = sample_configs.sample_session_persistence_tuple()
        ret = jinja_cfg._transform_session_persistence(in_persistence)
        self.assertEqual(sample_configs.RET_PERSISTENCE, ret)

    def test_transform_health_monitor(self):
        in_persistence = sample_configs.sample_health_monitor_tuple()
        ret = jinja_cfg._transform_health_monitor(in_persistence)
        self.assertEqual(sample_configs.RET_MONITOR, ret)

    def test_transform_member(self):
        in_member = sample_configs.sample_member_tuple('sample_member_id_1',
                                                       '10.0.0.99')
        ret = jinja_cfg._transform_member(in_member)
        self.assertEqual(sample_configs.RET_MEMBER_1, ret)

    def test_transform_pool(self):
        in_pool = sample_configs.sample_pool_tuple()
        ret = jinja_cfg._transform_pool(in_pool)
        self.assertEqual(sample_configs.RET_POOL, ret)

    def test_transform_pool_admin_state_down(self):
        in_pool = sample_configs.sample_pool_tuple(hm_admin_state=False)
        ret = jinja_cfg._transform_pool(in_pool)
        result = sample_configs.RET_POOL
        result['health_monitor'] = ''
        self.assertEqual(result, ret)

    def test_transform_listener(self):
        in_listener = sample_configs.sample_listener_tuple()
        ret = jinja_cfg._transform_listener(in_listener, '/v2')
        self.assertEqual(sample_configs.RET_LISTENER, ret)

    def test_transform_loadbalancer(self):
        in_lb = sample_configs.sample_loadbalancer_tuple()
        ret = jinja_cfg._transform_loadbalancer(in_lb, '/v2')
        self.assertEqual(sample_configs.RET_LB, ret)

    def test_include_member(self):
        ret = jinja_cfg._include_member(
            sample_configs.sample_member_tuple('sample_member_id_1',
                                               '10.0.0.99'))
        self.assertTrue(ret)

    def test_include_member_invalid_status(self):
        ret = jinja_cfg._include_member(
            sample_configs.sample_member_tuple('sample_member_id_1',
                                               '10.0.0.99', status='PENDING'))
        self.assertFalse(ret)

    def test_include_member_invalid_admin_state(self):
        ret = jinja_cfg._include_member(
            sample_configs.sample_member_tuple('sample_member_id_1',
                                               '10.0.0.99',
                                               admin_state_up=False))
        self.assertFalse(ret)

    def test_expand_expected_codes(self):
        exp_codes = ''
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes), set([]))
        exp_codes = '200'
        self.assertEqual(
            jinja_cfg._expand_expected_codes(exp_codes), set(['200']))
        exp_codes = '200, 201'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201']))
        exp_codes = '200, 201,202'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201', '202']))
        exp_codes = '200-202'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201', '202']))
        exp_codes = '200-202, 205'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201', '202', '205']))
        exp_codes = '200, 201-203'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201', '202', '203']))
        exp_codes = '200, 201-203, 205'
        self.assertEqual(jinja_cfg._expand_expected_codes(exp_codes),
                         set(['200', '201', '202', '203', '205']))
        exp_codes = '201-200, 205'
        self.assertEqual(
            jinja_cfg._expand_expected_codes(exp_codes), set(['205']))


text:
<?php

namespace Dwf\PronosticsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Country
 *
 * @ORM\Table(name="country")
 * @ORM\Entity(repositoryClass="Dwf\PronosticsBundle\Repository\CountryRepository")
 */
class Country
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Country
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

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

redpajama_set_name: RedPajamaGithub


text:
https://opentelemetry.io/

OpenTelemetry is a collection of tools, APIs, and SDKs. Use it to instrument, generate, collect, and export telemetry data (metrics, logs, and traces) to help you analyze your software's performance and behavior.

## Integration

You can find it [here](https://opentelemetry.io/docs/instrumentation/net/getting-started/) about how to use OpenTelemetry in console applications or ASP.NET Core, at here we mainly describe how to tracing CAP data to OpenTelemetry.

### Configuration

Install the CAP OpenTelemetry package into the project.

```C#
dotnet add package DotNetCore.Cap.OpenTelemetry
```

The OpenTelemetry data comes from [diagnostics](diagnostics.md), add the instrumentation of CAP to the configuration of OpenTelemetry.

```C#
services.AddOpenTelemetryTracing((builder) => builder
    .AddAspNetCoreInstrumentation()
    .AddCapInstrumentation()    // <-- Add this line
    .AddZipkinExporter()
);
```

Here is a diagram of CAP's tracking data in Zipkin:

<img src="/img/opentelemetry.png">


text:
using Mendham.Events.Components;
using Mendham.Events.Test.TestObjects;
using Mendham.Testing;
using Moq;
using System.Collections.Generic;
using System.Linq;

namespace Mendham.Events.Test.Fixtures
{
    public class EventLoggerProcessorFixture : Fixture<EventLoggerProcessor>
    {
        public IEventLogger EventLogger1 { get; set; }
        public IEventLogger EventLogger2 { get; set; }

        private List<IEventLogger> _loggers;

        public EventLoggerProcessorFixture()
        {
            _loggers = new List<IEventLogger>();
        }

        public TestEvent Event { get; set; }

        public override EventLoggerProcessor CreateSut()
        {
            var loggersAtCreation = _loggers.ToList();
            return new EventLoggerProcessor(() => loggersAtCreation);
        }

        public void AddLogger(IEventLogger logger)
        {
            _loggers.Add(logger);
        }

        public override void ResetFixture()
        {
            base.ResetFixture();

            _loggers.Clear();

            EventLogger1 = Mock.Of<IEventLogger>();
            EventLogger2 = Mock.Of<IEventLogger>();
        }
    }
}


text:
package org.ocpsoft.common.util;

/**
 * Utility methods for making precondition/postcondition assertions.
 *
 * @author Lincoln Baxter, III
 */
public final class Assert
{
   private Assert()
   {}

   /**
    * Throw an exception if the given {@link Object} is not null.
    */
   public static void isNull(final Object object, final String message) throws IllegalArgumentException
   {
      if (object != null)
      {
         throw new IllegalArgumentException(message);
      }
   }

   /**
    * Throw an exception if the given {@link Object} is null.
    */
   public static void notNull(final Object object, final String message) throws IllegalArgumentException
   {
      if (object == null)
      {
         throw new IllegalArgumentException(message);
      }
   }

   /**
    * Throw an exception if the given value is not true.
    */
   public static void assertTrue(final boolean value, final String message) throws IllegalArgumentException
   {
      if (value != true)
      {
         throw new IllegalArgumentException(message);
      }
   }

   /**
    * Throw an exception if the given value is not false.
    */
   public static void assertFalse(final boolean value, final String message) throws IllegalArgumentException
   {
      if (value != false)
      {
         throw new IllegalArgumentException(message);
      }
   }
}


text:
extern const U64 kSievePrimes[];
extern const size_t kNumSievePrimes;
extern const U64 kNextPostSievePrime;


text:
package utility;

public class Pair {
	public int r;
	public int c;

	public Pair(int row, int col) {
		r = row;
		c = col;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <InstrumentSensitivity>
    <Value>419430.4</Value>
    <Frequency>2.5</Frequency>
    <InputUnits>
      <Name>V</Name>
    </InputUnits>
    <OutputUnits>
      <Name>count</Name>
    </OutputUnits>
  </InstrumentSensitivity>
  <Stage number="1">
    <Coefficients resourceId="Coefficients#Q330S+_FLbelow100-10">
      <InputUnits>
        <Name>V</Name>
      </InputUnits>
      <OutputUnits>
        <Name>count</Name>
      </OutputUnits>
      <CfTransferFunctionType>DIGITAL</CfTransferFunctionType>
    </Coefficients>
    <Decimation>
      <InputSampleRate>1</InputSampleRate>
      <Factor>1</Factor>
      <Offset>0</Offset>
      <Delay>0</Delay>
      <Correction>0</Correction>
    </Decimation>
    <StageGain>
      <Value>419430.4</Value>
      <Frequency>2.5</Frequency>
    </StageGain>
  </Stage>
  <Stage number="2">
    <FIR resourceId="FIR#Q330S+_FLbelow100-10" name="Q330S+_FLbelow100-10">
      <InputUnits>
        <Name>count</Name>
      </InputUnits>
      <OutputUnits>
        <Name>count</Name>
      </OutputUnits>
      <Symmetry>NONE</Symmetry>
      <NumeratorCoefficient i="1">1.8190256e-17</NumeratorCoefficient>
      <NumeratorCoefficient i="2">1.0051919e-12</NumeratorCoefficient>
      <NumeratorCoefficient i="3">-1.247748e-11</NumeratorCoefficient>
      <NumeratorCoefficient i="4">-1.8647005e-11</NumeratorCoefficient>
      <NumeratorCoefficient i="5">3.6412782e-10</NumeratorCoefficient>
      <NumeratorCoefficient i="6">1.5765226e-09</NumeratorCoefficient>
      <NumeratorCoefficient i="7">8.1168464e-09</NumeratorCoefficient>
      <NumeratorCoefficient i="8">-1.0723788e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="9">1.1619641e-08</NumeratorCoefficient>
      <NumeratorCoefficient i="10">4.5558403e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="11">-3.7521996e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="12">3.8200366e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="13">9.4136356e-08</NumeratorCoefficient>
      <NumeratorCoefficient i="14">-8.288413e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="15">1.6259014e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="16">-2.8913645e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="17">3.9620894e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="18">5.0363609e-05</NumeratorCoefficient>
      <NumeratorCoefficient i="19">0.00015505784</NumeratorCoefficient>
      <NumeratorCoefficient i="20">-0.0004909179</NumeratorCoefficient>
      <NumeratorCoefficient i="21">-0.00036404434</NumeratorCoefficient>
      <NumeratorCoefficient i="22">0.00068938036</NumeratorCoefficient>
      <NumeratorCoefficient i="23">-0.0013095578</NumeratorCoefficient>
      <NumeratorCoefficient i="24">0.001417586</NumeratorCoefficient>
      <NumeratorCoefficient i="25">-0.00079100732</NumeratorCoefficient>
      <NumeratorCoefficient i="26">-0.0009041226</NumeratorCoefficient>
      <NumeratorCoefficient i="27">0.0034771077</NumeratorCoefficient>
      <NumeratorCoefficient i="28">-0.0062555521</NumeratorCoefficient>
      <NumeratorCoefficient i="29">0.0080462933</NumeratorCoefficient>
      <NumeratorCoefficient i="30">-0.0073106741</NumeratorCoefficient>
      <NumeratorCoefficient i="31">0.0026339853</NumeratorCoefficient>
      <NumeratorCoefficient i="32">0.004900436</NumeratorCoefficient>
      <NumeratorCoefficient i="33">-0.016046065</NumeratorCoefficient>
      <NumeratorCoefficient i="34">0.027431074</NumeratorCoefficient>
      <NumeratorCoefficient i="35">-0.035286138</NumeratorCoefficient>
      <NumeratorCoefficient i="36">0.034773022</NumeratorCoefficient>
      <NumeratorCoefficient i="37">-0.020715899</NumeratorCoefficient>
      <NumeratorCoefficient i="38">-0.01260638</NumeratorCoefficient>
      <NumeratorCoefficient i="39">0.067725087</NumeratorCoefficient>
      <NumeratorCoefficient i="40">-0.17579081</NumeratorCoefficient>
      <NumeratorCoefficient i="41">0.52604157</NumeratorCoefficient>
      <NumeratorCoefficient i="42">0.70265915</NumeratorCoefficient>
      <NumeratorCoefficient i="43">-0.11835462</NumeratorCoefficient>
      <NumeratorCoefficient i="44">0.0071894441</NumeratorCoefficient>
      <NumeratorCoefficient i="45">0.034533149</NumeratorCoefficient>
      <NumeratorCoefficient i="46">-0.050959588</NumeratorCoefficient>
      <NumeratorCoefficient i="47">0.048421036</NumeratorCoefficient>
      <NumeratorCoefficient i="48">-0.035983145</NumeratorCoefficient>
      <NumeratorCoefficient i="49">0.020069074</NumeratorCoefficient>
      <NumeratorCoefficient i="50">-0.0054360536</NumeratorCoefficient>
      <NumeratorCoefficient i="51">-0.0051096421</NumeratorCoefficient>
      <NumeratorCoefficient i="52">0.0099143523</NumeratorCoefficient>
      <NumeratorCoefficient i="53">-0.011135741</NumeratorCoefficient>
      <NumeratorCoefficient i="54">0.0086839889</NumeratorCoefficient>
      <NumeratorCoefficient i="55">-0.0048487651</NumeratorCoefficient>
      <NumeratorCoefficient i="56">0.0012873927</NumeratorCoefficient>
      <NumeratorCoefficient i="57">0.0011002038</NumeratorCoefficient>
      <NumeratorCoefficient i="58">-0.0020952568</NumeratorCoefficient>
      <NumeratorCoefficient i="59">0.0019480136</NumeratorCoefficient>
      <NumeratorCoefficient i="60">-0.0012632874</NumeratorCoefficient>
      <NumeratorCoefficient i="61">0.00038965037</NumeratorCoefficient>
      <NumeratorCoefficient i="62">-8.7138913e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="63">-0.00066276239</NumeratorCoefficient>
      <NumeratorCoefficient i="64">0.00010454617</NumeratorCoefficient>
      <NumeratorCoefficient i="65">8.0506963e-05</NumeratorCoefficient>
      <NumeratorCoefficient i="66">6.5584775e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="67">-2.5982608e-06</NumeratorCoefficient>
      <NumeratorCoefficient i="68">9.8725222e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="69">-1.4507002e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="70">-4.7504845e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="71">6.8520757e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="72">-4.6192338e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="73">3.7519783e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="74">1.3825561e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="75">-1.3617794e-07</NumeratorCoefficient>
      <NumeratorCoefficient i="76">-1.2015633e-09</NumeratorCoefficient>
      <NumeratorCoefficient i="77">3.5488951e-09</NumeratorCoefficient>
      <NumeratorCoefficient i="78">3.8757759e-10</NumeratorCoefficient>
      <NumeratorCoefficient i="79">3.4494488e-11</NumeratorCoefficient>
      <NumeratorCoefficient i="80">-2.5484328e-11</NumeratorCoefficient>
      <NumeratorCoefficient i="81">1.7170283e-12</NumeratorCoefficient>
      <NumeratorCoefficient i="82">5.3750237e-15</NumeratorCoefficient>
    </FIR>
    <Decimation>
      <InputSampleRate>1</InputSampleRate>
      <Factor>1</Factor>
      <Offset>0</Offset>
      <Delay>0</Delay>
      <Correction>0</Correction>
    </Decimation>
    <StageGain>
      <Value>1</Value>
      <Frequency>2.5</Frequency>
    </StageGain>
  </Stage>
</Response>


text:
package com.cfk.xiaov.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import java.io.File;

/**
 * @创建者 Sean
 * @描述 文件打开工具类
 */
public class FileOpenUtils {

    /**
     * 调用自带的视频播放器
     *
     * @param context
     * @param path
     */
    private static void openVideo(Context context, String path) {
        Uri uri = Uri.parse(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "video/mp4");// "video/mp4"
        context.startActivity(intent);
    }

    /**
     * 调用自带的音频播放器
     *
     * @param context
     * @param path
     */
    private static void openAudio(Context context, String path) {
        File f = new File(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(f), "audio/*");// "audio/mp3"
        context.startActivity(intent);
    }

    /**
     * 调用自带的图库
     *
     * @param context
     * @param path
     */
    private static void openPic(Context context, String path) {
        File f = new File(path);
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), "image/*");
        context.startActivity(intent);
    }

    /**
     * 调用手机上能打开对应类型文件的程序
     *
     * @param context
     * @param path
     * @return true表示成功找到程序,false表示找不到能成功打开的程序
     */
    public static boolean openFile(Context context, String path) {
        String mimeType = MimeTypeUtils.getMimeType(path);
        File f = new File(path);
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), mimeType);
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sunRays</groupId>
  <artifactId>springHibernateTemplateDaoSupport-hbm</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springHibernateTemplateDaoSupport-hbm</name>

  <properties>
		<spring.version>3.2.1.RELEASE</spring.version>
  </properties>

  <dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>${spring.version}</version>
		</dependency>
		<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.2.6.ga</version>
		</dependency>
		<dependency>
      		<groupId>javax.transaction</groupId>
      		<artifactId>jta</artifactId>
      		<version>1.1</version>
    	</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
package com.timeslily.videofile;

import android.provider.BaseColumns;

public class VideoColumns implements BaseColumns {
    public static final String TABLE_NAME = "tb_video";
    /** 视频名称 */
    public static final String VIDEO_NAME = "video_name";
    /** 视频路径 */
//    public static final String VIDEO_PATH = "video_path";
    /** 缩略图缓存路径 */
    public static final String VIDEO_THUBMNAIL_PATH = "video_thumbnail_path";
    /** 父文件路径 */
    public static final String VIDEO_PARENT_PATH = "video_parent_path";
    /** 视频时长 */
    public static final String VIDEO_DURATION = "video_duration";
    /** 是否播放过 */
    public static final String VIDEO_IS_PLAYED = "video_is_played";
    /** 上次播放时间 */
    public static final String VIDEO_LAST_PLAY_TIME = "video_last_play_time";
    /** 最近播放标识 */
    public static final String VIDEO_RECENT_PLAY = "video_recent_play";

}


text:
[clappr](../../index.md) / [io.clappr.player.base](../index.md) / [ErrorInfo](index.md) / [writeToParcel](./write-to-parcel.md)

# writeToParcel

`fun writeToParcel(dest: `[`Parcel`](https://developer.android.com/reference/android/os/Parcel.html)`, flags: `[`Int`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)`): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)


text:
package org.kie.server.controller.api;

public final class KieServerControllerConstants {

    private KieServerControllerConstants() {}

    public static final String KIE_CONTROLLER_SWAGGER_DISABLED = "org.kie.server.controller.swagger.disabled";

    public static final String KIE_CONTROLLER_TEMPLATE_CACHE_TTL = "org.kie.server.controller.template.cache.ttl";

    public static final String KIE_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE =
            "org.kie.server.controller.openshift.prefer.kieserver.service";

    public static final String KIE_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED =
            "org.kie.server.controller.openshift.global.discovery.enabled";

}


text:
/* See license.txt for terms of usage */

Firebug.extend(function(FBL) { with (FBL) {
// ************************************************************************************************

// ************************************************************************************************
// Plugin Module

Firebug.Plugin = extend(Firebug.Module,
{
    getPanel: function()
    {
        return Firebug.chrome ? Firebug.chrome.getPanel("Plugin") : null;
    },

    clear: function()
    {
        alert("clear button clicked");
        this.getPanel().panelNode.innerHTML = "";
    }
});

// ************************************************************************************************
// Plugin Panel

function PluginPanel(){};

PluginPanel.prototype = extend(Firebug.Panel,
{
    name: "Plugin",
    title: "Plugin",

    options: {
        hasToolButtons: true,
        innerHTMLSync: true
    },

    create: function(){
        Firebug.Panel.create.apply(this, arguments);

        this.clearButton = new Button({
            caption: "Clear",
            title: "Clear Panel",
            owner: Firebug.Plugin,
            onClick: Firebug.Plugin.clear
        });
    },

    initialize: function(){
        Firebug.Panel.initialize.apply(this, arguments);

        this.clearButton.initialize();

        this.panelNode.innerHTML = "Hello World!";
    }

});

Firebug.registerPanel(PluginPanel);
Firebug.registerModule(Firebug.Plugin);

// ************************************************************************************************
}});


text:
@implementation SDKView (FLViewGeometry)

+ (id) viewWithFrame:(CGRect) frame {
    return FLAutorelease([[[self class] alloc] initWithFrame:frame]);
}

- (void) moveBy:(CGPoint) delta {
	if(delta.x != 0.0f || delta.y != 0.0f) {
		CGRect frame = self.frame;
		frame.origin.x += delta.x;
		frame.origin.y += delta.y;
		self.frame = frame;
	}
}

- (void) moveBy:(CGFloat) x y:(CGFloat)y {
	if(x != 0.0f || y != 0.0f) {
		CGRect frame = self.frame;
		frame.origin.x += x;
		frame.origin.y += y;
		self.newFrame = frame;
	}
}

- (void) resize:(CGSize) newSize {
	self.newFrame = FLRectSetSizeWithSize(self.frame, newSize);
}

- (void) moveTo:(CGPoint) newOrigin {
	self.newFrame = FLRectSetOrigin(self.frame, newOrigin.x, newOrigin.y);
}

- (void) moveTo:(CGFloat) left top:(CGFloat) top {
	self.newFrame = FLRectSetOrigin(self.frame, left, top);
}

#if DEBUG
+ (void) warnIfNonIntegralFramesInViewHierarchy:(SDKView*) view {
	while(view) {
		if(!FLRectIsIntegral(view.frame)) {
			FLLog(@"Warning a view of type '%@' has non-integral frame: %@",
				NSStringFromClass([view class]),
				NSStringFromCGRect(view.frame));
		}
		view = view.superview;
	}
}

#if IOS
- (SDKColor*) debugBackgroundColor {
    return self.backgroundColor;
}

- (void) setDebugBackgroundColor:(SDKColor*) color {
    self.backgroundColor = color;
}
#endif

#endif

- (CGRect) frameOptimizedForLocation {
	return FLRectOptimizedForViewLocation(self.frame);
}

- (void) setFrameOptimizedForLocation:(CGRect) frame {
	self.newFrame = FLRectOptimizedForViewLocation(frame);
}

- (CGRect) frameOptimizedForSize {
	return FLRectOptimizedForViewSize(self.frame);
}

- (void) setFrameOptimizedForSize:(CGRect) frame {
	self.newFrame = FLRectOptimizedForViewSize(frame);
}

- (BOOL) isFrameOptimized {
	return FLRectIsOptimizedForView(self.frame);
}

- (CGRect) newFrame {
	return self.frame;
}

- (void) setNewFrame:(CGRect) newFrame {
#if DEBUG
	if(!FLRectIsIntegral(newFrame)) {
		FLLog(@"Warning setting non-integral rect in view: %@", NSStringFromCGRect(newFrame));
	}
#endif

	if(!CGRectEqualToRect(newFrame, self.frame)) {
		self.frame = newFrame;
	}

#if DEBUG
	[SDKView warnIfNonIntegralFramesInViewHierarchy:self];
#endif
}

- (BOOL) setFrameIfChanged:(CGRect) newFrame {

    if(!CGRectEqualToRect(newFrame, self.frame)) {
		self.frame = newFrame;
		return YES;
	}

	return NO;
}

- (BOOL) setBoundsIfChanged:(CGRect) newBounds {

    if(!CGRectEqualToRect(newBounds, self.bounds)) {
		self.bounds = newBounds;
		return YES;
	}

	return NO;
}
#if DEBUG
//- (NSMutableString*) debugDescription
//{
//	  NSMutableString* str = [super debugDescription];
//	  [str appendFormat:@"\nview bounds: %@\nview frame: %@\nsuperview bounds: %@",
//			  NSStringFromCGRect(self.bounds),
//			  NSStringFromCGRect(self.frame),
//			  NSStringFromCGRect(self.superview.bounds)];
//	  return str;
//}
#endif

- (CGRect) frameSizedToFitInSuperview:(BOOL) centerInSuperview {
	return self.superview ? self.superview.bounds : CGRectZero;
}

- (CGSize) sizeThatFitsInSuperview {
	return self.superview ? [self frameSizedToFitInSuperview:NO].size : CGSizeZero;
}

- (BOOL) setViewSizeToFitInSuperview:(BOOL) centerInSuperview {
	if(self.superview) {
		return [self setFrameIfChanged:[self frameSizedToFitInSuperview:centerInSuperview]];
	}

	return NO;
}

- (BOOL) setViewSizeToContentSize {
	return NO;
}

- (id) objectByMoniker:(id) aMoniker {
    id outObj = [self objectByMoniker:aMoniker];
    if(!outObj) {
        for(SDKView* view in self.subviews) {
            outObj = [view objectByMoniker:aMoniker];
            if(outObj) {
                break;
            }
        }
    }

    return outObj;
}

@end


text:
@implementation Physics

+ (Physics *) physics {
  return [[Physics alloc] init];
}

- (id) init {
  if(self = [super init]) {
    self.forces = [[NSMutableArray alloc] initWithCapacity:100] ;
    self.forcebank = [[Bank alloc] initWithType:[Force class]] ;
  }
  return self;
}

- (Force *) applyForceToEntity:(GameEntity *) entity {
  Force *output = [self.forcebank withdraw];
  [self.forces addObject:output];

  output.direction = (vec3){0,0,0};
  output.massAcceleration = 0.f;
  output.subject = entity;

  return output;
}

- (void) applyForces {
  const float friction = 0.005f;
  [self.forces removeObjectsMatching: ^(Force *force) {
    if(force.subject == nil) return YES;

    vec3 vector = scale(force.direction, force.massAcceleration / force.subject.mass);
    force.massAcceleration -= friction * force.subject.mass;
    force.subject.origin = add(force.subject.origin, vector);

    if(force.massAcceleration <= 0.f) {
      [self.forcebank deposit: force];
      return YES;
    }
    return NO;
  }];
}

- (void) removeForcesForEntity:(KZEntity *) entity {
  [self.forces removeObjectsMatching: ^(Force *force) {
    return (BOOL)(force.subject == entity);
  }];
}

- (NSArray *) forcesForEntity:(KZEntity *) entity {
  NSMutableArray *output = [[NSMutableArray alloc] init] ;
  for(Force *force in self.forces) {
    if(force.subject == entity) [output addObject:force];
  }

  return [NSArray arrayWithArray: output];
}

- (void) bounceCollidingEntities:(NSArray *) entities {
  NSArray *collisions = nil;
  NSInteger iteration = 0;

  do {
    collisions = [self findAllCollisions: entities];
    for(Collision *c in collisions) {
      c.attacker.origin = c.point;

      [self removeForcesForEntity: c.attacker];
      [self removeForcesForEntity: c.victim];
      Force *victimForce = [self applyForceToEntity:c.victim];
      Force *attackerForce = [self applyForceToEntity:c.attacker];

      victimForce.massAcceleration = c.massAcceleration * 0.6f;
      attackerForce.massAcceleration = c.massAcceleration * 0.4f;
      victimForce.direction = c.direction;
      // TODO: instead of reversing the direction mirror it about the colloding axis.
      attackerForce.direction = iteration > 0 ? scale(c.direction, -1.f) : c.direction;
      NSLog(@"%d %f", iteration, victimForce.massAcceleration);
    }
  } while([collisions count] > 0 && iteration++ < 16);
}

- (NSArray *) findAllCollisions:(NSArray *) entities {
  NSMutableArray *collisions = [NSMutableArray array];

  GameEntity *b = nil;
  for(GameEntity *a in entities) {
    if([a isMoving] == NO) continue;
    if((b = [self firstEntity:entities touching:a]) == nil) continue;
    [collisions addObject: [self collisionWith:a and:b]];
  }

  return [NSArray arrayWithArray: collisions];
}

- (GameEntity *) firstEntity:(NSArray *) entities touching:(GameEntity *) t {
  for(GameEntity *e in entities) {
    if(t == e) continue;
    if([t isTouching: e]) return e;
  }
  return nil;
}

- (Collision *) collisionWith:(GameEntity *) a and: (GameEntity *) b {
  Collision *collision = [[Collision alloc] init] ;

  collision.attacker = a;
  collision.victim = b;
  collision.point = [self findCollisionPoint:a : b];

  for(Force *f in [self forcesForEntity: a]) {
    collision.direction = add(collision.direction, f.direction);
    collision.massAcceleration += f.massAcceleration;
  }

  collision.direction = normalize(collision.direction);
  return collision;
}

- (vec3) findCollisionPoint:(GameEntity *) a : (GameEntity *) b {
  float closestLineDistance = a.halfwidth + b.halfwidth;
  vec3 vector = scale(a.vector, (a.halfwidth + b.halfwidth));
  vec3 output = a.lastorigin;

  vec3 tl = (vec3){b.origin.x + b.dimensions.x * .5f, b.origin.y - b.dimensions.y * .5f, 0};
  vec3 tr = (vec3){b.origin.x + b.dimensions.x * .5f, b.origin.y + b.dimensions.y * .5f, 0};
  vec3 bl = (vec3){b.origin.x - b.dimensions.x * .5f, b.origin.y - b.dimensions.y * .5f, 0};
  vec3 br = (vec3){b.origin.x - b.dimensions.x * .5f, b.origin.y + b.dimensions.y * .5f, 0};

  vec3 sides[4][2] = { {tl, tr}, {bl, br}, {bl, tl}, {br, tr} };

  for(int i=0;i<4;i++) {
    if(linesCanIntersect(a.lastorigin, add(a.lastorigin, vector), sides[i][0], sides[i][1])) {
      vec3 p = segmentIntersect(a.lastorigin, add(a.lastorigin, vector), sides[i][0], sides[i][1]);
      float distance = fabsf(p.x - a.lastorigin.x) + fabsf(p.y - a.lastorigin.y);
      if(distance < closestLineDistance) {
        closestLineDistance = distance;
        output = p;
      }
    }
  }

  return output;
}

@end


text:
import axios from 'axios';
const startUrl = 'api/students';

export function apiGetStudentsByHeader(year, educationFormId, specialityId, specializationId, groupId) {
  return axios.get(startUrl +
    `/GetStudentsByHeader?year=${year}&educationFormId=${educationFormId}&specialityId=${specialityId}&specializationId=${specializationId}&groupId=${groupId}`
  );
}

export function apiGetStudentsWithoutSelected(year, educationFormId, specialityId, specializationId, groupId, exceptedIds) {
  const exceptedParams = exceptedIds.reduce((prev, curr) => {
    return prev + '&w=' + curr;
  });
  const url = startUrl + `/GetStudentsWithoutSelected?year=${year}&educationFormId=${educationFormId}` +
    `&specialityId=${specialityId}&specializationId=${specializationId}&groupId=${groupId}` + (exceptedParams && '&w=' + exceptedParams);
  return axios.get(url);
}


text:
const selectorRegex = /^[a-z#][a-z0-9\-${}]*$/;
const selectorErrorMessage =
  'Selectors need to be in lower spine case (e.g. foo-bar).';
const selectorClassOption = [
  selectorRegex,
  {
    resolveNestedSelectors: true,
    message: selectorErrorMessage,
  },
];
const selectorIDOption = [
  selectorRegex,
  {
    message: selectorErrorMessage,
  },
];

const styleLintOptions = {
  extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
  plugins: ['stylelint-order'],
  rules: {
    // Temporarily disabling as it seems to be giving false negatives for legal scss at-rules.
    'at-rule-no-unknown': null,
    'comment-whitespace-inside': null,
    'function-url-quotes': 'never',
    'block-opening-brace-newline-after': 'always',
    'block-closing-brace-newline-before': 'always',
    'declaration-empty-line-before': null,
    'rule-empty-line-before': [
      'always',
      {
        except: ['first-nested', 'after-single-line-comment'],
        ignore: ['after-comment'],
      },
    ],
    'selector-class-pattern': selectorClassOption,
    'selector-id-pattern': selectorIDOption,
    'string-quotes': 'single',
    'declaration-no-important': true,
    'order/properties-order': [
      {
        emptyLineBefore: 'always',
        properties: [
          'display',
          'visibility',
          'float',
          'clear',
          'overflow',
          'overflow-x',
          'overflow-y',
          '-ms-overflow-x',
          '-ms-overflow-y',
          '-webkit-overflow-scrolling',
          '-ms-overflow-scrolling',
          'clip',
          'zoom',
          'max-zoom',
          'min-zoom',
          'grid',
          'grid-template',
          'grid-template-columns',
          'grid-template-rows',
          'grid-template-areas',
          'grid-gap',
          'grid-column-gap',
          'grid-row-gap',
          'place-items',
          'justify-items',
          'align-items',
          'place-content',
          'justify-content',
          'align-content',
          'grid-auto-columns',
          'grid-auto-rows',
          'grid-auto-flow',
          'grid-column',
          'grid-column-start',
          'grid-column-end',
          'grid-row',
          'grid-row-start',
          'grid-row-end',
          'grid-area',
          'place-self',
          'justify-self',
          'align-self',
          'flex-flow',
          'flex-direction',
          'flex-wrap',
          'order',
          'flex',
          'flex-grow',
          'flex-shrink',
          'flex-basis',
          'columns',
          'column-count',
          'column-fill',
          'column-gap',
          'column-rule',
          'column-rule-color',
          'column-rule-style',
          'column-rule-width',
          'column-span',
          'column-width',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: ['position', 'z-index', 'top', 'right', 'bottom', 'left'],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          '-webkit-box-sizing',
          '-moz-box-sizing',
          'box-sizing',
          'margin',
          'margin-top',
          'margin-right',
          'margin-bottom',
          'margin-left',
          'outline',
          'outline-width',
          'outline-style',
          'outline-color',
          'outline-offset',
          'border',
          'border-width',
          'border-style',
          'border-color',
          'border-top',
          'border-top-width',
          'border-top-style',
          'border-top-color',
          'border-right',
          'border-right-width',
          'border-right-style',
          'border-right-color',
          'border-bottom',
          'border-bottom-width',
          'border-bottom-style',
          'border-bottom-color',
          'border-left',
          'border-left-width',
          'border-left-style',
          'border-left-color',
          '-webkit-border-radius',
          '-moz-border-radius',
          'border-radius',
          '-webkit-border-top-left-radius',
          '-moz-border-radius-topleft',
          'border-top-left-radius',
          '-webkit-border-top-right-radius',
          '-moz-border-radius-topright',
          'border-top-right-radius',
          '-webkit-border-bottom-right-radius',
          '-moz-border-radius-bottomright',
          'border-bottom-right-radius',
          '-webkit-border-bottom-left-radius',
          '-moz-border-radius-bottomleft',
          'border-bottom-left-radius',
          '-webkit-border-image',
          '-moz-border-image',
          '-o-border-image',
          'border-image',
          '-webkit-border-image-source',
          '-moz-border-image-source',
          '-o-border-image-source',
          'border-image-source',
          '-webkit-border-image-slice',
          '-moz-border-image-slice',
          '-o-border-image-slice',
          'border-image-slice',
          '-webkit-border-image-width',
          '-moz-border-image-width',
          '-o-border-image-width',
          'border-image-width',
          '-webkit-border-image-outset',
          '-moz-border-image-outset',
          '-o-border-image-outset',
          'border-image-outset',
          '-webkit-border-image-repeat',
          '-moz-border-image-repeat',
          '-o-border-image-repeat',
          'border-image-repeat',
          'border-top-image',
          'border-top-left-image',
          'border-top-right-image',
          'border-right-image',
          'border-bottom-image',
          'border-bottom-left-image',
          'border-bottom-right-image',
          'border-left-image',
          'border-corner-image',
          'padding',
          'padding-top',
          'padding-right',
          'padding-bottom',
          'padding-left',
          'width',
          'min-width',
          'max-width',
          'height',
          'min-height',
          'max-height',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          'break-after',
          'break-before',
          'break-inside',
          'page-break-after',
          'page-break-before',
          'page-break-inside',
          'orphans',
          'widows',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          'table-layout',
          'empty-cells',
          'caption-side',
          'border-spacing',
          'border-collapse',
          'list-style',
          'list-style-position',
          'list-style-type',
          'list-style-image',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          'fill',
          'stroke',
          'stroke-opacity',
          'stroke-width',
          'pointer-events',
          'opacity',
          'color',
          'background',
          'filter',
          'filter:progid:DXImageTransform.Microsoft.Alpha(Opacity)',
          "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha'",
          '-ms-interpolation-mode',
          'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader',
          'background-color',
          'background-image',
          'background-repeat',
          'background-attachment',
          'background-position',
          'background-position-x',
          '-ms-background-position-x',
          'background-position-y',
          '-ms-background-position-y',
          '-webkit-background-clip',
          '-moz-background-clip',
          'background-clip',
          'background-origin',
          '-webkit-background-size',
          '-moz-background-size',
          '-o-background-size',
          'background-size',
          'box-decoration-break',
          '-webkit-box-shadow',
          '-moz-box-shadow',
          'box-shadow',
          'filter:progid:DXImageTransform.Microsoft.gradient',
          "-ms-filter:'progid:DXImageTransform.Microsoft.gradient'",
          'text-shadow',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          'font',
          'font-family',
          'font-feature-settings',
          'font-size',
          'line-height',
          'font-weight',
          'font-style',
          'font-variant',
          'font-size-adjust',
          'font-stretch',
          'font-effect',
          'font-emphasize',
          'font-emphasize-position',
          'font-emphasize-style',
          'font-smooth',
        ],
      },
      {
        emptyLineBefore: 'always',
        properties: [
          'content',
          'quotes',
          'counter-reset',
          'counter-increment',
          'resize',
          'cursor',
          '-webkit-user-select',
          '-moz-user-select',
          '-ms-user-select',
          'user-select',
          'nav-index',
          'nav-up',
          'nav-right',
          'nav-down',
          'nav-left',
          '-webkit-transition',
          '-moz-transition',
          '-ms-transition',
          '-o-transition',
          'transition',
          '-webkit-transition-delay',
          '-moz-transition-delay',
          '-ms-transition-delay',
          '-o-transition-delay',
          'transition-delay',
          '-webkit-transition-timing-function',
          '-moz-transition-timing-function',
          '-ms-transition-timing-function',
          '-o-transition-timing-function',
          'transition-timing-function',
          '-webkit-transition-duration',
          '-moz-transition-duration',
          '-ms-transition-duration',
          '-o-transition-duration',
          'transition-duration',
          '-webkit-transition-property',
          '-moz-transition-property',
          '-ms-transition-property',
          '-o-transition-property',
          'transition-property',
          '-webkit-transform',
          '-moz-transform',
          '-ms-transform',
          '-o-transform',
          'transform',
          '-webkit-transform-origin',
          '-moz-transform-origin',
          '-ms-transform-origin',
          '-o-transform-origin',
          'transform-origin',
          '-webkit-animation',
          '-moz-animation',
          '-ms-animation',
          '-o-animation',
          'animation',
          '-webkit-animation-name',
          '-moz-animation-name',
          '-ms-animation-name',
          '-o-animation-name',
          'animation-name',
          '-webkit-animation-duration',
          '-moz-animation-duration',
          '-ms-animation-duration',
          '-o-animation-duration',
          'animation-duration',
          '-webkit-animation-play-state',
          '-moz-animation-play-state',
          '-ms-animation-play-state',
          '-o-animation-play-state',
          'animation-play-state',
          '-webkit-animation-timing-function',
          '-moz-animation-timing-function',
          '-ms-animation-timing-function',
          '-o-animation-timing-function',
          'animation-timing-function',
          '-webkit-animation-delay',
          '-moz-animation-delay',
          '-ms-animation-delay',
          '-o-animation-delay',
          'animation-delay',
          '-webkit-animation-iteration-count',
          '-moz-animation-iteration-count',
          '-ms-animation-iteration-count',
          '-o-animation-iteration-count',
          'animation-iteration-count',
          '-webkit-animation-direction',
          '-moz-animation-direction',
          '-ms-animation-direction',
          '-o-animation-direction',
          'animation-direction',
          'animation-fill-mode',
          'direction',
          'orientation',
          'text-orientation',
          'text-rendering',
          'text-align',
          '-webkit-text-align-last',
          '-moz-text-align-last',
          '-ms-text-align-last',
          'text-align-last',
          'vertical-align',
          'white-space',
          'text-decoration',
          'text-emphasis',
          'text-emphasis-color',
          'text-emphasis-style',
          'text-emphasis-position',
          'text-indent',
          '-ms-text-justify',
          'text-justify',
          'letter-spacing',
          'word-spacing',
          '-ms-writing-mode',
          'text-outline',
          'text-transform',
          'text-wrap',
          'text-overflow',
          '-ms-text-overflow',
          'text-overflow-ellipsis',
          'text-overflow-mode',
          '-ms-word-wrap',
          'word-wrap',
          'word-break',
          '-ms-word-break',
          '-moz-tab-size',
          '-o-tab-size',
          'tab-size',
          '-webkit-hyphens',
          '-moz-hyphens',
          'hyphens',
        ],
      },
    ],
  },
};

module.exports = styleLintOptions;


text:
import Colors from 'material-ui/lib/styles/colors'
import ColorManipulator from 'material-ui/lib/utils/color-manipulator'
import Spacing from 'material-ui/lib/styles/spacing'
import zIndex from 'material-ui/lib/styles/zIndex'

export default {
  spacing: Spacing,
  zIndex: zIndex,
  fontFamily: 'Roboto, sans-serif',
  palette: {
    //primary1Color: Colors.cyan500,
    primary1Color: '#008fd5',
    primary2Color: Colors.cyan700,
    primary3Color: Colors.lightBlack,
    // accent1Color: Colors.pinkA200,
    // accent1Color: '#008fd5',
    accent1Color: '#f3742c',
    accent2Color: Colors.grey100,
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
    disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
    pickerHeaderColor: Colors.cyan500,
  }
}


text:
'use strict';

var expect = require('expect.js'),
    concat = require('concat-stream'),
    fs = require('fs'),
    folderify = require('../lib/folderify');

var browserify = require('browserify');

var expectedBundle = fs.readFileSync(__dirname +'/fixtures/expected-bundle.js','utf8');

describe('folderify', function() {
    it('is defined', function() {
        expect(folderify).to.be.an('function');
    });

    it('return a through stream', function() {
        expect(folderify('./test/files').constructor.name).to.be.equal('Stream');
    });

    function checkTransform(source, expected, done) {
        var stream = folderify('./test/files');
        var result = concat(function(data) {
            //console.log('----------------------------');
            //console.log(data);
            //console.log('----------------------------');
            //console.log(expected);
            //console.log('----------------------------');
            expect(data).to.be.equal(expected);
            done();
        });
        stream.pipe(result);

        stream.write(source);
        stream.end();
    }

    this.timeout(3000);

    it('un-require include-folder', function(done) {
        var source = 'var iF = require("include-folder");\n' +
            'console.log("anything");\n' +
            'var another = require("include-folder");\n' +
            'console.log("anything");\n' +
            'var ciao=iF;\n' +
            'var b;\n' +
            'console.log(b = another);\n' +
            'console.log(b = require("include-folder"));\n';
        var expected = 'var iF = undefined;\n' +
            'console.log("anything");\n' +
            'var another = undefined;\n' +
            'console.log("anything");\n' +
            'var ciao=iF;\n' +
            'var b;\n' +
            'console.log(b = another);\n' +
            'console.log(b = undefined);\n';
        checkTransform(source, expected, done);
    });

    it('skip hidden files', function(done) {
        var source =
            'var iF = require("include-folder");\n' +
            'var files = iF("./test/files")\n';

        var expected = 'var iF = undefined;\n' +
            'var files = (function(){var self={},fs = require("fs");\n' +
            'self["file3OtherFile"] = "this is file3OtherContent content";\n' +
            'self["file1"] = "this is file1 content";\n' +
            'self["file1_1"] = "this is file1_1 content";\n' +
            'return self})()\n';

        checkTransform(source, expected, done);
    });

    it('include hidden files', function(done) {
        var source =
            'var iF = require("include-folder");\n' +
            'var files = iF("./test/files",/(.*)/)\n';

        var expected = 'var iF = undefined;\n' +
            'var files = (function(){var self={},fs = require("fs");\n' +
            'self["DS_STORE"] = "ciao";\n' +
            'self["file3OtherFile"] = "this is file3OtherContent content";\n' +
            'self["file1"] = "this is file1 content";\n' +
            'self["file1_1"] = "this is file1_1 content";\n' +

            'return self})()\n';

        checkTransform(source, expected, done);
    });

    it('preserve filenames', function(done) {
        var source =
            'var iF = require("include-folder");\n' +
            'var files = iF("./test/files",null,{preserveFilenames:true})\n';

        var expected = 'var iF = undefined;\n' +
            'var files = (function(){var self={},fs = require("fs");\n' +
            'self["file-3-other&file.txt"] = "this is file3OtherContent content";\n' +
            'self["file1.check"] = "this is file1 content";\n' +
            'self["file1.txt"] = "this is file1_1 content";\n' +

            'return self})()\n';

        checkTransform(source, expected, done);
    });

    it('doesn\'t require brfs', function(done){

        var b = browserify(__dirname +'/fixtures/source.js');
        b.transform(folderify);

        b
          .bundle()
          .on('error', done)
          .pipe(concat(function(data){
              expect(data.toString('utf8')).to.be.equal(expectedBundle);
              done();
          }));
    });

    it('is compatible with brfs', function(done){

        var b = browserify(__dirname +'/fixtures/source.js');
        b.transform(folderify);
        b.transform('brfs');

        b
          .bundle()
          .on('error', done)
          .pipe(concat(function(data){
              expect(data.toString('utf8')).to.be.equal(expectedBundle);
              done();
          }));
    });

    it('support transforms in both order', function(done){

        var b = browserify(__dirname +'/fixtures/source.js');
        b.transform('brfs');
        b.transform(folderify);

        b
          .bundle()
          .on('error', done)
          .pipe(concat(function(data){
              //console.log(data.toString('utf8'));
              //console.log(expectedBundle);
              expect(data.toString('utf8')).to.be.equal(expectedBundle);
              done();
          }));
    });
});


text:
import { DefaultGridCell, DefaultGridCellParams } from '../default/DefaultGridCell';
import { Style, BaseStyle } from './Style';
import { renderer, visualize } from '../../ui/Extensibility';
import { Point, PointLike } from '../../geom/Point';

/**
 * Defines the parameters that can/should be passed to a new StyledGridCell instance.
 */
export interface StyledGridCellParams extends DefaultGridCellParams
{
    placeholder?:string;
    style?:Style;
}

@renderer(draw)
export class StyledGridCell extends DefaultGridCell
{
    @visualize()
    public style:Style = BaseStyle;

    @visualize()
    public placeholder:string = '';

    /**
     * Initializes a new instance of StyledGridCell.
     *
     * @param params
     */
    constructor(params:StyledGridCellParams)
    {
        super(params);

        this.placeholder = params.placeholder || '';
        this.style = params.style || BaseStyle;
    }
}

function draw(gfx:CanvasRenderingContext2D, visual:any):void
{
    let style = visual.style as Style;

    gfx.lineWidth = 1;
    let av = gfx.lineWidth % 2 == 0 ? 0 : 0.5;

    gfx.fillStyle = style.fillColor;
    gfx.fillRect(-av, -av, visual.width, visual.height);

    gfx.strokeStyle = style.borderColor;
    gfx.strokeRect(-av, -av, visual.width, visual.height);

    let textPt = new Point(3, visual.height / 2) as PointLike;
    if (style.text.alignment === 'center')
    {
        textPt.x = visual.width / 2;
    }
    if (style.text.alignment === 'right')
    {
        textPt.x = visual.width - 3;
    }

    gfx.font = `${style.text} ${style.text.variant} ${style.text.weight} ${style.text.size}px ${style.text.font}`;
    gfx.textAlign = style.text.alignment;
    gfx.textBaseline = 'middle';
    gfx.fillStyle = style.text.color;
    gfx.fillText(style.formatter(visual.value, visual) || visual.placeholder, textPt.x, textPt.y);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.jeewx.api.core.req.model.dataCube</title>
<meta name="date" content="2019-06-04">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

org.jeewx.api.core.req.model.dataCube

类

WxDataCubeStreamArticleSummaryParam

WxDataCubeStreamArticleTotalParam

WxDataCubeStreamMsgDistMonthParam

WxDataCubeStreamMsgDistParam

WxDataCubeStreamMsgDistWeekParam

WxDataCubeStreamMsgHourParam

WxDataCubeStreamMsgMonthParam

WxDataCubeStreamMsgParam

WxDataCubeStreamMsgWeekParam

WxDataCubeStreamUserCumulateParam

WxDataCubeStreamUserReadHourParam

WxDataCubeStreamUserReadParam

WxDataCubeStreamUserShareHourParam

WxDataCubeStreamUserShareParam

WxDataCubeStreamUserSummaryParam


text:
local ej = require "ejoy2d"
local fw = require "ejoy2d.framework"
local pack = require "ejoy2d.simplepackage"

pack.load {
	pattern = fw.WorkDir..[[examples/test_jpg/asset/?]],
	"test_jpg",
}

local obj = ej.sprite("test_jpg","girl")

local game = {}
local screencoord = { x = 0, y = 0, scale = 0.8 }

function game.update()

end

function game.drawframe()
	ej.clear(0xff808080)	-- clear (0.5,0.5,0.5,1) gray
	obj:draw(screencoord)
end

function game.touch(what, x, y)
end

function game.message(...)
end

function game.handle_error(...)
end

function game.on_resume()
end

function game.on_pause()
end

ej.start(game)


text:
package org.carrot2.text.preprocessing.filter;

import org.carrot2.core.attribute.Processing;
import org.carrot2.text.preprocessing.PreprocessingContext;
import org.carrot2.util.attribute.*;
import static org.carrot2.text.analysis.TokenTypeUtils.*;

/**
 * Accepts words that are not stop words and phrases that do not start nor end in a stop
 * word.
 */
@Bindable(prefix = "StopWordLabelFilter")
public class StopWordLabelFilter extends SingleLabelFilterBase
{
    /**
     * Remove leading and trailing stop words. Removes labels that consist of, start or
     * end in stop words.
     *
     * @level Basic
     * @group Label filtering
     */
    @Input
    @Processing
    @Attribute
    public boolean enabled = true;

    @Override
    public boolean acceptPhrase(PreprocessingContext context, int phraseIndex)
    {
        final int [] wordIndices = context.allPhrases.wordIndices[phraseIndex];
        final short [] termTypes = context.allWords.type;

        return !isCommon(termTypes[wordIndices[0]])
            && !isCommon(termTypes[wordIndices[wordIndices.length - 1]]);
    }

    @Override
    public boolean acceptWord(PreprocessingContext context, int wordIndex)
    {
        return !isCommon(context.allWords.type[wordIndex]);
    }

    public boolean isEnabled()
    {
        return enabled;
    }
}


text:
namespace {

typedef testing::Test CannedBrowsingDataIndexedDBHelperTest;

TEST_F(CannedBrowsingDataIndexedDBHelperTest, Empty) {
  const GURL origin("http://host1:1/");
  const string16 description(ASCIIToUTF16("description"));

  scoped_refptr<CannedBrowsingDataIndexedDBHelper> helper(
      new CannedBrowsingDataIndexedDBHelper());

  ASSERT_TRUE(helper->empty());
  helper->AddIndexedDB(origin, description);
  ASSERT_FALSE(helper->empty());
  helper->Reset();
  ASSERT_TRUE(helper->empty());
}

TEST_F(CannedBrowsingDataIndexedDBHelperTest, IgnoreExtensionsAndDevTools) {
  const GURL origin1("chrome-extension://abcdefghijklmnopqrstuvwxyz/");
  const GURL origin2("chrome-devtools://abcdefghijklmnopqrstuvwxyz/");
  const string16 description(ASCIIToUTF16("description"));

  scoped_refptr<CannedBrowsingDataIndexedDBHelper> helper(
      new CannedBrowsingDataIndexedDBHelper());

  ASSERT_TRUE(helper->empty());
  helper->AddIndexedDB(origin1, description);
  ASSERT_TRUE(helper->empty());
  helper->AddIndexedDB(origin2, description);
  ASSERT_TRUE(helper->empty());
}

} // namespace


text:
import { TestBed, inject } from '@angular/core/testing';

import { InMemoryDataService } from './in-memory-data.service';

describe('InMemoryDataService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [InMemoryDataService]
    });
  });

  it('should be created', inject([InMemoryDataService], (service: InMemoryDataService) => {
    expect(service).toBeTruthy();
  }));
});


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE398_Poor_Code_Quality__empty_block_15.c
Label Definition File: CWE398_Poor_Code_Quality.label.xml
Template File: point-flaw-15.tmpl.c
*/
/*
 * @description
 * CWE: 398 Poor Code Quality
 * Sinks: empty_block
 *    GoodSink: Code block contains code
 *    BadSink : An empty code block has no effect
 * Flow Variant: 15 Control flow: switch(6)
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE398_Poor_Code_Quality__empty_block_15_bad()
{
    switch(6)
    {
    case 6:
        /* FLAW: An empty block has no effect */
    {
    }
    printLine("Hello from bad()");
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() changes the switch to switch(5) */
static void good1()
{
    switch(5)
    {
    case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
        /* FIX: Do not include an empty block */
    {
        printLine("Inside the block");
    }
    printLine("Hello from good()");
    break;
    }
}

/* good2() reverses the blocks in the switch */
static void good2()
{
    switch(6)
    {
    case 6:
        /* FIX: Do not include an empty block */
    {
        printLine("Inside the block");
    }
    printLine("Hello from good()");
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

void CWE398_Poor_Code_Quality__empty_block_15_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE398_Poor_Code_Quality__empty_block_15_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE398_Poor_Code_Quality__empty_block_15_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.relational;

import com.google.common.collect.ImmutableList;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.ResolvedFunction;
import io.prestosql.sql.tree.QualifiedName;
import org.testng.annotations.Test;

import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.spi.function.OperatorType.LESS_THAN;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.sql.analyzer.TypeSignatureProvider.fromTypes;
import static io.prestosql.sql.relational.Expressions.constant;
import static io.prestosql.sql.relational.Expressions.field;
import static java.util.Collections.singletonList;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class TestDeterminismEvaluator
{
    @Test
    public void testDeterminismEvaluator()
    {
        Metadata metadata = createTestMetadataManager();
        DeterminismEvaluator determinismEvaluator = new DeterminismEvaluator(metadata);

        CallExpression random = new CallExpression(
                metadata.resolveFunction(QualifiedName.of("random"), fromTypes(BIGINT)),
                BIGINT,
                singletonList(constant(10L, BIGINT)));
        assertFalse(determinismEvaluator.isDeterministic(random));

        InputReferenceExpression col0 = field(0, BIGINT);
        ResolvedFunction lessThan = metadata.resolveOperator(LESS_THAN, ImmutableList.of(BIGINT, BIGINT));

        CallExpression lessThanExpression = new CallExpression(lessThan, BOOLEAN, ImmutableList.of(col0, constant(10L, BIGINT)));
        assertTrue(determinismEvaluator.isDeterministic(lessThanExpression));

        CallExpression lessThanRandomExpression = new CallExpression(lessThan, BOOLEAN, ImmutableList.of(col0, random));
        assertFalse(determinismEvaluator.isDeterministic(lessThanRandomExpression));
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84_bad.cpp
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-84_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: calloc Allocate data using calloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84.h"

namespace CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84
{
CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84_bad::CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84_bad(struct _twoIntsStruct * dataCopy)
{
    data = dataCopy;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (struct _twoIntsStruct *)calloc(100, sizeof(struct _twoIntsStruct));
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine((twoIntsStruct *)&data[0]);
}

CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84_bad::~CWE401_Memory_Leak__struct_twoIntsStruct_calloc_84_bad()
{
    /* POTENTIAL FLAW: No deallocation */
    ; /* empty statement needed for some flow variants */
}
}
#endif /* OMITBAD */


text:
package org.apache.hadoop.hdfs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager;
import org.apache.hadoop.hdfs.security.token.block.SecurityTestUtil;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;

import com.google.common.base.Preconditions;

public class TestDFSStripedOutputStreamWithFailure {
  public static final Log LOG = LogFactory.getLog(
      TestDFSStripedOutputStreamWithFailure.class);
  static {
    GenericTestUtils.setLogLevel(DFSOutputStream.LOG, Level.ALL);
    GenericTestUtils.setLogLevel(DataStreamer.LOG, Level.ALL);
  }

  private static final int NUM_DATA_BLOCKS = StripedFileTestUtil.NUM_DATA_BLOCKS;
  private static final int NUM_PARITY_BLOCKS = StripedFileTestUtil.NUM_PARITY_BLOCKS;
  private static final int CELL_SIZE = StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
  private static final int STRIPES_PER_BLOCK = 4;
  private static final int BLOCK_SIZE = CELL_SIZE * STRIPES_PER_BLOCK;
  private static final int BLOCK_GROUP_SIZE = BLOCK_SIZE * NUM_DATA_BLOCKS;

  private static final int FLUSH_POS
      = 9*DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT + 1;

  static {
    System.out.println("NUM_DATA_BLOCKS  = " + NUM_DATA_BLOCKS);
    System.out.println("NUM_PARITY_BLOCKS= " + NUM_PARITY_BLOCKS);
    System.out.println("CELL_SIZE        = " + CELL_SIZE
        + " (=" + StringUtils.TraditionalBinaryPrefix.long2String(CELL_SIZE, "B", 2) + ")");
    System.out.println("BLOCK_SIZE       = " + BLOCK_SIZE
        + " (=" + StringUtils.TraditionalBinaryPrefix.long2String(BLOCK_SIZE, "B", 2) + ")");
    System.out.println("BLOCK_GROUP_SIZE = " + BLOCK_GROUP_SIZE
        + " (=" + StringUtils.TraditionalBinaryPrefix.long2String(BLOCK_GROUP_SIZE, "B", 2) + ")");
  }

  static List<Integer> newLengths() {
    final List<Integer> lengths = new ArrayList<>();
    lengths.add(FLUSH_POS + 2);
    for(int b = 0; b <= 2; b++) {
      for(int c = 0; c < STRIPES_PER_BLOCK*NUM_DATA_BLOCKS; c++) {
        for(int delta = -1; delta <= 1; delta++) {
          final int length = b*BLOCK_GROUP_SIZE + c*CELL_SIZE + delta;
          System.out.println(lengths.size() + ": length=" + length
              + ", (b, c, d) = (" + b + ", " + c + ", " + delta + ")");
          lengths.add(length);
        }
      }
    }
    return lengths;
  }

  private static final int[][] dnIndexSuite = {
      {0, 1},
      {0, 5},
      {0, 6},
      {0, 8},
      {1, 5},
      {1, 6},
      {6, 8},
      {0, 1, 2},
      {3, 4, 5},
      {0, 1, 6},
      {0, 5, 6},
      {0, 5, 8},
      {0, 6, 7},
      {5, 6, 7},
      {6, 7, 8},
  };

  private int[] getKillPositions(int fileLen, int num) {
    int[] positions = new int[num];
    for (int i = 0; i < num; i++) {
      positions[i] = fileLen * (i + 1) / (num + 1);
    }
    return positions;
  }

  private static final List<Integer> LENGTHS = newLengths();

  static int getLength(int i) {
    return LENGTHS.get(i);
  }

  private MiniDFSCluster cluster;
  private DistributedFileSystem dfs;
  private final Path dir = new Path("/"
      + TestDFSStripedOutputStreamWithFailure.class.getSimpleName());

  private void setup(Configuration conf) throws IOException {
    final int numDNs = NUM_DATA_BLOCKS + NUM_PARITY_BLOCKS;
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDNs).build();
    cluster.waitActive();
    dfs = cluster.getFileSystem();
    dfs.mkdirs(dir);
    dfs.setErasureCodingPolicy(dir, null);
  }

  private void tearDown() {
    if (cluster != null) {
      cluster.shutdown();
    }
  }

  private HdfsConfiguration newHdfsConfiguration() {
    final HdfsConfiguration conf = new HdfsConfiguration();
    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
    conf.setLong(HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, 6000L);
    conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY, 0);
    return conf;
  }

  @Test(timeout=240000)
  public void testDatanodeFailure56() throws Exception {
    runTest(getLength(56));
  }

  @Test(timeout=240000)
  public void testMultipleDatanodeFailure56() throws Exception {
    runTestWithMultipleFailure(getLength(56));
  }

  @Test(timeout=240000)
  public void testBlockTokenExpired() throws Exception {
    final int length = NUM_DATA_BLOCKS * (BLOCK_SIZE - CELL_SIZE);
    final HdfsConfiguration conf = newHdfsConfiguration();

    conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true);
    conf.setInt(CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, 0);
    // Set short retry timeouts so this test runs faster
    conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
    for (int dn = 0; dn < 9; dn += 2) {
      try {
        setup(conf);
        runTest(length, new int[]{length/2}, new int[]{dn}, true);
      } catch (Exception e) {
        LOG.error("failed, dn=" + dn + ", length=" + length);
        throw e;
      } finally {
        tearDown();
      }
    }
  }

  @Test(timeout = 90000)
  public void testAddBlockWhenNoSufficientDataBlockNumOfNodes()
      throws IOException {
    HdfsConfiguration conf = new HdfsConfiguration();
    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
    try {
      setup(conf);
      ArrayList<DataNode> dataNodes = cluster.getDataNodes();
      // shutdown few datanodes to avoid getting sufficient data blocks number
      // of datanodes
      int killDns = dataNodes.size() / 2;
      int numDatanodes = dataNodes.size() - killDns;
      for (int i = 0; i < killDns; i++) {
        cluster.stopDataNode(i);
      }
      cluster.restartNameNodes();
      cluster.triggerHeartbeats();
      DatanodeInfo[] info = dfs.getClient().datanodeReport(
          DatanodeReportType.LIVE);
      assertEquals("Mismatches number of live Dns ", numDatanodes, info.length);
      final Path dirFile = new Path(dir, "ecfile");
      FSDataOutputStream out = null;
      try {
        out = dfs.create(dirFile, true);
        out.write("something".getBytes());
        out.flush();
        out.close();
        Assert.fail("Failed to validate available dns against blkGroupSize");
      } catch (IOException ioe) {
        // expected
        GenericTestUtils.assertExceptionContains("Failed to get 6 nodes from" +
            " namenode: blockGroupSize= 9, blocks.length= 5", ioe);
      }
    } finally {
      tearDown();
    }
  }

  @Test(timeout = 90000)
  public void testAddBlockWhenNoSufficientParityNumOfNodes() throws IOException {
    HdfsConfiguration conf = new HdfsConfiguration();
    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
    try {
      setup(conf);
      ArrayList<DataNode> dataNodes = cluster.getDataNodes();
      // shutdown few data nodes to avoid writing parity blocks
      int killDns = (NUM_PARITY_BLOCKS - 1);
      int numDatanodes = dataNodes.size() - killDns;
      for (int i = 0; i < killDns; i++) {
        cluster.stopDataNode(i);
      }
      cluster.restartNameNodes();
      cluster.triggerHeartbeats();
      DatanodeInfo[] info = dfs.getClient().datanodeReport(
          DatanodeReportType.LIVE);
      assertEquals("Mismatches number of live Dns ", numDatanodes, info.length);
      Path srcPath = new Path(dir, "testAddBlockWhenNoSufficientParityNodes");
      int fileLength = StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE - 1000;
      final byte[] expected = StripedFileTestUtil.generateBytes(fileLength);
      DFSTestUtil.writeFile(dfs, srcPath, new String(expected));
      LOG.info("writing finished. Seek and read the file to verify.");
      StripedFileTestUtil.verifySeek(dfs, srcPath, fileLength);
    } finally {
      tearDown();
    }
  }

  void runTest(final int length) {
    final HdfsConfiguration conf = newHdfsConfiguration();
    for (int dn = 0; dn < 9; dn++) {
      try {
        setup(conf);
        runTest(length, new int[]{length/2}, new int[]{dn}, false);
      } catch (Throwable e) {
        final String err = "failed, dn=" + dn + ", length=" + length
            + StringUtils.stringifyException(e);
        LOG.error(err);
        Assert.fail(err);
      } finally {
        tearDown();
      }
    }
  }

  void runTestWithMultipleFailure(final int length) throws Exception {
    final HdfsConfiguration conf = newHdfsConfiguration();
    for(int i=0;i<dnIndexSuite.length;i++){
      int[] dnIndex = dnIndexSuite[i];
      int[] killPos = getKillPositions(length, dnIndex.length);
      try {
        setup(conf);
        runTest(length, killPos, dnIndex, false);
      } catch (Throwable e) {
        final String err = "failed, killPos=" + Arrays.toString(killPos)
            + ", dnIndex=" + Arrays.toString(dnIndex) + ", length=" + length;
        LOG.error(err);
        throw e;
      } finally {
        tearDown();
      }
    }
  }

  /**
   * runTest implementation
   * @param length file length
   * @param killPos killing positions in ascending order
   * @param dnIndex DN index to kill when meets killing positions
   * @param tokenExpire wait token to expire when kill a DN
   * @throws Exception
   */
  private void runTest(final int length, final int[] killPos,
      final int[] dnIndex, final boolean tokenExpire) throws Exception {
    if (killPos[0] <= FLUSH_POS) {
      LOG.warn("killPos=" + Arrays.toString(killPos) + " <= FLUSH_POS=" + FLUSH_POS
          + ", length=" + length + ", dnIndex=" + Arrays.toString(dnIndex));
      return; //skip test
    }
    Preconditions.checkArgument(length > killPos[0], "length=%s <= killPos=%s",
        length, killPos);
    Preconditions.checkArgument(killPos.length == dnIndex.length);

    final Path p = new Path(dir, "dn" + Arrays.toString(dnIndex)
        + "len" + length + "kill" +  Arrays.toString(killPos));
    final String fullPath = p.toString();
    LOG.info("fullPath=" + fullPath);

    if (tokenExpire) {
      final NameNode nn = cluster.getNameNode();
      final BlockManager bm = nn.getNamesystem().getBlockManager();
      final BlockTokenSecretManager sm = bm.getBlockTokenSecretManager();

      // set a short token lifetime (1 second)
      SecurityTestUtil.setBlockTokenLifetime(sm, 1000L);
    }

    final AtomicInteger pos = new AtomicInteger();
    final FSDataOutputStream out = dfs.create(p);
    final DFSStripedOutputStream stripedOut
        = (DFSStripedOutputStream)out.getWrappedStream();

    long firstGS = -1;  // first GS of this block group which never proceeds blockRecovery
    long oldGS = -1; // the old GS before bumping
    int numKilled=0;
    for(; pos.get() < length; ) {
      final int i = pos.getAndIncrement();
      if (numKilled < killPos.length &&  i == killPos[numKilled]) {
        assertTrue(firstGS != -1);
        final long gs = getGenerationStamp(stripedOut);
        if (numKilled == 0) {
          assertEquals(firstGS, gs);
        } else {
          //TODO: implement hflush/hsync and verify gs strict greater than oldGS
          assertTrue(gs >= oldGS);
        }
        oldGS = gs;

        if (tokenExpire) {
          DFSTestUtil.flushInternal(stripedOut);
          waitTokenExpires(out);
        }

        killDatanode(cluster, stripedOut, dnIndex[numKilled], pos);
        numKilled++;
      }

      write(out, i);

      if (i % BLOCK_GROUP_SIZE == FLUSH_POS) {
        firstGS = getGenerationStamp(stripedOut);
        oldGS = firstGS;
      }
    }
    out.close();
    assertEquals(dnIndex.length, numKilled);

    short expectedReported = StripedFileTestUtil.getRealTotalBlockNum(length);
    for(int idx :dnIndex) {
      if (length > idx * CELL_SIZE || idx >= NUM_DATA_BLOCKS) {
        expectedReported--;
      }
    }
    DFSTestUtil.waitReplication(dfs, p, expectedReported);

    cluster.triggerBlockReports();
    StripedFileTestUtil.checkData(dfs, p, length, dnIndex, oldGS);
  }

  static void write(FSDataOutputStream out, int i) throws IOException {
    try {
      out.write(StripedFileTestUtil.getByte(i));
    } catch(IOException ioe) {
      throw new IOException("Failed at i=" + i, ioe);
    }
  }

  static long getGenerationStamp(DFSStripedOutputStream out)
      throws IOException {
    DFSTestUtil.flushBuffer(out);
    final long gs = DFSTestUtil.flushInternal(out).getGenerationStamp();
    LOG.info("getGenerationStamp returns " + gs);
    return gs;
  }

  static DatanodeInfo getDatanodes(StripedDataStreamer streamer) {
    for(;;) {
      DatanodeInfo[] datanodes = streamer.getNodes();
      if (datanodes == null) {
        // try peeking following block.
        final LocatedBlock lb = streamer.peekFollowingBlock();
        if (lb != null) {
          datanodes = lb.getLocations();
        }
      }

      if (datanodes != null) {
        Assert.assertEquals(1, datanodes.length);
        Assert.assertNotNull(datanodes[0]);
        return datanodes[0];
      }

      try {
        Thread.sleep(100);
      } catch (InterruptedException ie) {
        Assert.fail(StringUtils.stringifyException(ie));
        return null;
      }
    }
  }

  static void killDatanode(MiniDFSCluster cluster, DFSStripedOutputStream out,
      final int dnIndex, final AtomicInteger pos) {
    final StripedDataStreamer s = out.getStripedDataStreamer(dnIndex);
    final DatanodeInfo datanode = getDatanodes(s);
    LOG.info("killDatanode " + dnIndex + ": " + datanode + ", pos=" + pos);
    cluster.stopDataNode(datanode.getXferAddr());
  }

  private void waitTokenExpires(FSDataOutputStream out) throws IOException {
    Token<BlockTokenIdentifier> token = DFSTestUtil.getBlockToken(out);
    while (!SecurityTestUtil.isBlockTokenExpired(token)) {
      try {
        Thread.sleep(10);
      } catch (InterruptedException ignored) {
      }
    }
  }

  public static abstract class TestBase {
    static final long TIMEOUT = 240000;

    int getBase() {
      final String name = getClass().getSimpleName();
      int i = name.length() - 1;
      for(; i >= 0 && Character.isDigit(name.charAt(i)); i--);
      return Integer.parseInt(name.substring(i + 1));
    }

    private final TestDFSStripedOutputStreamWithFailure test
        = new TestDFSStripedOutputStreamWithFailure();
    private void run(int offset) {
      final int i = offset + getBase();
      final int length = getLength(i);
      System.out.println("Run test " + i + ", length=" + length);
      test.runTest(length);
    }

    @Test(timeout=TIMEOUT) public void test0() {run(0);}
    @Test(timeout=TIMEOUT) public void test1() {run(1);}
    @Test(timeout=TIMEOUT) public void test2() {run(2);}
    @Test(timeout=TIMEOUT) public void test3() {run(3);}
    @Test(timeout=TIMEOUT) public void test4() {run(4);}
    @Test(timeout=TIMEOUT) public void test5() {run(5);}
    @Test(timeout=TIMEOUT) public void test6() {run(6);}
    @Test(timeout=TIMEOUT) public void test7() {run(7);}
    @Test(timeout=TIMEOUT) public void test8() {run(8);}
    @Test(timeout=TIMEOUT) public void test9() {run(9);}
  }
}