text:
from math import sqrt
from projecteuler.Divisors import prime_factor_array
from functools import reduce
from operator import mul

# is the number's digits the same forward and backward?
def is_palindrome(n):
    digit_array = [int(c) for c in str(n)]
    length = len(digit_array)
    for i in range(0, length // 2):
        if digit_array[i] != digit_array[length - i - 1]:
            return False
    return True

# does the number contain every digit from 1-d
# (0-d if include_zero is true) exactly once?
def is_pandigital(n, d, include_zero):
    return sorted(str(n)) == sorted(str(i) for i in range((not include_zero), d + 1))

# is x a permutation of y?
# works for both numbers and strings
def is_permutation(x, y):
    return sorted(str(x)) == sorted(str(y))

# proof for is_pentagonal:
# formula for nth pentagonal number, x, is x = n(3n-1)/2
# rearranging the formula: 3n^2 - n - 2x = 0
# using quadratic formula: n = (1 +/- sqrt(1 + 24x)) / 6
# therefore if (1 + sqrt(1 + 24x)) / 6 is an integer, the number is pentagonal
# so (1 + sqrt(1 + 24x)) % 6 must equal 0
# and sqrt(1 + 24x) % 6 must equal 5

# is the given number a pentagonal number?
def is_pentagonal(n):
    return sqrt(1 + 24 * n) % 6 == 5

# is the given number a triangular number?
# same logic applies as for is_pentagonal
def is_triangular(n):
    return sqrt(1 + 8 * n) % 1 == 0

# is the given number an s-gonal number?
# logic abstracted from is_pentagonal and
# from wikipedia's polygonal number formula
def is_polygonal(x, s):
    a = s / 2 - 1
    b = -(s / 2 - 2)
    c = -x
    return ((-b + sqrt(b**2 - 4 * a * c)) / (2 * a)) % 1 == 0

# returns the nth s-gonal number
# using wikipedia's polygonal number formula
def nth_polygonal(n, s):
    return (n**2 * (s - 2) - n * (s - 4)) // 2

# returns the totient of n using wikipedia's totient formula:
# n * (product of 1 - 1/p for all primes dividing n) == totient(n)
# BEFORE USING: generate_primes must be called with at least n+1
def totient(n):
    if n == 1:
        return 1
    return (int) (n * reduce(mul, [1 - 1 / p for p, e in prime_factor_array(n)]))


text:
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;

namespace DynamicaLabs.XrmTools.Tests
{
    public class OrganizationServiceAdapter : OrganizationService
    {
        public OrganizationServiceAdapter() : base(Mocked.MockedService())
        {

        }

        public OrganizationServiceAdapter(string connectionStringName) : base(connectionStringName)
        {
        }

        public OrganizationServiceAdapter(CrmConnection connection) : base(connection)
        {
        }

        public OrganizationServiceAdapter(IOrganizationService service) : base(service)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import unittest

from aids.sorting_and_searching.insertion_sort import insertion_sort

class InsertionSortTestCase(unittest.TestCase):
    '''
    Unit tests for insertion sort
    '''

    def setUp(self):
        self.example_1 = [18,5,3,1,19,6,0,7,4,2,5]

    def test_selection_sort(self):
        insertion_sort(self.example_1)
        self.assertEqual(self.example_1,[0,1,2,3,4,5,5,6,7,18,19])

    def tearDown(self):
        pass

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


text:
package com.azure.resourcemanager.synapse.implementation;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.synapse.fluent.SqlPoolWorkloadGroupsClient;
import com.azure.resourcemanager.synapse.fluent.models.WorkloadGroupInner;
import com.azure.resourcemanager.synapse.models.SqlPoolWorkloadGroups;
import com.azure.resourcemanager.synapse.models.WorkloadGroup;

public final class SqlPoolWorkloadGroupsImpl implements SqlPoolWorkloadGroups {
    private static final ClientLogger LOGGER = new ClientLogger(SqlPoolWorkloadGroupsImpl.class);

    private final SqlPoolWorkloadGroupsClient innerClient;

    private final com.azure.resourcemanager.synapse.SynapseManager serviceManager;

    public SqlPoolWorkloadGroupsImpl(
        SqlPoolWorkloadGroupsClient innerClient, com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public WorkloadGroup get(
        String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName) {
        WorkloadGroupInner inner =
            this.serviceClient().get(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName);
        if (inner != null) {
            return new WorkloadGroupImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    public Response<WorkloadGroup> getWithResponse(
        String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName, Context context) {
        Response<WorkloadGroupInner> inner =
            this
                .serviceClient()
                .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new WorkloadGroupImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public void delete(String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName) {
        this.serviceClient().delete(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName);
    }

    public void delete(
        String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName, Context context) {
        this.serviceClient().delete(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, context);
    }

    public PagedIterable<WorkloadGroup> list(String resourceGroupName, String workspaceName, String sqlPoolName) {
        PagedIterable<WorkloadGroupInner> inner =
            this.serviceClient().list(resourceGroupName, workspaceName, sqlPoolName);
        return Utils.mapPage(inner, inner1 -> new WorkloadGroupImpl(inner1, this.manager()));
    }

    public PagedIterable<WorkloadGroup> list(
        String resourceGroupName, String workspaceName, String sqlPoolName, Context context) {
        PagedIterable<WorkloadGroupInner> inner =
            this.serviceClient().list(resourceGroupName, workspaceName, sqlPoolName, context);
        return Utils.mapPage(inner, inner1 -> new WorkloadGroupImpl(inner1, this.manager()));
    }

    public WorkloadGroup getById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
        if (workspaceName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
        }
        String sqlPoolName = Utils.getValueFromIdByName(id, "sqlPools");
        if (sqlPoolName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'sqlPools'.", id)));
        }
        String workloadGroupName = Utils.getValueFromIdByName(id, "workloadGroups");
        if (workloadGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'workloadGroups'.", id)));
        }
        return this
            .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, Context.NONE)
            .getValue();
    }

    public Response<WorkloadGroup> getByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
        if (workspaceName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
        }
        String sqlPoolName = Utils.getValueFromIdByName(id, "sqlPools");
        if (sqlPoolName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'sqlPools'.", id)));
        }
        String workloadGroupName = Utils.getValueFromIdByName(id, "workloadGroups");
        if (workloadGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'workloadGroups'.", id)));
        }
        return this.getWithResponse(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, context);
    }

    public void deleteById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
        if (workspaceName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
        }
        String sqlPoolName = Utils.getValueFromIdByName(id, "sqlPools");
        if (sqlPoolName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'sqlPools'.", id)));
        }
        String workloadGroupName = Utils.getValueFromIdByName(id, "workloadGroups");
        if (workloadGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'workloadGroups'.", id)));
        }
        this.delete(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, Context.NONE);
    }

    public void deleteByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String workspaceName = Utils.getValueFromIdByName(id, "workspaces");
        if (workspaceName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'workspaces'.", id)));
        }
        String sqlPoolName = Utils.getValueFromIdByName(id, "sqlPools");
        if (sqlPoolName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'sqlPools'.", id)));
        }
        String workloadGroupName = Utils.getValueFromIdByName(id, "workloadGroups");
        if (workloadGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'workloadGroups'.", id)));
        }
        this.delete(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, context);
    }

    private SqlPoolWorkloadGroupsClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.synapse.SynapseManager manager() {
        return this.serviceManager;
    }

    public WorkloadGroupImpl define(String name) {
        return new WorkloadGroupImpl(name, this.manager());
    }
}


text:
from music21 import exceptions21
from music21 import corpus

if __name__ == '__main__':
    try:
        import guppy
    except ImportError:
        raise exceptions21.Music21Exception("memoryUsage.py requires guppy")

    hp = guppy.hpy()
    hp.setrelheap()
    x = corpus.parse('bwv66.6')
    h = hp.heap()
    print(h)


text:
namespace mtk {
    // Execute callback at the end of scope
    namespace detail {
        template<typename T>
        struct ScopeGuard {
        public:
            template<typename F,
                typename = std::enable_if_t<std::negation_v<std::is_same<std::decay_t<F>, ScopeGuard>>>>
                constexpr ScopeGuard(F&& f)
                : m_pair{ std::forward<F>(f), true }
            {}
            ~ScopeGuard() noexcept
            {
                if (m_pair.second())
                    m_pair.first()();
            }
            ScopeGuard(ScopeGuard&& other) noexcept(std::is_nothrow_move_constructible_v<T>)
                : m_pair{ std::move(other.m_pair.first()), other.m_pair.second() }
            {
                other.disable();
            }
            constexpr void disable() noexcept
            {
                m_pair.second() = false;
            }

        private:
            compressed_pair<T, bool> m_pair;
        };
    }

    template<typename T>
    constexpr detail::ScopeGuard<std::decay_t<T>> scope_guard(T&& f)
    {
        return { std::forward<T>(f) };
    }
}


text:
jest.unmock('./ReactDrawer.js');
/*eslint no-unused-vars: ["error", {varsIgnorePattern: "React[Drawer]*"}]*/
import React from 'react';
import ReactDrawer from './ReactDrawer';
import { shallow } from 'enzyme';

describe('ReactDrawer', () => {

  it('should display an overlay and a drawer', () => {
    const wrapper = shallow(
      <ReactDrawer open />
    );
    expect(wrapper.find('.react-drawer-overlay').length).toBe(1);
    expect(wrapper.find('.react-drawer-drawer').length).toBe(1);
  });
  it('with noOverlay should display a drawer', () => {
    const wrapper = shallow(
      <ReactDrawer open noOverlay />
    );
    expect(wrapper.find('.react-drawer-overlay').length).toBe(0);
    expect(wrapper.find('.react-drawer-drawer').length).toBe(1);
  });
  it('should onAnimationEnded change the state', () => {
    const wrapper = shallow(
      <ReactDrawer open />
    );
    const instance = wrapper.instance();
    instance.state.open = false;
    instance.state.hiddenOverlay = false;
    instance.onAnimationEnded();
    expect(instance.state.hiddenOverlay).toBe(true);
  });
  it('should componentWillMount set initial state from props', () => {
    let wrapper = shallow(
      <ReactDrawer open={false} />
    );
    let instance = wrapper.instance();
    expect(instance.state.open).toBe(false);
    wrapper = shallow(
      <ReactDrawer open />
    );
    instance = wrapper.instance();
    expect(instance.state.open).toBe(true);
    expect(instance.state.hiddenOverlay).toBe(true);
    expect(instance.state.hiddenDrawer).toBe(true);
  });
  it('should closeDrawer set some state', () => {
    const wrapper = shallow(
      <ReactDrawer open />
    );
    const instance = wrapper.instance();
    expect(instance.state.open).toBe(true);
    instance.closeDrawer();
    expect(instance.state.open).toBe(false);
  });
  it('should closeDrawer call onClose', () => {
    const onClose = jest.fn();
    const wrapper = shallow(
      <ReactDrawer open onClose={onClose}/>
    );
    const instance = wrapper.instance();
    expect(onClose.mock.calls.length).toBe(0);
    instance.closeDrawer();
    expect(onClose.mock.calls.length).toBe(1);
  });
  it('should openDrawer set some state', () => {
    const wrapper = shallow(
      <ReactDrawer open={false} />
    );
    const instance = wrapper.instance();
    instance.openDrawer();
    expect(instance.state.hiddenOverlay).toBe(false);
    expect(instance.state.hiddenDrawer).toBe(false);
    expect(instance.state.open).toBe(true);
  });
  it('should componentWillReceiveProps call openDrawer/closeDrawer', () => {
    const wrapper = shallow(
      <ReactDrawer open={false} />
    );
    const instance = wrapper.instance();
    expect(instance.state.open).toBe(false);
    instance.openDrawer = jest.fn();
    instance.closeDrawer = jest.fn();
    instance.componentWillReceiveProps({open: true});
    expect(instance.openDrawer.mock.calls.length).toBe(1);
    expect(instance.closeDrawer.mock.calls.length).toBe(0);
    // now lets close it
    instance.state.open = true;
    instance.componentWillReceiveProps({open: false});
    expect(instance.closeDrawer.mock.calls.length).toBe(1);
  });
  it('should componentDidMount add an event listener', () => {
    const wrapper = shallow(
      <ReactDrawer open />
    );
    const instance = wrapper.instance();
    instance.drawer = {
      addEventListener: jest.fn()
    };
    instance.componentDidMount();
    const calls = instance.drawer.addEventListener.mock.calls;
    expect(calls.length).toBe(1);
    expect(calls[0].length).toBe(2);
    expect(calls[0][0]).toBe('webkitAnimationEnd');
    expect(calls[0][1]).toBe(instance.onAnimationEnded);
  });
  it('should componentWillUnmount remove an event listener', () => {
    const wrapper = shallow(
      <ReactDrawer open />
    );
    const instance = wrapper.instance();
    instance.drawer = {
      removeEventListener: jest.fn()
    };
    instance.componentWillUnmount();
    const calls = instance.drawer.removeEventListener.mock.calls;
    expect(calls.length).toBe(1);
    expect(calls[0].length).toBe(2);
    expect(calls[0][0]).toBe('webkitAnimationEnd');
    expect(calls[0][1]).toBe(instance.onAnimationEnded);
  });
  it('should getOverlayClassName return class', () => {
    const theme = {
      overlay: 'test-overlay',
      hidden: 'test-hidden'
    };
    const animate = {
      'fadeIn': 'test-fadeIn',
      'fadeOut': 'test-fadeOut'
    };
    const wrapper = shallow(
      <ReactDrawer open />
    );
    const instance = wrapper.instance();
    let c = instance.getOverlayClassName(theme, animate).split(' ');
    expect(c.length).toBe(4);
    expect(c.indexOf('react-drawer-overlay')).not.toBe(-1);
    expect(c.indexOf('test-overlay')).not.toBe(-1);
    expect(c.indexOf('test-fadeIn')).not.toBe(-1);
    expect(c.indexOf('test-hidden')).not.toBe(-1);

    instance.state.open = false;
    c = instance.getOverlayClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeIn')).toBe(-1);
    expect(c.indexOf('test-fadeOut')).not.toBe(-1);

    instance.state.hiddenOverlay = false;
    c = instance.getOverlayClassName(theme, animate).split(' ');
    expect(c.indexOf('test-hidden')).toBe(-1);
  });
  it('should getDrawerClassName return class', () => {
    const theme = {
      drawer: 'test-drawer',
      'drawer-top': 'test-drawer-top',
      'drawer-bottom': 'test-drawer-bottom',
      'drawer-left': 'test-drawer-left',
      'drawer-right': 'test-drawer-right',
      hidden: 'test-hidden'
    };
    const animate = {
      'fadeInUp': 'test-fadeInUp',
      'fadeInDown': 'test-fadeInDown',
      'fadeInLeft': 'test-fadeInLeft',
      'fadeInRight': 'test-fadeInRight',
      'fadeOutUp': 'test-fadeOutUp',
      'fadeOutDown': 'test-fadeOutDown',
      'fadeOutLeft': 'test-fadeOutLeft',
      'fadeOutRight': 'test-fadeOutRight'
    };
    const wrapper = shallow(
      <ReactDrawer open />
    );
    let instance = wrapper.instance();
    let c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.length).toBe(5);
    expect(c.indexOf('react-drawer-drawer')).not.toBe(-1);
    expect(c.indexOf('test-drawer')).not.toBe(-1);
    expect(c.indexOf('test-hidden')).not.toBe(-1);
    expect(c.indexOf('test-fadeInUp')).toBe(-1);
    expect(c.indexOf('test-fadeInRight')).not.toBe(-1);
    expect(c.indexOf('test-fadeInDown')).toBe(-1);
    expect(c.indexOf('test-fadeInLeft')).toBe(-1);

    wrapper.setProps({position: 'top'});
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeInUp')).toBe(-1);
    expect(c.indexOf('test-fadeInRight')).toBe(-1);
    expect(c.indexOf('test-fadeInDown')).not.toBe(-1);
    expect(c.indexOf('test-fadeInLeft')).toBe(-1);

    wrapper.setProps({position: 'bottom'});
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeInUp')).not.toBe(-1);
    expect(c.indexOf('test-fadeInRight')).toBe(-1);
    expect(c.indexOf('test-fadeInDown')).toBe(-1);
    expect(c.indexOf('test-fadeInLeft')).toBe(-1);

    wrapper.setProps({position: 'left'});
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeInUp')).toBe(-1);
    expect(c.indexOf('test-fadeInRight')).toBe(-1);
    expect(c.indexOf('test-fadeInDown')).toBe(-1);
    expect(c.indexOf('test-fadeInLeft')).not.toBe(-1);

    wrapper.setProps({position: 'right'});
    instance = wrapper.instance();
    instance.state.open = false;
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('react-drawer-drawer')).not.toBe(-1);
    expect(c.indexOf('test-drawer')).not.toBe(-1);
    expect(c.indexOf('test-fadeOutUp')).toBe(-1);
    expect(c.indexOf('test-fadeOutRight')).not.toBe(-1);
    expect(c.indexOf('test-fadeOutDown')).toBe(-1);
    expect(c.indexOf('test-fadeOutLeft')).toBe(-1);

    wrapper.setProps({position: 'top'});
    instance = wrapper.instance();
    instance.state.open = false;
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeOutUp')).not.toBe(-1);
    expect(c.indexOf('test-fadeOutRight')).toBe(-1);
    expect(c.indexOf('test-fadeOutDown')).toBe(-1);
    expect(c.indexOf('test-fadeOutLeft')).toBe(-1);

    wrapper.setProps({position: 'bottom'});
    instance = wrapper.instance();
    instance.state.open = false;
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeOutUp')).toBe(-1);
    expect(c.indexOf('test-fadeOutRight')).toBe(-1);
    expect(c.indexOf('test-fadeOutDown')).not.toBe(-1);
    expect(c.indexOf('test-fadeOutLeft')).toBe(-1);

    wrapper.setProps({position: 'left'});
    instance = wrapper.instance();
    instance.state.open = false;
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-fadeOutUp')).toBe(-1);
    expect(c.indexOf('test-fadeOutRight')).toBe(-1);
    expect(c.indexOf('test-fadeOutDown')).toBe(-1);
    expect(c.indexOf('test-fadeOutLeft')).not.toBe(-1);

    instance.state.hiddenDrawer = false;
    c = instance.getDrawerClassName(theme, animate).split(' ');
    expect(c.indexOf('test-hidden')).toBe(-1);
  });
});


text:
package org.apache.hadoop.hbase.regionserver;

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

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.FSTableDescriptors;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({ RegionServerTests.class, SmallTests.class })
public class TestReadAndWriteRegionInfoFile {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestReadAndWriteRegionInfoFile.class);

  private static final HBaseCommonTestingUtility UTIL = new HBaseTestingUtility();

  private static final Configuration CONF = UTIL.getConfiguration();

  private static FileSystem FS;

  private static Path ROOT_DIR;

  @BeforeClass
  public static void setUp() throws IOException {
    ROOT_DIR = UTIL.getDataTestDir();
    FS = ROOT_DIR.getFileSystem(CONF);
  }

  @AfterClass
  public static void tearDown() {
    UTIL.cleanupTestDir();
  }

  @Test
  public void testReadAndWriteRegionInfoFile() throws IOException, InterruptedException {
    RegionInfo ri = RegionInfoBuilder.FIRST_META_REGIONINFO;
    // Create a region. That'll write the .regioninfo file.
    FSTableDescriptors fsTableDescriptors = new FSTableDescriptors(FS, ROOT_DIR);
    FSTableDescriptors.tryUpdateAndGetMetaTableDescriptor(CONF, FS, ROOT_DIR);
    HRegion r = HBaseTestingUtility.createRegionAndWAL(ri, ROOT_DIR, CONF,
      fsTableDescriptors.get(TableName.META_TABLE_NAME));
    // Get modtime on the file.
    long modtime = getModTime(r);
    HBaseTestingUtility.closeRegionAndWAL(r);
    Thread.sleep(1001);
    r = HRegion.openHRegion(ROOT_DIR, ri, fsTableDescriptors.get(TableName.META_TABLE_NAME), null,
      CONF);
    // Ensure the file is not written for a second time.
    long modtime2 = getModTime(r);
    assertEquals(modtime, modtime2);
    // Now load the file.
    HRegionFileSystem.loadRegionInfoFileContent(r.getRegionFileSystem().getFileSystem(),
      r.getRegionFileSystem().getRegionDir());
    HBaseTestingUtility.closeRegionAndWAL(r);
  }

  private long getModTime(final HRegion r) throws IOException {
    FileStatus[] statuses = r.getRegionFileSystem().getFileSystem().listStatus(
      new Path(r.getRegionFileSystem().getRegionDir(), HRegionFileSystem.REGION_INFO_FILE));
    assertTrue(statuses != null && statuses.length == 1);
    return statuses[0].getModificationTime();
  }
}


text:
<?php  if ( ! defined('ROOT')) exit('Script access is forbidden');

 /**
 * @version 1.2
 * @author DinuSV
 */

/**
 * @ingroup libraries
 * @brief Provides a paypal interface wrapper
 *
 * Usage
 *
 * @code
 * // Paypal form usage
 *
 * $paypal = new PayPal();
 * $paypal->createForm( 'mybusiness', 'itemnumber33', 'USD', 20 );
 * // if you want a recurring payment type
 * $paypal->recurringPaymentType('M');
 * $paypal->redirectAfter( 0 );
 * $paypal->formIpn('myurl');
 * $paypal->formOutput();
 * @endcode
 *
 *
 * @code
 * // Paypal ipn usage
 *
 * $paypal = new PayPal();
 * try {
 * 	if ( $paypal->validIpn() ){
 * 		//get id of the item the payment was made for
 * 		$id = $paypal->ipnPostedData( 'item_number' );
 * 	} else
 * 		//payment not successful
 * } catch( Exception $e ){
 * 	// Invalid IPN
 * }
 * @endcode
 */
class PayPal{

	/**
	 * @var SANDBOX
	 * string : Paypal sandbox post link
	 */
	const SANDBOX = 'https://sandbox.paypal.com/cgi-bin/webscr';

	/**
	 * @var ACTIVE
	 * string : Paypal active post link
	 */
	const ACTIVE  = 'https://www.paypal.com/cgi-bin/websrc';

	/**
	 * @var PPURL
	 * string : Paypal url
	 */
	const PPURL   = 'www.paypal.com';

	/**
	 * @var PPSBURL
	 * string : Paypal developer url
	 */
	const PPSBURL = 'sandbox.paypal.com';

	private

	/*
	 * Paypal Form Fields
	 * ----------------------------------------- */

		/**
		 * @var $form_fields
		 * array : Fields that will be posted to paypal
		 */
		$form_fields       = array(),

		/**
		 * @var $form_submit_image
		 * string : Custom submit button
		 */
		$form_submit_image = null,

		/**
		 * @var $form_action
		 * string : Paypal form action, can be either the paypal sandbox url or the original one
		 */
		$form_action       = '',

		/**
		 * @var $form_redirect
		 * string : Submit the form using javascript after a set number of seconds. Set this to 0 to
		 * disable autosubmitting
		 */
		$form_redirect     = 10,

	/*
	 * Paypal Ipn Fields
	 * ----------------------------------------- */

		/**
		 * @var $ipn_posted_data
		 * string : The posted data received by the ipn request
		 */
		$ipn_posted_data,

		/**
		 * @var $ipn_payment_data
		 * string : Payment data processed from the posted data received by ipn
		 */
		$ipn_payment_data  = array();

	/** Construct
	 */
	public function PayPal(){
		$this->form_fields['cmd'] = '_xclick';
	}

	/*
	 * Paypal Form Methods
	 * ----------------------------------------- */

	/** Creates a form based on the required fields
	 *
	 * @param string $business      : email adress for the paypal account
	 * @param string $item_name     : name of the item or shopping cart( must be 127 characters max )
	 * @param string $currency_code : defines the currency in which the monetary variables are denoted
	 * @param string $price         : price of the item or the total price of all items in the shopping cart
	 * @param Tag $submit            : [optional] the button for the buyer to press in order to initiate the
	 * 	process. The default will be the paypal button 'x-click-but01.gif' from their website.
	 * @param string $action        : [optional] the location the form will be submited to. The default value
	 * 	is https://www.paypal.com/cgi-bin/websrc
	 *
	 * @return PayPal : current object
	 */
	public function createForm( $business, $item_name, $currency_code, $price, $submit = null, $action = null ){
		$this->headersNoCache();
		if ( $submit === null )
			$this->form_submit_image = new Tag( 'input',array(
				'type' => 'submit',
				'value' => 'Buy now'
			));
		else
			$this->form_submit_image = $submit;
		if ( $action === null )
			$this->form_action = self::ACTIVE;
		else $this->form_action = $action;
		$this->formSet( array(
			'business'      => $business,
			'item_name'     => $item_name,
			'currency_code' => $currency_code,
			'amount'        => $price,
		));
		return $this;
	}

	/** Set fields for the form
	 *
	 * @param string $fields : field name
	 * @param array $fields  : array of field names and values to set
	 * @param string $value  : [optional]field value
	 *
	 * @return PayPal : current object
	 */
	public function formSet( $fields, $value = '' ){
		if ( !is_array( $fields ) ){
			$this->form_fields[$fields] = $value;
		} else {
			$this->form_fields = array_merge( $this->form_fields, $fields );
		}
		return $this;
	}

	/** Set form action, PayPal::SANDBOX, PayPal::ACTIVE can be used
	 *
	 * @param string $action
	 *
	 * @return PayPal : current object
	 */
	public function formAction( $action ){
		$this->form_action = $action;
		return $this;
	}

	/** Set the payment type : once a day, a month, a year or just one payment
	 *
	 * @param string $type   : once / day / month / year
	 * @param integer $every : [optional] enable recurring payment for every number of years/months/days
	 */
	public function recurringPaymentType( $type, $every = 1 ){
		$this->formSet( 'src', '1' );
		$this->formSet( 'sra', '1' );
		$this->formSet( 'cmd', '_xclick-subscriptions' );
		if ( isset( $this->form_fields['amount'] ) ){
			$price = $this->form_fields['amount'];
			unset( $this->form_fields['amount'] );
		} else $price = 0;
		$this->formSet( 'a3', $price );
		$this->formSet( 'no_note', 1 );
		$this->formSet( 'no_shipping', 1 );
		$type = strtoupper( $type[0] );
		if ( $type === 'Y' || $type === 'M' || $type !== 'D' ){
			$this->formSet( 't3', $type );
			$this->formSet( 'p3', $every );
		} else throw new InvalidArgumentTypeException("Type must be day/month/year/once. Unexpected value");
		return $this;
	}

	/** Redirect the form to paypal after a set number of seconds
	 *
	 * @param integer $seconds
	 *
	 * @return PayPal : current object
	 */
	public function redirectAfter( $seconds ){
		$this->form_redirect = $seconds;
		return $this;
	}

	/** Set paypals instant payment notification
	 *
	 * @param string $ipn_url
	 *
	 * @return PayPal : current object
	 */
	public function formIpn( $ipn_url ){
		$this->formSet( 'notify_url', $ipn_url );
		return $this;
	}

	/** Set the paypal form to the extended version in order to support more arguments
	 *
	 * @return PayPal : current object
	 */
	public function formExtend(){
		$this->formSet( 'redirect_cmd', $this->form_fields['cmd'] );
		$this->formSet( 'cmd', '_ext-enter' );
		return $this;
	}

	/** Generate the form and output it
	 */
	public function formOutput(){
		$form = new Form('post', $this->form_action );
		/* Set form name */
		if ( $this->form_redirect > 0 && !$form->hasAttribute('name') )
			$form->setAttribute( 'name', 'paypalsubmitform' );;
		/* Form */
		echo $form->create();
		foreach( $this->form_fields as $fieldname => $fieldvalue ){
			echo $form->input( 'hidden', $fieldname, $fieldvalue );
		}
		echo $this->form_submit_image;
		echo $form->end();
		if ( $this->form_redirect > 0 ){
			echo '<script>' .
				'setTimeout("pp_submit()", ' . $this->form_redirect . ' * 100);' .
				'function pp_submit(){ document.' . $form>getAttribute('name') . '.submit(); }' .
				'</script>';
		}
	}

	/** Function call recomended in order to disable caching before outputing the form
	 */
	public function headersNoCache(){
		header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Cache-Control: pre-check=0, post-check=0, max-age=0');
		header('Pragma: no-cache');
	}

	/*
	 * Paypal Ipn Methods
	 * ----------------------------------------- */

	/** Get ipn payment data after the ipn has been processed
	 *
	 * @param string $key : [optional]set to null in order to return all the values as an array
	 *
	 * @throws IndexOutOfBoundsException
	 *
	 * @return array  : returns an empty array if the fields haven't been set
	 * @return string : returns the value if a key is given
	 */
	public function ipnPaymentData( $key = null ){
		if ( $key === null )
			return $this->ipn_payment_data;
		else {
			if ( !isset( $this->ipn_payment_data[$key] ) )
				throw new IndexOutOfBoundsException( 'Cannot find index ' . $key . ' for IpnPaymentData' );
			return $this->ipn_payment_data[$key];
		}
	}

	/** Get posted data from paypal after the ipn has been processed
	 *
	 * @param string $key : [optional]set to null in order to return all the values as an array
	 *
	 * @throws IndexOutOfBoundsException
	 *
	 * @return array  : returns an empty array if the fields haven't been set
	 * @return string : returns the value if a key is given
	 */
	public function ipnPostedData( $key = null ){
		if ( $key = null )
			return $this->ipn_posted_data;
		else {
			if ( !isset( $this->ipn_posted_data[$key] ) )
				throw new IndexOutOfBoundsException( 'Cannot find index ' . $key . ' for IpnPostedData' );
			return $this->ipn_posted_data[$key];
		}
	}

	/** Checks is the request is a valid ipn from paypal
	 *
	 * @param string $paypalurl          : [optional] paypal url to post data to
	 *
	 * @throws PageNotFoundException     : in case the paypal connection can't be established
	 * @throws IncompleteActionException : in case the ipn verification failed
	 *
	 * @return boolean : true if it's a valid Ipn, false otherwise
	 */
	public function validIpn( $paypalurl = self::PPURL ){
		if ( empty($_POST) ) return false;
		$price = 0; $postvars = 0;
		/* Return the data to paypal in order to check for the payment */
		foreach( $_POST as $key => $value ){
			$postvars .= $key . '=' . urlencode($value) . '&';
			$this->ipn_posted_data[$key] = $value;
		}
		$postvars .= 'cmd=_notify-validate';
		$errstr = ''; $errno = '';
		/* Open the connection */
		$fp= @ fsockopen( $paypalurl, 80, $errno, $errstr, 30 );
		if (!$fp) throw new PageNotFoundException( 'fsockopen error no. ' . $errno . ':' .  $errstr );
		/* Send data */
		@ fputs($fp, "POST /cgi-bin/webscr HTTP/1.1\r\n");
		@ fputs($fp, "Host: ".$paypalurl."\r\n");
		@ fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
		@ fputs($fp, "Content-length: ".strlen($postvars)."\r\n");
		@ fputs($fp, "Connection: close\r\n\r\n");
		@ fputs($fp, $postvars . "\r\n\r\n");
		/* Get page contents */
		$str = '';
		while( !feof( $fp ) )
			$str .= @ fgets( $fp, 1024 );
		@ fclose($fp);
		/* Check if this payment has been verified */
		if( !preg_match( '/VERIFIED/i', $str ) )
			throw new IncompleteActionException( 'Ipn verification failed' );

		/* If everything ok, proceed with parsing the posted data */
		if( preg_match( '/subscr/', $this->ipn_posted_data['txn_type'] ) ) {
			$this->ipn_payment_data['type'] = 'subscription';
			if ( in_array( $this->ipn_posted_data['txn_type'], array('subscr_signup') ) )
				return false;
			if( $this->ipn_posted_data['txn_type'] == 'subscr_payment' ) {
				if( $this->ipn_posted_data['payment_status'] == 'Completed' ) {
					$this->ipn_payment_data['price'] = $this->ipn_posted_data['mc_amount3'];
					return true;
				}
			}
		} else {
			if( $this->ipn_posted_data['payment_status'] == 'Completed' ){
				$this->ipn_payment_data['type']  = 'payment';
				$this->ipn_payment_data['price'] = $this->ipn_posted_data['mc_gross'];
				return true;
			}
		}
		return false;
	}
}


text:
<!--

-->
<!--@subject {{trans "Currency Update Warnings"}} @-->
<!--@vars {
"var warnings":"Currency Update Warnings"
} @-->

{{trans "Currency Update Warnings"}}

{{var warnings}}


text:
<ion-view title="{{species.name}}">
    <ion-content has-header="true">

                    {{species.item.name}} ({{species.item.commonNameSingle}})

 Spotted {{species.occurence}} times in the area.

Commonly known as: {{species.item.commonNameSingle}}

Other names: {{species.item.commonName}}

    </ion-content>
</ion-view>


text:
var ICustomDataAttributes = {
	setOnClickEvents: function(withinDivId) {}
}


text:
import React from 'react'
import PropTypes from 'prop-types'
import getConfig from 'next/config'
import {uniqBy, sortBy} from 'lodash'

import SimpleDownload from '../downloads/simple'
import VectorDownload from '../downloads/vector'

const {publicRuntimeConfig: {
  PUBLIC_URL,
  TRANSCODER_URL
}} = getConfig()

const DOWNLOAD_RESOURCE_TYPE_ORDER = {
  vector: 1,
  raster: 2,
  table: 3,
  data: 4
}

class DownloadResource extends React.Component {
  static propTypes = {
    recordId: PropTypes.string.isRequired,
    resource: PropTypes.shape({
      name: PropTypes.string,
      description: PropTypes.string,
      href: PropTypes.string.isRequired,
      downloads: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.string.isRequired,
        type: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
        url: PropTypes.string.isRequired
      })).isRequired
    }).isRequired,

    setPreview: PropTypes.func.isRequired
  }

  renderDownload(download) {
    switch (download.resourceType) {
      case 'vector': {
        const {recordId, resource, setPreview} = this.props

        const url = `${TRANSCODER_URL}/links/${resource.proxyId}/downloads/${download.id}`
        const embed = `${PUBLIC_URL}/embed/datasets/${recordId}/resources/download:${resource.proxyId}/${download.id}`

        return (
          <VectorDownload
            available
            name={download.name}
            url={url}
            setPreview={() => setPreview(url, download.name, embed)}
          />
        )
      }

      default:
        return (
          <SimpleDownload
            type={download.type}
            name={download.name}
            url={download.url}
          />
        )
    }
  }

  render() {
    const {resource} = this.props

    const downloads = sortBy(
      uniqBy(resource.downloads, download => {
        return download.type + download.name
      }),
      download => {
        return DOWNLOAD_RESOURCE_TYPE_ORDER[download.resourceType]
      }
    )

    return (

{resource.name || resource.href}

{resource.description && resource.description}

          {downloads.map(download => (

              {this.renderDownload(download)}

          ))}

    )
  }
}

export default DownloadResource


text:
const path = require('path');
const fse = require('fs-extra');
const helpers = require('yeoman-test');

const { SERVER_MAIN_RES_DIR, SERVER_MAIN_SRC_DIR, CLIENT_MAIN_SRC_DIR } = require('../../generators/generator-constants');

const DEFAULT_TEST_OPTIONS = { fromCli: true, skipInstall: true, skipChecks: true, skipPrettier: true };

describe('jhipster:entities', () => {
  context('when regenerating', () => {
    describe('some entities', () => {
      let runResult;
      before(() =>
        helpers
          .create(require.resolve('../../generators/entities'))
          .doInDir(dir => {
            fse.copySync(path.join(__dirname, '../templates/default'), dir);
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple.json'), path.join(dir, '.jhipster/Foo.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple2.json'), path.join(dir, '.jhipster/Bar.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple3.json'), path.join(dir, '.jhipster/Skip.json'));
          })
          .withArguments(['Foo', 'Bar'])
          .withOptions({ ...DEFAULT_TEST_OPTIONS, regenerate: true, force: true })
          .run()
          .then(result => {
            runResult = result;
          })
      );

      after(() => runResult.cleanup());

      it('should create files for entity Foo', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101210_added_entity_Foo.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Foo.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/foo/foo.model.ts`,
        ]);
      });

      it('should create files for the entity Bar', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101211_added_entity_Bar.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Bar.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/bar/bar.model.ts`,
        ]);
      });

      it('should not create files for the entity Skip', () => {
        runResult.assertNoFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101212_added_entity_Skip.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Skip.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/skip/skip.model.ts`,
        ]);
      });
    });

    describe('selected entities with writeEveryEntity', () => {
      let runResult;
      before(() =>
        helpers
          .create(require.resolve('../../generators/entities'))
          .doInDir(dir => {
            fse.copySync(path.join(__dirname, '../templates/default'), dir);
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple.json'), path.join(dir, '.jhipster/Foo.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple2.json'), path.join(dir, '.jhipster/Bar.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple3.json'), path.join(dir, '.jhipster/Skip.json'));
          })
          .withArguments(['Foo', 'Bar'])
          .withOptions({ ...DEFAULT_TEST_OPTIONS, regenerate: true, force: true, writeEveryEntity: true })
          .run()
          .then(result => {
            runResult = result;
          })
      );

      after(() => runResult.cleanup());

      it('should create files for entity Foo', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101210_added_entity_Foo.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Foo.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/foo/foo.model.ts`,
        ]);
      });

      it('should create files for the entity Bar', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101211_added_entity_Bar.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Bar.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/bar/bar.model.ts`,
        ]);
      });

      it('should create files for the entity Skip', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101212_added_entity_Skip.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Skip.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/skip/skip.model.ts`,
        ]);
      });
    });

    describe('all entities', () => {
      let runResult;
      before(() =>
        helpers
          .create(require.resolve('../../generators/entities'))
          .doInDir(dir => {
            fse.copySync(path.join(__dirname, '../templates/default'), dir);
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple.json'), path.join(dir, '.jhipster/Foo.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple2.json'), path.join(dir, '.jhipster/Bar.json'));
            fse.copySync(path.join(__dirname, '../templates/.jhipster/Simple3.json'), path.join(dir, '.jhipster/Skip.json'));
          })
          .withOptions({ ...DEFAULT_TEST_OPTIONS, regenerate: true, force: true })
          .run()
          .then(result => {
            runResult = result;
          })
      );

      after(() => runResult.cleanup());

      it('should create files for entity Foo', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101210_added_entity_Foo.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Foo.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/foo/foo.model.ts`,
        ]);
      });

      it('should create files for the entity Bar', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101211_added_entity_Bar.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Bar.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/bar/bar.model.ts`,
        ]);
      });

      it('should create files for the entity Skip', () => {
        runResult.assertFile([
          `${SERVER_MAIN_RES_DIR}config/liquibase/changelog/20160926101212_added_entity_Skip.xml`,
          `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/domain/Skip.java`,
          `${CLIENT_MAIN_SRC_DIR}app/entities/skip/skip.model.ts`,
        ]);
      });
    });
  });
});


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#include "unicode/dcfmtsym.h"
#include "unicode/decimfmt.h"
#include "unicode/msgfmt.h"
#include "unicode/plurfmt.h"
#include "unicode/plurrule.h"
#include "cmemory.h"
#include "plurfmts.h"
#include "plurults.h"

#define PLURAL_PATTERN_DATA 4
#define PLURAL_TEST_ARRAY_SIZE 256

#define PLURAL_SYNTAX_DATA 8

// The value must be same as PLKeywordLookups[] order.
#define PFT_ZERO   0
#define PFT_ONE    1
#define PFT_TWO    2
#define PFT_FEW    3
#define PFT_MANY   4
#define PFT_OTHER  5

void PluralFormatTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
    if (exec) logln("TestSuite PluralFormat");
    TESTCASE_AUTO_BEGIN;
    TESTCASE_AUTO(pluralFormatBasicTest);
    TESTCASE_AUTO(pluralFormatUnitTest);
    TESTCASE_AUTO(pluralFormatLocaleTest);
    TESTCASE_AUTO(pluralFormatExtendedTest);
    TESTCASE_AUTO(pluralFormatExtendedParseTest);
    TESTCASE_AUTO(ordinalFormatTest);
    TESTCASE_AUTO(TestDecimals);
    TESTCASE_AUTO_END;
}

/**
 * Test various generic API methods of PluralFormat for Basic usage.
 */
void PluralFormatTest::pluralFormatBasicTest(/*char *par*/)
{
    UErrorCode status[8];
    PluralFormat* plFmt[8];
    Locale        locale = Locale::getDefault();
    UnicodeString otherPattern = UnicodeString("other{#}");
    UnicodeString message=UnicodeString("ERROR: PluralFormat basic test");

    // ========= Test constructors
    logln(" Testing PluralFormat constructors ...");
    status[0] = U_ZERO_ERROR;
    PluralRules*  plRules = PluralRules::createDefaultRules(status[0]);

    status[0] = U_ZERO_ERROR;
    NumberFormat *numFmt = NumberFormat::createInstance(status[0]);
    if (U_FAILURE(status[0])) {
        dataerrln("ERROR: Could not create NumberFormat instance with default locale ");
    }

    for (int32_t i=0; i< 8; ++i) {
        status[i] = U_ZERO_ERROR;
    }
    plFmt[0] = new PluralFormat(status[0]);
    plFmt[1] = new PluralFormat(*plRules, status[1]);
    plFmt[2] = new PluralFormat(locale, status[2]);
    plFmt[3] = new PluralFormat(locale, *plRules, status[3]);
    plFmt[4] = new PluralFormat(otherPattern, status[4]);
    plFmt[5] = new PluralFormat(*plRules, otherPattern, status[5]);
    plFmt[6] = new PluralFormat(locale, otherPattern, status[6]);
    plFmt[7] = new PluralFormat(locale, *plRules, otherPattern, status[7]);

    for (int32_t i=0; i< 8; ++i) {
        if (U_SUCCESS(status[i])) {
            numberFormatTest(plFmt[i], numFmt, 1, 12, NULL, NULL, FALSE, &message);
            numberFormatTest(plFmt[i], numFmt, 100, 112, NULL, NULL, FALSE, &message);
        }
        else {
            dataerrln("ERROR: PluralFormat constructor failed!");
        }
       delete plFmt[i];
    }
    // ======= Test clone, assignment operator && == operator.
    plFmt[0]= new PluralFormat(status[0]);
    plFmt[0]->setNumberFormat(numFmt,status[0]);
    UnicodeString us = UnicodeString("");
    plFmt[0]->toPattern(us);
    plFmt[1]= new PluralFormat(locale, status[1]);
    if ( U_SUCCESS(status[0]) && U_SUCCESS(status[1]) ) {
        *plFmt[1] = *plFmt[0];
        if (plFmt[1]!=NULL) {
            if ( *plFmt[1] != *plFmt[0] ) {
                errln("ERROR:  clone plural format test failed!");
            }
        }
    }
    else {
         dataerrln("ERROR: PluralFormat constructor failed! - [0]%s [1]%s", u_errorName(status[0]), u_errorName(status[1]));
    }
    delete plFmt[0];

    status[0] = U_ZERO_ERROR;
    plFmt[0]= new PluralFormat(locale, status[0]);
    if ( U_SUCCESS(status[0]) ) {
        *plFmt[1] = *plFmt[0];
        if (plFmt[1]!=NULL) {
            if ( *plFmt[1] != *plFmt[0] ) {
                errln("ERROR:  assignment operator test failed!");
            }
        }
    }
    else {
         dataerrln("ERROR: PluralFormat constructor failed! - %s", u_errorName(status[1]));
    }

    if ( U_SUCCESS(status[1]) ) {
        plFmt[2] = (PluralFormat*) plFmt[1]->clone();

        if (plFmt[1]!=NULL) {
            if ( *plFmt[1] != *plFmt[2] ) {
                errln("ERROR:  clone function test failed!");
            }
        }
        delete plFmt[1];
        delete plFmt[2];
    }
    else {
         dataerrln("ERROR: PluralFormat clone failed! - %s", u_errorName(status[1]));
    }

    delete plFmt[0];
    delete numFmt;
    delete plRules;

    // Tests parseObject
    UErrorCode stat = U_ZERO_ERROR;
    PluralFormat *pf = new PluralFormat(stat);
    Formattable *f = new Formattable();
    ParsePosition *pp = new ParsePosition();
    pf->parseObject((UnicodeString)"",*f,*pp);
    if(U_FAILURE(stat)) {
        dataerrln("ERROR: PluralFormat::parseObject: %s", u_errorName(stat));
    }
    delete pf;
    delete f;
    delete pp;
}

/**
 * Unit tests of PluralFormat class.
 */
void PluralFormatTest::pluralFormatUnitTest(/*char *par*/)
{
    UnicodeString patternTestData[PLURAL_PATTERN_DATA] = {
        UNICODE_STRING_SIMPLE("odd {# is odd.} other{# is even.}"),
        UNICODE_STRING_SIMPLE("other{# is odd or even.}"),
        UNICODE_STRING_SIMPLE("odd{The number {0, number, #.#0} is odd.}other{The number {0, number, #.#0} is even.}"),
        UNICODE_STRING_SIMPLE("odd{The number {1, number, #} is odd.}other{The number {2, number, #} is even.}"),
    };
    UnicodeString patternOddTestResult[PLURAL_PATTERN_DATA] = {
        UNICODE_STRING_SIMPLE(" is odd."),
        UNICODE_STRING_SIMPLE(" is odd or even."),
        UNICODE_STRING_SIMPLE("The number {0, number, #.#0} is odd."),
        UNICODE_STRING_SIMPLE("The number {1, number, #} is odd."),
    };
    UnicodeString patternEvenTestResult[PLURAL_PATTERN_DATA] = {
        UNICODE_STRING_SIMPLE(" is even."),
        UNICODE_STRING_SIMPLE(" is odd or even."),
        UNICODE_STRING_SIMPLE("The number {0, number, #.#0} is even."),
        UNICODE_STRING_SIMPLE("The number {2, number, #} is even."),
    };
    UnicodeString checkSyntaxtData[PLURAL_SYNTAX_DATA] = {
        // ICU 4.8 does not check for duplicate keywords any more.
        //UNICODE_STRING_SIMPLE("odd{foo} odd{bar} other{foobar}"),
        //UNICODE_STRING_SIMPLE("odd{foo} other{bar} other{foobar}"),
        UNICODE_STRING_SIMPLE("odd{foo}"),
        // ICU 4.8 does not check for unknown keywords any more.
        //UNICODE_STRING_SIMPLE("otto{foo} other{bar}"),
        UNICODE_STRING_SIMPLE("*odd{foo} other{bar}"),
        UNICODE_STRING_SIMPLE("odd{foo},other{bar}"),
        UNICODE_STRING_SIMPLE("od d{foo} other{bar}"),
        UNICODE_STRING_SIMPLE("odd{foo}{foobar}other{foo}"),
    };

    UErrorCode status = U_ZERO_ERROR;
    UnicodeString oddAndEvenRule = UNICODE_STRING_SIMPLE("odd: n mod 2 is 1");
    PluralRules*  plRules = PluralRules::createRules(oddAndEvenRule, status);
    if (U_FAILURE(status)) {
        dataerrln("ERROR:  create PluralRules instance failed in unit tests.- exitting");
        return;
    }

    // ======= Test PluralRules pattern syntax.
    logln("Testing PluralRules pattern syntax.");
    for (int32_t i=0; i<PLURAL_SYNTAX_DATA; ++i) {
        status = U_ZERO_ERROR;

        PluralFormat plFmt=PluralFormat(*plRules, status);
        if (U_FAILURE(status)) {
            dataerrln("ERROR:  PluralFormat constructor failed in unit tests.- exitting");
            return;
        }
        plFmt.applyPattern(checkSyntaxtData[i], status);
        if (U_SUCCESS(status)) {
            errln("ERROR:  PluralFormat failed to detect syntax error with pattern: "+checkSyntaxtData[i]);
        }
    }

    // ======= Test applying various pattern
    logln("Testing various patterns");
    status = U_ZERO_ERROR;
    UBool overwrite[PLURAL_PATTERN_DATA] = {FALSE, FALSE, TRUE, TRUE};

    NumberFormat *numFmt = NumberFormat::createInstance(status);
    UnicodeString message=UnicodeString("ERROR: PluralFormat tests various pattern ...");
    if (U_FAILURE(status)) {
        dataerrln("ERROR: Could not create NumberFormat instance with default locale ");
    }
    for(int32_t i=0; i<PLURAL_PATTERN_DATA; ++i) {
        status = U_ZERO_ERROR;
        PluralFormat plFmt=PluralFormat(*plRules, status);
        if (U_FAILURE(status)) {
            dataerrln("ERROR:  PluralFormat constructor failed in unit tests.- exitting");
            return;
        }
        plFmt.applyPattern(patternTestData[i], status);
        if (U_FAILURE(status)) {
            errln("ERROR:  PluralFormat failed to apply pattern- "+patternTestData[i]);
            continue;
        }
        numberFormatTest(&plFmt, numFmt, 1, 10, (UnicodeString *)&patternOddTestResult[i],
                         (UnicodeString *)&patternEvenTestResult[i], overwrite[i], &message);
    }
    delete plRules;
    delete numFmt;

    // ======= Test set locale
    status = U_ZERO_ERROR;
    plRules = PluralRules::createRules(UNICODE_STRING_SIMPLE("odd: n mod 2 is 1"), status);
    PluralFormat pluralFmt = PluralFormat(*plRules, status);
    if (U_FAILURE(status)) {
        dataerrln("ERROR: Could not create PluralFormat instance in setLocale() test - exitting. ");
        delete plRules;
        return;
    }
    pluralFmt.applyPattern(UNICODE_STRING_SIMPLE("odd{odd} other{even}"), status);
    pluralFmt.setLocale(Locale::getEnglish(), status);
    if (U_FAILURE(status)) {
        dataerrln("ERROR: Could not setLocale() with English locale ");
        delete plRules;
        return;
    }
    message = UNICODE_STRING_SIMPLE("Error set locale: pattern is not reset!");

    // Check that pattern gets deleted.
    logln("\n Test setLocale() ..\n");
    numFmt = NumberFormat::createInstance(Locale::getEnglish(), status);
    if (U_FAILURE(status)) {
        dataerrln("ERROR: Could not create NumberFormat instance with English locale ");
    }
    numberFormatTest(&pluralFmt, numFmt, 5, 5, NULL, NULL, FALSE, &message);
    pluralFmt.applyPattern(UNICODE_STRING_SIMPLE("odd__{odd} other{even}"), status);
    if (pluralFmt.format((int32_t)1, status) != UNICODE_STRING_SIMPLE("even")) {
        errln("SetLocale should reset rules but did not.");
    }
    status = U_ZERO_ERROR;
    pluralFmt.applyPattern(UNICODE_STRING_SIMPLE("one{one} other{not one}"), status);
    if (U_FAILURE(status)) {
        errln("SetLocale should reset rules but did not.");
    }
    UnicodeString one = UNICODE_STRING_SIMPLE("one");
    UnicodeString notOne = UNICODE_STRING_SIMPLE("not one");
    UnicodeString plResult, numResult;
    for (int32_t i=0; i<20; ++i) {
        plResult = pluralFmt.format(i, status);
        if ( i==1 ) {
            numResult = one;
        }
        else {
            numResult = notOne;
        }
        if ( numResult != plResult ) {
            errln("Wrong ruleset loaded by setLocale() - got:"+plResult+ UnicodeString("  expecting:")+numResult);
        }
    }

    // =========== Test copy constructor
    logln("Test copy constructor and == operator of PluralFormat");
    PluralFormat dupPFmt = PluralFormat(pluralFmt);
    if (pluralFmt != dupPFmt) {
        errln("Failed in PluralFormat copy constructor or == operator");
    }

    delete plRules;
    delete numFmt;
}

/**
 * Test locale data used in PluralFormat class.
 */
void
PluralFormatTest::pluralFormatLocaleTest(/*char *par*/)
{
    int8_t pluralResults[PLURAL_TEST_ARRAY_SIZE];  // 0: is for default

    // ======= Test DefaultRule
    logln("Testing PluralRules with no rule.");
    // for CLDR 24, here delete tr,
    // add id lo ms th zh
    const char* oneRuleLocales[8] = {"id", "ja", "ko", "lo", "ms", "th", "vi", "zh"};
    UnicodeString testPattern = UNICODE_STRING_SIMPLE("other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER; // other
    helperTestResults(oneRuleLocales, 8, testPattern, pluralResults);

    // ====== Test Singular1 locales.
    logln("Testing singular1 locales.");
    // for CLDR 24, here delete da de en et fi gl he it nl pt pt sv bn ca gu is mr pa sw ur zu
    // add hu tr others
    const char* singular1Locales[56] = {"af","asa","az","bem","bez","bg","brx","chr",
                    "ckb","dv","ee","el","eo","es","eu","fo","fur","fy","gsw","ha",
                    "haw","hu","jgo","ka","kk","kl","ks","ku","lb","ml","mn","nah",
                    "nb","ne","nn","no","nr","om","or","pap","ps","rm","rof","sn",
                    "so", "sq","ta","te","tk","tn","tr","ts","vo","wae","xh","xog"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    pluralResults[2]= PFT_OTHER;
    helperTestResults(singular1Locales, 56, testPattern, pluralResults);

    // ======== Test Singular01 locales.
    logln("Testing singular1 locales.");
    // for CLDR 24, here add hy
    const char* singular01Locales[4] = {"ff","fr","hy","kab"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_ONE;
    pluralResults[2]= PFT_OTHER;
    helperTestResults(singular01Locales, 4, testPattern, pluralResults);

    // ======== Test ZeroSingular locales.
    logln("Testing singular1 locales.");
    const char* zeroSingularLocales[1] = {"lv"};
    testPattern = UNICODE_STRING_SIMPLE("zero{zero} one{one} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_ZERO;
    pluralResults[1]= PFT_ONE;
    for (int32_t i=2; i<20; ++i) {
        pluralResults[i]= (i < 10)? PFT_OTHER: PFT_ZERO;
        pluralResults[i*10] = PFT_ZERO;
        pluralResults[i*10+1] = PFT_ONE; // note override after loop
        pluralResults[i*10+2] = PFT_OTHER; // note override after loop
    }
    pluralResults[111]= PFT_ZERO;
    pluralResults[112]= PFT_ZERO;
    helperTestResults(zeroSingularLocales, 1, testPattern, pluralResults);

    // ======== Test singular dual locales.
    logln("Testing singular1 locales.");
    const char* singularDualLocales[1] = {"ga"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} two{two} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    pluralResults[2]= PFT_TWO;
    pluralResults[3]= PFT_OTHER;
    helperTestResults(singularDualLocales, 1, testPattern, pluralResults);

    // ======== Test Singular Zero Some locales.
    logln("Testing singular1 locales.");
    const char* singularZeroSomeLocales[1] = {"ro"};
    testPattern = UNICODE_STRING_SIMPLE("few{few} one{one} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_FEW;
    for (int32_t i=1; i<20; ++i) {
        pluralResults[i] = PFT_FEW; // note override after loop
        pluralResults[100+i] = PFT_FEW;
    }
    pluralResults[1]= PFT_ONE;
    helperTestResults(singularZeroSomeLocales, 1, testPattern, pluralResults);

    // ======== Test Special 12/19.
    logln("Testing special 12 and 19.");
    const char* special12_19Locales[1] = {"lt"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    for (int32_t i=2; i<20; ++i) {
        pluralResults[i]= (i < 10)? PFT_FEW: PFT_OTHER;
        pluralResults[i*10] = PFT_OTHER;
        if (i==11)  continue;
        pluralResults[i*10+1] = PFT_ONE;
        pluralResults[i*10+2] = PFT_FEW;
    }
    helperTestResults(special12_19Locales, 1, testPattern, pluralResults);

    // ======== Test Paucal Except 11 14.
    logln("Testing Paucal Except 11 and 14, set A.");
    const char* paucal01LocalesA[2] = {"hr","sr"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    for (int32_t i=2; i<20; ++i) {
        pluralResults[i]= (i < 5)? PFT_FEW: PFT_OTHER;
        if (i==11)  continue;
        pluralResults[i*10+1] = PFT_ONE;
        pluralResults[i*10+2] = PFT_FEW;
        pluralResults[i*10+5] = PFT_OTHER;
        pluralResults[i*10+6] = PFT_OTHER;
        pluralResults[i*10+7] = PFT_OTHER;
        pluralResults[i*10+8] = PFT_OTHER;
        pluralResults[i*10+9] = PFT_OTHER;
    }
    helperTestResults(paucal01LocalesA, 2, testPattern, pluralResults);

    logln("Testing Paucal Except 11 and 14, set B.");
    const char* paucal01LocalesB[1] = {"ru"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} many{many} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_MANY;
    pluralResults[1]= PFT_ONE;
    for (int32_t i=2; i<20; ++i) {
        pluralResults[i]= (i < 5)? PFT_OTHER: PFT_MANY;
        if (i==11)  continue;
        pluralResults[i*10] = PFT_MANY;
        pluralResults[i*10+1] = PFT_ONE;
        pluralResults[i*10+2] = PFT_OTHER;
        pluralResults[i*10+5] = PFT_MANY;
        pluralResults[i*10+6] = PFT_MANY;
        pluralResults[i*10+7] = PFT_MANY;
        pluralResults[i*10+8] = PFT_MANY;
        pluralResults[i*10+9] = PFT_MANY;
    }
    helperTestResults(paucal01LocalesB, 1, testPattern, pluralResults);

    logln("Testing Paucal Except 11 and 14, set C.");
    const char* paucal01LocalesC[1] = {"uk"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} many{many} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_MANY;
    pluralResults[1]= PFT_ONE;
    for (int32_t i=2; i<20; ++i) {
        pluralResults[i]= (i < 5)? PFT_FEW: PFT_MANY;
        if (i==11)  continue;
        pluralResults[i*10] = PFT_MANY;
        pluralResults[i*10+1] = PFT_ONE;
        pluralResults[i*10+2] = PFT_FEW;
        pluralResults[i*10+5] = PFT_MANY;
        pluralResults[i*10+6] = PFT_MANY;
        pluralResults[i*10+7] = PFT_MANY;
        pluralResults[i*10+8] = PFT_MANY;
        pluralResults[i*10+9] = PFT_MANY;
    }
    helperTestResults(paucal01LocalesC, 1, testPattern, pluralResults);

    // ======== Test Singular Paucal.
    logln("Testing Singular Paucal.");
    const char* singularPaucalLocales[2] = {"cs","sk"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    pluralResults[2]= PFT_FEW;
    pluralResults[5]= PFT_OTHER;
    helperTestResults(singularPaucalLocales, 2, testPattern, pluralResults);

    // ======== Test Paucal (1), (2,3,4).
    logln("Testing Paucal (1), (2,3,4).");
    const char* paucal02Locales[1] = {"pl"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} many{many} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    for (int32_t i=0; i<20; ++i) {
        pluralResults[i*10+0] = PFT_MANY;
        pluralResults[i*10+1] = PFT_MANY; // note override after loop
        if ((i==1)||(i==11)) {
            pluralResults[i*10+2] = PFT_MANY;
            pluralResults[i*10+3] = PFT_MANY;
            pluralResults[i*10+4] = PFT_MANY;
        }
        else {
            pluralResults[i*10+2] = PFT_FEW;
            pluralResults[i*10+3] = PFT_FEW;
            pluralResults[i*10+4] = PFT_FEW;
        }
        pluralResults[i*10+5] = PFT_MANY;
    }
    pluralResults[1]= PFT_ONE;
    helperTestResults(paucal02Locales, 1, testPattern, pluralResults);

    // ======== Test Paucal (1), (2), (3,4).
    logln("Testing Paucal (1), (2), (3,4).");
    const char* paucal03Locales[1] = {"sl"};
    testPattern = UNICODE_STRING_SIMPLE("one{one} two{two} few{few} other{other}");
    uprv_memset(pluralResults, -1, sizeof(pluralResults));
    pluralResults[0]= PFT_OTHER;
    pluralResults[1]= PFT_ONE;
    pluralResults[2]= PFT_TWO;
    pluralResults[3]= PFT_FEW;
    pluralResults[5]= PFT_OTHER;
    pluralResults[101]= PFT_ONE;
    pluralResults[102]= PFT_TWO;
    pluralResults[103]= PFT_FEW;
    pluralResults[105]= PFT_OTHER;
    helperTestResults(paucal03Locales, 1, testPattern, pluralResults);

    // TODO: move this test to Unit Test after CLDR 1.6 is final and we support float
    // ======= Test French "WITHIN rule
    logln("Testing PluralRules with fr rule.");
    testPattern = UNICODE_STRING_SIMPLE("one{one} other{other}");
    Locale ulocale((const char *)"fr");
    UErrorCode status = U_ZERO_ERROR;
    PluralFormat plFmt(ulocale, testPattern, status);
    if (U_FAILURE(status)) {
        dataerrln("Failed to apply pattern to fr locale - %s", u_errorName(status));
    }
    else {
        status = U_ZERO_ERROR;
        UnicodeString plResult = plFmt.format(0.0, status);  // retrun ONE
        plResult = plFmt.format(0.5, status);  // retrun ONE
        plResult = plFmt.format(1.0, status);  // retrun ONE
        plResult = plFmt.format(1.9, status);  // retrun ONE
        plResult = plFmt.format(2.0, status);  // retrun OTHER
    }
}

void
PluralFormatTest::pluralFormatExtendedTest(void) {
  const char *targets[] = {
    "There are no widgets.",
    "There is one widget.",
    "There is a bling widget and one other widget.",
    "There is a bling widget and 2 other widgets.",
    "There is a bling widget and 3 other widgets.",
    "Widgets, five (5-1=4) there be.",
    "There is a bling widget and 5 other widgets.",
    "There is a bling widget and 6 other widgets.",
  };

  const char* fmt =
      "offset:1.0 "
      "=0 {There are no widgets.} "
      "=1.0 {There is one widget.} "
      "=5 {Widgets, five (5-1=#) there be.} "
      "one {There is a bling widget and one other widget.} "
      "other {There is a bling widget and # other widgets.}";

  UErrorCode status = U_ZERO_ERROR;
  UnicodeString fmtString(fmt, -1, US_INV);
  PluralFormat pf(Locale::getEnglish(), fmtString, status);
  MessageFormat mf(UNICODE_STRING_SIMPLE("{0,plural,").append(fmtString).append((UChar)0x7d /* '}' */),
                   Locale::getEnglish(), status);
  Formattable args;
  FieldPosition ignore;
  if (U_FAILURE(status)) {
    dataerrln("Failed to apply pattern - %s", u_errorName(status));
    return;
  }
  for (int32_t i = 0; i <= 7; ++i) {
    UnicodeString result = pf.format(i, status);
    if (U_FAILURE(status)) {
      errln("PluralFormat.format(value %d) failed - %s", i, u_errorName(status));
      return;
    }
    UnicodeString expected(targets[i], -1, US_INV);
    if (expected != result) {
      UnicodeString message("PluralFormat.format(): Expected '", -1, US_INV);
      message.append(expected);
      message.append(UnicodeString("' but got '", -1, US_INV));
      message.append(result);
      message.append("'", -1, US_INV);
      errln(message);
    }
    args.setLong(i);
    mf.format(&args, 1, result.remove(), ignore, status);
    if (U_FAILURE(status)) {
      errln("MessageFormat.format(value %d) failed - %s", i, u_errorName(status));
      return;
    }
    if (expected != result) {
      UnicodeString message("MessageFormat.format(): Expected '", -1, US_INV);
      message.append(expected);
      message.append(UnicodeString("' but got '", -1, US_INV));
      message.append(result);
      message.append("'", -1, US_INV);
      errln(message);
    }
  }
}

void
PluralFormatTest::pluralFormatExtendedParseTest(void) {
  const char *failures[] = {
    "offset:1..0 =0 {Foo}",
    "offset:1.0 {Foo}",
    "=0= {Foo}",
    "=0 {Foo} =0.0 {Bar}",
    " = {Foo}",
  };
  int len = UPRV_LENGTHOF(failures);

  for (int i = 0; i < len; ++i) {
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString fmt(failures[i], -1, US_INV);
    PluralFormat pf(fmt, status);
    if (U_SUCCESS(status)) {
      errln("expected failure when parsing '" + fmt + "'");
    }
  }
}

void
PluralFormatTest::ordinalFormatTest(void) {
    IcuTestErrorCode errorCode(*this, "ordinalFormatTest");
    UnicodeString pattern("one{#st file}two{#nd file}few{#rd file}other{#th file}");
    PluralFormat pf(Locale::getEnglish(), UPLURAL_TYPE_ORDINAL, pattern, errorCode);
    if (errorCode.logDataIfFailureAndReset("PluralFormat(en, UPLURAL_TYPE_ORDINAL, pattern) failed")) {
      return;
    }
    UnicodeString result = pf.format((int32_t)321, errorCode);
    if (!errorCode.logIfFailureAndReset("PluralFormat.format(321) failed") &&
        result != UNICODE_STRING_SIMPLE("321st file")) {
      errln(UnicodeString("PluralFormat.format(321) wrong result string: ") + result);
    }
    result = pf.format((int32_t)22, errorCode);
    if (!errorCode.logIfFailureAndReset("PluralFormat.format(22) failed") &&
        result != UNICODE_STRING_SIMPLE("22nd file")) {
      errln(UnicodeString("PluralFormat.format(22) wrong result string: ") + result);
    }
    result = pf.format((int32_t)3, errorCode);
    if (!errorCode.logIfFailureAndReset("PluralFormat.format(3) failed") &&
        result != UNICODE_STRING_SIMPLE("3rd file")) {
      errln(UnicodeString("PluralFormat.format(3) wrong result string: ") + result);
    }

    // Code coverage: Use the other new-for-UPluralType constructor as well.
    PluralFormat pf2(Locale::getEnglish(), UPLURAL_TYPE_ORDINAL, errorCode);
    pf2.applyPattern(pattern, errorCode);
    if (errorCode.logIfFailureAndReset("PluralFormat(en, UPLURAL_TYPE_ORDINAL, pattern) failed")) {
      return;
    }
    result = pf2.format((int32_t)456, errorCode);
    if (!errorCode.logIfFailureAndReset("PluralFormat.format(456) failed") &&
        result != UNICODE_STRING_SIMPLE("456th file")) {
      errln(UnicodeString("PluralFormat.format(456) wrong result string: ") + result);
    }
    result = pf2.format((int32_t)111, errorCode);
    if (!errorCode.logIfFailureAndReset("PluralFormat.format(111) failed") &&
        result != UNICODE_STRING_SIMPLE("111th file")) {
      errln(UnicodeString("PluralFormat.format(111) wrong result string: ") + result);
    }
}

void
PluralFormatTest::TestDecimals() {
    IcuTestErrorCode errorCode(*this, "TestDecimals");
    // Simple number replacement.
    PluralFormat pf(Locale::getEnglish(), "one{one meter}other{# meters}", errorCode);
    assertEquals("simple format(1)", "one meter", pf.format((int32_t)1, errorCode), TRUE);
    assertEquals("simple format(1.5)", "1.5 meters", pf.format(1.5, errorCode), TRUE);
    PluralFormat pf2(Locale::getEnglish(),
            "offset:1 one{another meter}other{another # meters}", errorCode);
    DecimalFormat df("0.0", new DecimalFormatSymbols(Locale::getEnglish(), errorCode), errorCode);
    pf2.setNumberFormat(&df, errorCode);
    assertEquals("offset-decimals format(1)", "another 0.0 meters", pf2.format((int32_t)1, errorCode), TRUE);
    assertEquals("offset-decimals format(2)", "another 1.0 meters", pf2.format((int32_t)2, errorCode), TRUE);
    assertEquals("offset-decimals format(2.5)", "another 1.5 meters", pf2.format(2.5, errorCode), TRUE);
    errorCode.reset();
}

void
PluralFormatTest::numberFormatTest(PluralFormat* plFmt,
                                   NumberFormat *numFmt,
                                   int32_t start,
                                   int32_t end,
                                   UnicodeString *numOddAppendStr,
                                   UnicodeString *numEvenAppendStr,
                                   UBool overwrite,  // overwrite the numberFormat.format result
                                   UnicodeString *message) {
    UErrorCode status = U_ZERO_ERROR;

    if ( (plFmt==NULL) || (numFmt==NULL) ) {
        dataerrln("ERROR: Could not create PluralFormat or NumberFormat - exitting");
        return;
    }
    UnicodeString plResult, numResult ;

    for (int32_t i=start; i<= end; ++i ) {
        numResult.remove();
        numResult = numFmt->format(i, numResult);
        plResult = plFmt->format(i, status);
        if ((numOddAppendStr!= NULL)&&(numEvenAppendStr!=NULL)) {
            if (overwrite) {
                if (i&1) {
                    numResult = *numOddAppendStr;
                }
                else {
                    numResult = *numEvenAppendStr;
                }
            }
            else {  // Append the string
                if (i&1) {
                    numResult += *numOddAppendStr;
                }
                else{
                    numResult += *numEvenAppendStr;
                }
            }
        }
        if ( (numResult!=plResult) || U_FAILURE(status) ) {
            if ( message == NULL ) {
                errln("ERROR: Unexpected plural format - got:"+plResult+ UnicodeString("  expecting:")+numResult);
            }
            else {
                errln( *message+UnicodeString("  got:")+plResult+UnicodeString("  expecting:")+numResult);
            }
        }
    }
    return;
}

void
PluralFormatTest::helperTestResults(const char** localeArray,
                                    int32_t capacityOfArray,
                                    UnicodeString& testPattern,
                                    int8_t *expResults) {
    UErrorCode status;
    UnicodeString plResult;
    const UnicodeString PLKeywordLookups[6] = {
        UNICODE_STRING_SIMPLE("zero"),
        UNICODE_STRING_SIMPLE("one"),
        UNICODE_STRING_SIMPLE("two"),
        UNICODE_STRING_SIMPLE("few"),
        UNICODE_STRING_SIMPLE("many"),
        UNICODE_STRING_SIMPLE("other"),
    };

    for (int32_t i=0; i<capacityOfArray; ++i) {
        const char *locale = localeArray[i];
        Locale ulocale((const char *)locale);
        status = U_ZERO_ERROR;
        PluralFormat plFmt(ulocale, testPattern, status);
        if (U_FAILURE(status)) {
            dataerrln("Failed to apply pattern to locale:"+UnicodeString(localeArray[i]) + " - " + u_errorName(status));
            continue;
        }
        for (int32_t n=0; n<PLURAL_TEST_ARRAY_SIZE; ++n) {
            if (expResults[n]!=-1) {
                status = U_ZERO_ERROR;
                plResult = plFmt.format(n, status);
                if (U_FAILURE(status)) {
                    errln("ERROR: Failed to format number in locale data tests with locale: "+
                           UnicodeString(localeArray[i]));
                }
                if (plResult != PLKeywordLookups[expResults[n]]){
                    plResult = plFmt.format(n, status);
                    errln("ERROR: Unexpected format result in locale: "+UnicodeString(localeArray[i])+
                          UnicodeString(" for value: ")+n+
                          UnicodeString("  got:")+plResult+
                          UnicodeString("  expecting:")+ PLKeywordLookups[expResults[n]]);
                }
            }
        }
    }
}

#endif /* #if !UCONFIG_NO_FORMATTING */


text:
// Copyright © 2004-2005 ASERT. Released under the Canoo Webtest license.
package com.canoo.webtest.extension.dialogs;

import com.canoo.webtest.engine.StepFailedException;
import com.canoo.webtest.steps.Step;
import org.apache.log4j.Logger;

/**
 * Check that all expected dialogs have been 'consumed' by JavaScript.<p>
 *
 * @author Paul King
 * @webtest.step category="Extension"
 * name="verifyNoDialogs"
 * alias="verifyNoDialogResponses"
 * description="Used in conjunction with the <stepref name='expectDialog' category='Extension'/> and <stepref name='expectDialogs' category='Extension'/> steps when dealing with <key>javascript</key> Dialog boxes. This step checks that all user responses expected were in fact \"consumed\" by <key>javascript</key>."
 */
public class VerifyNoDialogs extends Step {
    private static final Logger LOG = Logger.getLogger(VerifyNoDialogs.class);

    public void doExecute() {
        final int count = DialogHelper.getExpectedDialogsCount(getContext());
        LOG.debug("Number of expected dialogs = " + count);
        if (count > 0) {
            throw new StepFailedException("Dialogs found but none expected!", this);
        }
    }

}


text:
namespace chrono {
namespace vehicle {
namespace hmmwv {

/// @addtogroup vehicle_models_hmmwv
/// @{

/// HMMWV wheel (can be used on any axle, left or right).
class CH_MODELS_API HMMWV_Wheel : public ChWheel {
  public:
    HMMWV_Wheel(const std::string& name);
    ~HMMWV_Wheel() {}

    virtual double GetWheelMass() const override { return m_mass; }
    virtual const ChVector<>& GetWheelInertia() const override { return m_inertia; }
    virtual double GetRadius() const override { return m_radius; }
    virtual double GetWidth() const override { return m_width; }

  protected:
    static const double m_radius;
    static const double m_width;
    static const double m_mass;
    static const ChVector<> m_inertia;
};

/// @} vehicle_models_hmmwv

}  // end namespace hmmwv
}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
using namespace std;

// Size of the framebuffer
const unsigned int SIZE = 512;

// A simple RGB struct will represent a pixel in the framebuffer
// Note: each channel is range <0, 255>
//       uint8_t or char would be signed so the range would be <-128, 127>
struct Pixel {
  uint8_t r,g,b;
};

int main() {
  // Initialize a framebuffer
  // NOTE: The framebuffer is allocated on the heap and needs to be freed manually.
  // Allocating on the stack may cause stack overflow depending on the size of the image.
  auto framebuffer = new Pixel[SIZE][SIZE];

  // Example: Generate a simple gradient
  for (unsigned int x = 0; x < SIZE; ++x) {
    for (unsigned int y = 0; y < SIZE; ++y) {
      framebuffer[x][y].r = (uint8_t)(x / 2);
      framebuffer[x][y].g = (uint8_t)(y / 2);
      framebuffer[x][y].b = 0;
    }
  }

  // Task1: Load RAW image file here instead

  // save the raw image to a file
  cout << "Generating result.raw file ..." << endl;
  ofstream raw("raw1_gradient.raw", ios::binary);
  raw.write(reinterpret_cast<char *>(framebuffer), sizeof(Pixel)*SIZE*SIZE);
  raw.close();

  delete[](framebuffer);

  cout << "Done." << endl;
  return EXIT_SUCCESS;
}


text:
from openerp.osv import fields, osv
from openerp.tools.translate import _

class account_move_line_reconcile_select(osv.osv_memory):
    _name = "account.move.line.reconcile.select"
    _description = "Move line reconcile select"
    _columns = {
       'account_id': fields.many2one('account.account', 'Account', \
                            domain = [('reconcile', '=', 1)], required=True),
    }

    def action_open_window(self, cr, uid, ids, context=None):
        """
        This function Open  account move line window for reconcile on given account id
        @param cr: the current row, from the database cursor,
        @param uid: the current user's ID for security checks,
        @param ids: account move line reconcile select's ID or list of IDs
        @return: dictionary of  Open  account move line window for reconcile on given account id

         """
        data = self.read(cr, uid, ids, context=context)[0]
        return {
            'domain': "[('account_id','=',%d),('reconcile_id','=',False),('state','<>','draft')]" % data['account_id'],
            'name': _('Reconciliation'),
            'view_type': 'form',
            'view_mode': 'tree,form',
            'view_id': False,
            'res_model': 'account.move.line',
            'type': 'ir.actions.act_window'
        }

account_move_line_reconcile_select()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class MakeIdColumnAutoIncrementInAlbumsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('albums', function (Blueprint $table) {
            $table->increments('id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('albums', function (Blueprint $table) {

        });
    }
}


text:
'use strict';

module.exports = require('export-files')(__dirname);

/**
 * Load the project environment. Starting with
 * package.json and .gitignore.
 */

// module.exports = function(app) {
//   app.transform('env env', env.env);
//   app.transform('env ignore', env.ignore);
//   app.transform('env files', env.files);
//   app.transform('env keys', env.keys);
//   app.transform('env github', env.github);
//   app.transform('env travis', env.travis);
//   app.transform('env user', env.user);
//   app.transform('env author', env.author);
//   app.transform('env username', env.username);
//   app.transform('env license', env.license);
//   app.transform('env licenses', env.licenses);
// };


text:
package com.aspectran.core.component.bean.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Dispatch {

    String value() default "";

    String name() default "";

    String dispatcher() default "";

    String contentType() default "";

    String encoding() default "";

}


text:
package com.evolveum.midpoint.prism.match;

/**
 * Creates MatchingRuleRegistry populated with standard matching rules.
 *
 * @author Radovan Semancik
 *
 */
public class MatchingRuleRegistryFactory {

	public static MatchingRuleRegistry createRegistry() {

		MatchingRuleRegistry registry = new MatchingRuleRegistry();
		registry.registerMatchingRule(new StringIgnoreCaseMatchingRule());
		registry.registerMatchingRule(new PolyStringStrictMatchingRule());
		registry.registerMatchingRule(new PolyStringOrigMatchingRule());
		registry.registerMatchingRule(new PolyStringNormMatchingRule());

		return registry;
	}

}