text:
import io
import marshal
import os
import sys
from test import support
from test.support import import_helper
import types
import unittest
from unittest import mock
import warnings

from test.test_importlib import util as test_util

init = test_util.import_importlib('importlib')
abc = test_util.import_importlib('importlib.abc')
machinery = test_util.import_importlib('importlib.machinery')
util = test_util.import_importlib('importlib.util')

##### Inheritance ##############################################################
class InheritanceTests:

    """Test that the specified class is a subclass/superclass of the expected
    classes."""

    subclasses = []
    superclasses = []

    def setUp(self):
        self.superclasses = [getattr(self.abc, class_name)
                             for class_name in self.superclass_names]
        if hasattr(self, 'subclass_names'):
            # Because test.support.import_fresh_module() creates a new
            # importlib._bootstrap per module, inheritance checks fail when
            # checking across module boundaries (i.e. the _bootstrap in abc is
            # not the same as the one in machinery). That means stealing one of
            # the modules from the other to make sure the same instance is used.
            machinery = self.abc.machinery
            self.subclasses = [getattr(machinery, class_name)
                               for class_name in self.subclass_names]
        assert self.subclasses or self.superclasses, self.__class__
        self.__test = getattr(self.abc, self._NAME)

    def test_subclasses(self):
        # Test that the expected subclasses inherit.
        for subclass in self.subclasses:
            self.assertTrue(issubclass(subclass, self.__test),
                "{0} is not a subclass of {1}".format(subclass, self.__test))

    def test_superclasses(self):
        # Test that the class inherits from the expected superclasses.
        for superclass in self.superclasses:
            self.assertTrue(issubclass(self.__test, superclass),
               "{0} is not a superclass of {1}".format(superclass, self.__test))

class MetaPathFinder(InheritanceTests):
    superclass_names = []
    subclass_names = ['BuiltinImporter', 'FrozenImporter', 'PathFinder',
                      'WindowsRegistryFinder']

(Frozen_MetaPathFinderInheritanceTests,
 Source_MetaPathFinderInheritanceTests
 ) = test_util.test_both(MetaPathFinder, abc=abc)

class PathEntryFinder(InheritanceTests):
    superclass_names = []
    subclass_names = ['FileFinder']

(Frozen_PathEntryFinderInheritanceTests,
 Source_PathEntryFinderInheritanceTests
 ) = test_util.test_both(PathEntryFinder, abc=abc)

class ResourceLoader(InheritanceTests):
    superclass_names = ['Loader']

(Frozen_ResourceLoaderInheritanceTests,
 Source_ResourceLoaderInheritanceTests
 ) = test_util.test_both(ResourceLoader, abc=abc)

class InspectLoader(InheritanceTests):
    superclass_names = ['Loader']
    subclass_names = ['BuiltinImporter', 'FrozenImporter', 'ExtensionFileLoader']

(Frozen_InspectLoaderInheritanceTests,
 Source_InspectLoaderInheritanceTests
 ) = test_util.test_both(InspectLoader, abc=abc)

class ExecutionLoader(InheritanceTests):
    superclass_names = ['InspectLoader']
    subclass_names = ['ExtensionFileLoader']

(Frozen_ExecutionLoaderInheritanceTests,
 Source_ExecutionLoaderInheritanceTests
 ) = test_util.test_both(ExecutionLoader, abc=abc)

class FileLoader(InheritanceTests):
    superclass_names = ['ResourceLoader', 'ExecutionLoader']
    subclass_names = ['SourceFileLoader', 'SourcelessFileLoader']

(Frozen_FileLoaderInheritanceTests,
 Source_FileLoaderInheritanceTests
 ) = test_util.test_both(FileLoader, abc=abc)

class SourceLoader(InheritanceTests):
    superclass_names = ['ResourceLoader', 'ExecutionLoader']
    subclass_names = ['SourceFileLoader']

(Frozen_SourceLoaderInheritanceTests,
 Source_SourceLoaderInheritanceTests
 ) = test_util.test_both(SourceLoader, abc=abc)

##### Default return values ####################################################

def make_abc_subclasses(base_class, name=None, inst=False, **kwargs):
    if name is None:
        name = base_class.__name__
    base = {kind: getattr(splitabc, name)
            for kind, splitabc in abc.items()}
    return {cls._KIND: cls() if inst else cls
            for cls in test_util.split_frozen(base_class, base, **kwargs)}

class ABCTestHarness:

    @property
    def ins(self):
        # Lazily set ins on the class.
        cls = self.SPLIT[self._KIND]
        ins = cls()
        self.__class__.ins = ins
        return ins

class MetaPathFinder:

    def find_module(self, fullname, path):
        return super().find_module(fullname, path)

class MetaPathFinderDefaultsTests(ABCTestHarness):

    SPLIT = make_abc_subclasses(MetaPathFinder)

    def test_find_module(self):
        # Default should return None.
        with self.assertWarns(DeprecationWarning):
            found = self.ins.find_module('something', None)
        self.assertIsNone(found)

    def test_invalidate_caches(self):
        # Calling the method is a no-op.
        self.ins.invalidate_caches()

(Frozen_MPFDefaultTests,
 Source_MPFDefaultTests
 ) = test_util.test_both(MetaPathFinderDefaultsTests)

class PathEntryFinder:

    def find_loader(self, fullname):
        return super().find_loader(fullname)

class PathEntryFinderDefaultsTests(ABCTestHarness):

    SPLIT = make_abc_subclasses(PathEntryFinder)

    def test_find_loader(self):
        with self.assertWarns(DeprecationWarning):
            found = self.ins.find_loader('something')
        self.assertEqual(found, (None, []))

    def find_module(self):
        self.assertEqual(None, self.ins.find_module('something'))

    def test_invalidate_caches(self):
        # Should be a no-op.
        self.ins.invalidate_caches()

(Frozen_PEFDefaultTests,
 Source_PEFDefaultTests
 ) = test_util.test_both(PathEntryFinderDefaultsTests)

class Loader:

    def load_module(self, fullname):
        return super().load_module(fullname)

class LoaderDefaultsTests(ABCTestHarness):

    SPLIT = make_abc_subclasses(Loader)

    def test_create_module(self):
        spec = 'a spec'
        self.assertIsNone(self.ins.create_module(spec))

    def test_load_module(self):
        with self.assertRaises(ImportError):
            self.ins.load_module('something')

    def test_module_repr(self):
        mod = types.ModuleType('blah')
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            with self.assertRaises(NotImplementedError):
                self.ins.module_repr(mod)
            original_repr = repr(mod)
            mod.__loader__ = self.ins
            # Should still return a proper repr.
            self.assertTrue(repr(mod))

(Frozen_LDefaultTests,
 SourceLDefaultTests
 ) = test_util.test_both(LoaderDefaultsTests)

class ResourceLoader(Loader):

    def get_data(self, path):
        return super().get_data(path)

class ResourceLoaderDefaultsTests(ABCTestHarness):

    SPLIT = make_abc_subclasses(ResourceLoader)

    def test_get_data(self):
        with self.assertRaises(IOError):
            self.ins.get_data('/some/path')

(Frozen_RLDefaultTests,
 Source_RLDefaultTests
 ) = test_util.test_both(ResourceLoaderDefaultsTests)

class InspectLoader(Loader):

    def is_package(self, fullname):
        return super().is_package(fullname)

    def get_source(self, fullname):
        return super().get_source(fullname)

SPLIT_IL = make_abc_subclasses(InspectLoader)

class InspectLoaderDefaultsTests(ABCTestHarness):

    SPLIT = SPLIT_IL

    def test_is_package(self):
        with self.assertRaises(ImportError):
            self.ins.is_package('blah')

    def test_get_source(self):
        with self.assertRaises(ImportError):
            self.ins.get_source('blah')

(Frozen_ILDefaultTests,
 Source_ILDefaultTests
 ) = test_util.test_both(InspectLoaderDefaultsTests)

class ExecutionLoader(InspectLoader):

    def get_filename(self, fullname):
        return super().get_filename(fullname)

SPLIT_EL = make_abc_subclasses(ExecutionLoader)

class ExecutionLoaderDefaultsTests(ABCTestHarness):

    SPLIT = SPLIT_EL

    def test_get_filename(self):
        with self.assertRaises(ImportError):
            self.ins.get_filename('blah')

(Frozen_ELDefaultTests,
 Source_ELDefaultsTests
 ) = test_util.test_both(InspectLoaderDefaultsTests)

class ResourceReader:

    def open_resource(self, *args, **kwargs):
        return super().open_resource(*args, **kwargs)

    def resource_path(self, *args, **kwargs):
        return super().resource_path(*args, **kwargs)

    def is_resource(self, *args, **kwargs):
        return super().is_resource(*args, **kwargs)

    def contents(self, *args, **kwargs):
        return super().contents(*args, **kwargs)

class ResourceReaderDefaultsTests(ABCTestHarness):

    SPLIT = make_abc_subclasses(ResourceReader)

    def test_open_resource(self):
        with self.assertRaises(FileNotFoundError):
            self.ins.open_resource('dummy_file')

    def test_resource_path(self):
        with self.assertRaises(FileNotFoundError):
            self.ins.resource_path('dummy_file')

    def test_is_resource(self):
        with self.assertRaises(FileNotFoundError):
            self.ins.is_resource('dummy_file')

    def test_contents(self):
        with self.assertRaises(FileNotFoundError):
            self.ins.contents()

(Frozen_RRDefaultTests,
 Source_RRDefaultsTests
 ) = test_util.test_both(ResourceReaderDefaultsTests)

##### MetaPathFinder concrete methods ##########################################
class MetaPathFinderFindModuleTests:

    @classmethod
    def finder(cls, spec):
        class MetaPathSpecFinder(cls.abc.MetaPathFinder):

            def find_spec(self, fullname, path, target=None):
                self.called_for = fullname, path
                return spec

        return MetaPathSpecFinder()

    def test_find_module(self):
        finder = self.finder(None)
        path = ['a', 'b', 'c']
        name = 'blah'
        with self.assertWarns(DeprecationWarning):
            found = finder.find_module(name, path)
        self.assertIsNone(found)

    def test_find_spec_with_explicit_target(self):
        loader = object()
        spec = self.util.spec_from_loader('blah', loader)
        finder = self.finder(spec)
        found = finder.find_spec('blah', 'blah', None)
        self.assertEqual(found, spec)

    def test_no_spec(self):
        finder = self.finder(None)
        path = ['a', 'b', 'c']
        name = 'blah'
        found = finder.find_spec(name, path, None)
        self.assertIsNone(found)
        self.assertEqual(name, finder.called_for[0])
        self.assertEqual(path, finder.called_for[1])

    def test_spec(self):
        loader = object()
        spec = self.util.spec_from_loader('blah', loader)
        finder = self.finder(spec)
        found = finder.find_spec('blah', None)
        self.assertIs(found, spec)

(Frozen_MPFFindModuleTests,
 Source_MPFFindModuleTests
 ) = test_util.test_both(MetaPathFinderFindModuleTests, abc=abc, util=util)

##### PathEntryFinder concrete methods #########################################
class PathEntryFinderFindLoaderTests:

    @classmethod
    def finder(cls, spec):
        class PathEntrySpecFinder(cls.abc.PathEntryFinder):

            def find_spec(self, fullname, target=None):
                self.called_for = fullname
                return spec

        return PathEntrySpecFinder()

    def test_no_spec(self):
        finder = self.finder(None)
        name = 'blah'
        with self.assertWarns(DeprecationWarning):
            found = finder.find_loader(name)
        self.assertIsNone(found[0])
        self.assertEqual([], found[1])
        self.assertEqual(name, finder.called_for)

    def test_spec_with_loader(self):
        loader = object()
        spec = self.util.spec_from_loader('blah', loader)
        finder = self.finder(spec)
        with self.assertWarns(DeprecationWarning):
            found = finder.find_loader('blah')
        self.assertIs(found[0], spec.loader)

    def test_spec_with_portions(self):
        spec = self.machinery.ModuleSpec('blah', None)
        paths = ['a', 'b', 'c']
        spec.submodule_search_locations = paths
        finder = self.finder(spec)
        with self.assertWarns(DeprecationWarning):
            found = finder.find_loader('blah')
        self.assertIsNone(found[0])
        self.assertEqual(paths, found[1])

(Frozen_PEFFindLoaderTests,
 Source_PEFFindLoaderTests
 ) = test_util.test_both(PathEntryFinderFindLoaderTests, abc=abc, util=util,
                         machinery=machinery)

##### Loader concrete methods ##################################################
class LoaderLoadModuleTests:

    def loader(self):
        class SpecLoader(self.abc.Loader):
            found = None
            def exec_module(self, module):
                self.found = module

            def is_package(self, fullname):
                """Force some non-default module state to be set."""
                return True

        return SpecLoader()

    def test_fresh(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            loader = self.loader()
            name = 'blah'
            with test_util.uncache(name):
                loader.load_module(name)
                module = loader.found
                self.assertIs(sys.modules[name], module)
            self.assertEqual(loader, module.__loader__)
            self.assertEqual(loader, module.__spec__.loader)
            self.assertEqual(name, module.__name__)
            self.assertEqual(name, module.__spec__.name)
            self.assertIsNotNone(module.__path__)
            self.assertIsNotNone(module.__path__,
                                module.__spec__.submodule_search_locations)

    def test_reload(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            name = 'blah'
            loader = self.loader()
            module = types.ModuleType(name)
            module.__spec__ = self.util.spec_from_loader(name, loader)
            module.__loader__ = loader
            with test_util.uncache(name):
                sys.modules[name] = module
                loader.load_module(name)
                found = loader.found
                self.assertIs(found, sys.modules[name])
                self.assertIs(module, sys.modules[name])

(Frozen_LoaderLoadModuleTests,
 Source_LoaderLoadModuleTests
 ) = test_util.test_both(LoaderLoadModuleTests, abc=abc, util=util)

##### InspectLoader concrete methods ###########################################
class InspectLoaderSourceToCodeTests:

    def source_to_module(self, data, path=None):
        """Help with source_to_code() tests."""
        module = types.ModuleType('blah')
        loader = self.InspectLoaderSubclass()
        if path is None:
            code = loader.source_to_code(data)
        else:
            code = loader.source_to_code(data, path)
        exec(code, module.__dict__)
        return module

    def test_source_to_code_source(self):
        # Since compile() can handle strings, so should source_to_code().
        source = 'attr = 42'
        module = self.source_to_module(source)
        self.assertTrue(hasattr(module, 'attr'))
        self.assertEqual(module.attr, 42)

    def test_source_to_code_bytes(self):
        # Since compile() can handle bytes, so should source_to_code().
        source = b'attr = 42'
        module = self.source_to_module(source)
        self.assertTrue(hasattr(module, 'attr'))
        self.assertEqual(module.attr, 42)

    def test_source_to_code_path(self):
        # Specifying a path should set it for the code object.
        path = 'path/to/somewhere'
        loader = self.InspectLoaderSubclass()
        code = loader.source_to_code('', path)
        self.assertEqual(code.co_filename, path)

    def test_source_to_code_no_path(self):
        # Not setting a path should still work and be set to <string> since that
        # is a pre-existing practice as a default to compile().
        loader = self.InspectLoaderSubclass()
        code = loader.source_to_code('')
        self.assertEqual(code.co_filename, '<string>')

(Frozen_ILSourceToCodeTests,
 Source_ILSourceToCodeTests
 ) = test_util.test_both(InspectLoaderSourceToCodeTests,
                         InspectLoaderSubclass=SPLIT_IL)

class InspectLoaderGetCodeTests:

    def test_get_code(self):
        # Test success.
        module = types.ModuleType('blah')
        with mock.patch.object(self.InspectLoaderSubclass, 'get_source') as mocked:
            mocked.return_value = 'attr = 42'
            loader = self.InspectLoaderSubclass()
            code = loader.get_code('blah')
        exec(code, module.__dict__)
        self.assertEqual(module.attr, 42)

    def test_get_code_source_is_None(self):
        # If get_source() is None then this should be None.
        with mock.patch.object(self.InspectLoaderSubclass, 'get_source') as mocked:
            mocked.return_value = None
            loader = self.InspectLoaderSubclass()
            code = loader.get_code('blah')
        self.assertIsNone(code)

    def test_get_code_source_not_found(self):
        # If there is no source then there is no code object.
        loader = self.InspectLoaderSubclass()
        with self.assertRaises(ImportError):
            loader.get_code('blah')

(Frozen_ILGetCodeTests,
 Source_ILGetCodeTests
 ) = test_util.test_both(InspectLoaderGetCodeTests,
                         InspectLoaderSubclass=SPLIT_IL)

class InspectLoaderLoadModuleTests:

    """Test InspectLoader.load_module()."""

    module_name = 'blah'

    def setUp(self):
        import_helper.unload(self.module_name)
        self.addCleanup(import_helper.unload, self.module_name)

    def load(self, loader):
        spec = self.util.spec_from_loader(self.module_name, loader)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', DeprecationWarning)
            return self.init._bootstrap._load_unlocked(spec)

    def mock_get_code(self):
        return mock.patch.object(self.InspectLoaderSubclass, 'get_code')

    def test_get_code_ImportError(self):
        # If get_code() raises ImportError, it should propagate.
        with self.mock_get_code() as mocked_get_code:
            mocked_get_code.side_effect = ImportError
            with self.assertRaises(ImportError):
                loader = self.InspectLoaderSubclass()
                self.load(loader)

    def test_get_code_None(self):
        # If get_code() returns None, raise ImportError.
        with self.mock_get_code() as mocked_get_code:
            mocked_get_code.return_value = None
            with self.assertRaises(ImportError):
                loader = self.InspectLoaderSubclass()
                self.load(loader)

    def test_module_returned(self):
        # The loaded module should be returned.
        code = compile('attr = 42', '<string>', 'exec')
        with self.mock_get_code() as mocked_get_code:
            mocked_get_code.return_value = code
            loader = self.InspectLoaderSubclass()
            module = self.load(loader)
            self.assertEqual(module, sys.modules[self.module_name])

(Frozen_ILLoadModuleTests,
 Source_ILLoadModuleTests
 ) = test_util.test_both(InspectLoaderLoadModuleTests,
                         InspectLoaderSubclass=SPLIT_IL,
                         init=init,
                         util=util)

##### ExecutionLoader concrete methods #########################################
class ExecutionLoaderGetCodeTests:

    def mock_methods(self, *, get_source=False, get_filename=False):
        source_mock_context, filename_mock_context = None, None
        if get_source:
            source_mock_context = mock.patch.object(self.ExecutionLoaderSubclass,
                                                    'get_source')
        if get_filename:
            filename_mock_context = mock.patch.object(self.ExecutionLoaderSubclass,
                                                      'get_filename')
        return source_mock_context, filename_mock_context

    def test_get_code(self):
        path = 'blah.py'
        source_mock_context, filename_mock_context = self.mock_methods(
                get_source=True, get_filename=True)
        with source_mock_context as source_mock, filename_mock_context as name_mock:
            source_mock.return_value = 'attr = 42'
            name_mock.return_value = path
            loader = self.ExecutionLoaderSubclass()
            code = loader.get_code('blah')
        self.assertEqual(code.co_filename, path)
        module = types.ModuleType('blah')
        exec(code, module.__dict__)
        self.assertEqual(module.attr, 42)

    def test_get_code_source_is_None(self):
        # If get_source() is None then this should be None.
        source_mock_context, _ = self.mock_methods(get_source=True)
        with source_mock_context as mocked:
            mocked.return_value = None
            loader = self.ExecutionLoaderSubclass()
            code = loader.get_code('blah')
        self.assertIsNone(code)

    def test_get_code_source_not_found(self):
        # If there is no source then there is no code object.
        loader = self.ExecutionLoaderSubclass()
        with self.assertRaises(ImportError):
            loader.get_code('blah')

    def test_get_code_no_path(self):
        # If get_filename() raises ImportError then simply skip setting the path
        # on the code object.
        source_mock_context, filename_mock_context = self.mock_methods(
                get_source=True, get_filename=True)
        with source_mock_context as source_mock, filename_mock_context as name_mock:
            source_mock.return_value = 'attr = 42'
            name_mock.side_effect = ImportError
            loader = self.ExecutionLoaderSubclass()
            code = loader.get_code('blah')
        self.assertEqual(code.co_filename, '<string>')
        module = types.ModuleType('blah')
        exec(code, module.__dict__)
        self.assertEqual(module.attr, 42)

(Frozen_ELGetCodeTests,
 Source_ELGetCodeTests
 ) = test_util.test_both(ExecutionLoaderGetCodeTests,
                         ExecutionLoaderSubclass=SPLIT_EL)

##### SourceLoader concrete methods ############################################
class SourceOnlyLoader:

    # Globals that should be defined for all modules.
    source = (b"_ = '::'.join([__name__, __file__, __cached__, __package__, "
              b"repr(__loader__)])")

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

    def get_data(self, path):
        if path != self.path:
            raise IOError
        return self.source

    def get_filename(self, fullname):
        return self.path

    def module_repr(self, module):
        return '<module>'

SPLIT_SOL = make_abc_subclasses(SourceOnlyLoader, 'SourceLoader')

class SourceLoader(SourceOnlyLoader):

    source_mtime = 1

    def __init__(self, path, magic=None):
        super().__init__(path)
        self.bytecode_path = self.util.cache_from_source(self.path)
        self.source_size = len(self.source)
        if magic is None:
            magic = self.util.MAGIC_NUMBER
        data = bytearray(magic)
        data.extend(self.init._pack_uint32(0))
        data.extend(self.init._pack_uint32(self.source_mtime))
        data.extend(self.init._pack_uint32(self.source_size))
        code_object = compile(self.source, self.path, 'exec',
                                dont_inherit=True)
        data.extend(marshal.dumps(code_object))
        self.bytecode = bytes(data)
        self.written = {}

    def get_data(self, path):
        if path == self.path:
            return super().get_data(path)
        elif path == self.bytecode_path:
            return self.bytecode
        else:
            raise OSError

    def path_stats(self, path):
        if path != self.path:
            raise IOError
        return {'mtime': self.source_mtime, 'size': self.source_size}

    def set_data(self, path, data):
        self.written[path] = bytes(data)
        return path == self.bytecode_path

SPLIT_SL = make_abc_subclasses(SourceLoader, util=util, init=init)

class SourceLoaderTestHarness:

    def setUp(self, *, is_package=True, **kwargs):
        self.package = 'pkg'
        if is_package:
            self.path = os.path.join(self.package, '__init__.py')
            self.name = self.package
        else:
            module_name = 'mod'
            self.path = os.path.join(self.package, '.'.join(['mod', 'py']))
            self.name = '.'.join([self.package, module_name])
        self.cached = self.util.cache_from_source(self.path)
        self.loader = self.loader_mock(self.path, **kwargs)

    def verify_module(self, module):
        self.assertEqual(module.__name__, self.name)
        self.assertEqual(module.__file__, self.path)
        self.assertEqual(module.__cached__, self.cached)
        self.assertEqual(module.__package__, self.package)
        self.assertEqual(module.__loader__, self.loader)
        values = module._.split('::')
        self.assertEqual(values[0], self.name)
        self.assertEqual(values[1], self.path)
        self.assertEqual(values[2], self.cached)
        self.assertEqual(values[3], self.package)
        self.assertEqual(values[4], repr(self.loader))

    def verify_code(self, code_object):
        module = types.ModuleType(self.name)
        module.__file__ = self.path
        module.__cached__ = self.cached
        module.__package__ = self.package
        module.__loader__ = self.loader
        module.__path__ = []
        exec(code_object, module.__dict__)
        self.verify_module(module)

class SourceOnlyLoaderTests(SourceLoaderTestHarness):

    """Test importlib.abc.SourceLoader for source-only loading.

    Reload testing is subsumed by the tests for
    importlib.util.module_for_loader.

    """

    def test_get_source(self):
        # Verify the source code is returned as a string.
        # If an OSError is raised by get_data then raise ImportError.
        expected_source = self.loader.source.decode('utf-8')
        self.assertEqual(self.loader.get_source(self.name), expected_source)
        def raise_OSError(path):
            raise OSError
        self.loader.get_data = raise_OSError
        with self.assertRaises(ImportError) as cm:
            self.loader.get_source(self.name)
        self.assertEqual(cm.exception.name, self.name)

    def test_is_package(self):
        # Properly detect when loading a package.
        self.setUp(is_package=False)
        self.assertFalse(self.loader.is_package(self.name))
        self.setUp(is_package=True)
        self.assertTrue(self.loader.is_package(self.name))
        self.assertFalse(self.loader.is_package(self.name + '.__init__'))

    def test_get_code(self):
        # Verify the code object is created.
        code_object = self.loader.get_code(self.name)
        self.verify_code(code_object)

    def test_source_to_code(self):
        # Verify the compiled code object.
        code = self.loader.source_to_code(self.loader.source, self.path)
        self.verify_code(code)

    def test_load_module(self):
        # Loading a module should set __name__, __loader__, __package__,
        # __path__ (for packages), __file__, and __cached__.
        # The module should also be put into sys.modules.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            with test_util.uncache(self.name):
                with warnings.catch_warnings():
                    warnings.simplefilter('ignore', DeprecationWarning)
                    module = self.loader.load_module(self.name)
                self.verify_module(module)
                self.assertEqual(module.__path__, [os.path.dirname(self.path)])
                self.assertIn(self.name, sys.modules)

    def test_package_settings(self):
        # __package__ needs to be set, while __path__ is set on if the module
        # is a package.
        # Testing the values for a package are covered by test_load_module.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            self.setUp(is_package=False)
            with test_util.uncache(self.name):
                with warnings.catch_warnings():
                    warnings.simplefilter('ignore', DeprecationWarning)
                    module = self.loader.load_module(self.name)
                self.verify_module(module)
                self.assertFalse(hasattr(module, '__path__'))

    def test_get_source_encoding(self):
        # Source is considered encoded in UTF-8 by default unless otherwise
        # specified by an encoding line.
        source = "_ = 'ü'"
        self.loader.source = source.encode('utf-8')
        returned_source = self.loader.get_source(self.name)
        self.assertEqual(returned_source, source)
        source = "# coding: latin-1\n_ = ü"
        self.loader.source = source.encode('latin-1')
        returned_source = self.loader.get_source(self.name)
        self.assertEqual(returned_source, source)

(Frozen_SourceOnlyLoaderTests,
 Source_SourceOnlyLoaderTests
 ) = test_util.test_both(SourceOnlyLoaderTests, util=util,
                         loader_mock=SPLIT_SOL)

@unittest.skipIf(sys.dont_write_bytecode, "sys.dont_write_bytecode is true")
class SourceLoaderBytecodeTests(SourceLoaderTestHarness):

    """Test importlib.abc.SourceLoader's use of bytecode.

    Source-only testing handled by SourceOnlyLoaderTests.

    """

    def verify_code(self, code_object, *, bytecode_written=False):
        super().verify_code(code_object)
        if bytecode_written:
            self.assertIn(self.cached, self.loader.written)
            data = bytearray(self.util.MAGIC_NUMBER)
            data.extend(self.init._pack_uint32(0))
            data.extend(self.init._pack_uint32(self.loader.source_mtime))
            data.extend(self.init._pack_uint32(self.loader.source_size))
            data.extend(marshal.dumps(code_object))
            self.assertEqual(self.loader.written[self.cached], bytes(data))

    def test_code_with_everything(self):
        # When everything should work.
        code_object = self.loader.get_code(self.name)
        self.verify_code(code_object)

    def test_no_bytecode(self):
        # If no bytecode exists then move on to the source.
        self.loader.bytecode_path = "<does not exist>"
        # Sanity check
        with self.assertRaises(OSError):
            bytecode_path = self.util.cache_from_source(self.path)
            self.loader.get_data(bytecode_path)
        code_object = self.loader.get_code(self.name)
        self.verify_code(code_object, bytecode_written=True)

    def test_code_bad_timestamp(self):
        # Bytecode is only used when the timestamp matches the source EXACTLY.
        for source_mtime in (0, 2):
            assert source_mtime != self.loader.source_mtime
            original = self.loader.source_mtime
            self.loader.source_mtime = source_mtime
            # If bytecode is used then EOFError would be raised by marshal.
            self.loader.bytecode = self.loader.bytecode[8:]
            code_object = self.loader.get_code(self.name)
            self.verify_code(code_object, bytecode_written=True)
            self.loader.source_mtime = original

    def test_code_bad_magic(self):
        # Skip over bytecode with a bad magic number.
        self.setUp(magic=b'0000')
        # If bytecode is used then EOFError would be raised by marshal.
        self.loader.bytecode = self.loader.bytecode[8:]
        code_object = self.loader.get_code(self.name)
        self.verify_code(code_object, bytecode_written=True)

    def test_dont_write_bytecode(self):
        # Bytecode is not written if sys.dont_write_bytecode is true.
        # Can assume it is false already thanks to the skipIf class decorator.
        try:
            sys.dont_write_bytecode = True
            self.loader.bytecode_path = "<does not exist>"
            code_object = self.loader.get_code(self.name)
            self.assertNotIn(self.cached, self.loader.written)
        finally:
            sys.dont_write_bytecode = False

    def test_no_set_data(self):
        # If set_data is not defined, one can still read bytecode.
        self.setUp(magic=b'0000')
        original_set_data = self.loader.__class__.mro()[1].set_data
        try:
            del self.loader.__class__.mro()[1].set_data
            code_object = self.loader.get_code(self.name)
            self.verify_code(code_object)
        finally:
            self.loader.__class__.mro()[1].set_data = original_set_data

    def test_set_data_raises_exceptions(self):
        # Raising NotImplementedError or OSError is okay for set_data.
        def raise_exception(exc):
            def closure(*args, **kwargs):
                raise exc
            return closure

        self.setUp(magic=b'0000')
        self.loader.set_data = raise_exception(NotImplementedError)
        code_object = self.loader.get_code(self.name)
        self.verify_code(code_object)

(Frozen_SLBytecodeTests,
 SourceSLBytecodeTests
 ) = test_util.test_both(SourceLoaderBytecodeTests, init=init, util=util,
                         loader_mock=SPLIT_SL)

class SourceLoaderGetSourceTests:

    """Tests for importlib.abc.SourceLoader.get_source()."""

    def test_default_encoding(self):
        # Should have no problems with UTF-8 text.
        name = 'mod'
        mock = self.SourceOnlyLoaderMock('mod.file')
        source = 'x = "ü"'
        mock.source = source.encode('utf-8')
        returned_source = mock.get_source(name)
        self.assertEqual(returned_source, source)

    def test_decoded_source(self):
        # Decoding should work.
        name = 'mod'
        mock = self.SourceOnlyLoaderMock("mod.file")
        source = "# coding: Latin-1\nx='ü'"
        assert source.encode('latin-1') != source.encode('utf-8')
        mock.source = source.encode('latin-1')
        returned_source = mock.get_source(name)
        self.assertEqual(returned_source, source)

    def test_universal_newlines(self):
        # PEP 302 says universal newlines should be used.
        name = 'mod'
        mock = self.SourceOnlyLoaderMock('mod.file')
        source = "x = 42\r\ny = -13\r\n"
        mock.source = source.encode('utf-8')
        expect = io.IncrementalNewlineDecoder(None, True).decode(source)
        self.assertEqual(mock.get_source(name), expect)

(Frozen_SourceOnlyLoaderGetSourceTests,
 Source_SourceOnlyLoaderGetSourceTests
 ) = test_util.test_both(SourceLoaderGetSourceTests,
                         SourceOnlyLoaderMock=SPLIT_SOL)

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


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <title>Solaris.js usage example</title>

    <link rel="stylesheet" href="solaris/solaris.css">

redpajama_set_name: RedPajamaGithub


text:
import collections
import datetime
from contextlib import contextmanager

import nagios

from dashie_sampler import DashieSampler

from novaclient.v1_1 import client as novaclient
from cinderclient.v1 import client as cinderclient
from keystoneclient.v2_0 import client as keystoneclient
from neutronclient.v2_0 import client as neutronclient

class BaseOpenstackSampler(DashieSampler):
    """docstring for ClassName"""
    def __init__(self, app, interval, conf=None, client_cache={},
                 response_cache={}):
        self._os_clients = client_cache
        self._conf = conf
        self._response_cache = response_cache
        super(BaseOpenstackSampler, self).__init__(app, interval)

    def _convert(self, values, min_rounded):
        # takes array of byte counts; returns array of value,unit pairs

        units = ['TB', 'GB', 'MB', 'KB', 'B']
        min_value = min(values)

        for i, unit in enumerate(units):
            threshold = 1024 ** (len(units) - i - 1)
            if min_value >= threshold:
                rounded = [(int(round(v / threshold)), unit) for v in values]

                over_min = True
                for value in rounded:
                    if value[0] < min_rounded:
                        over_min = False

                if over_min:
                    return rounded

    def _client(self, service, region):

        if not self._os_clients.get(region):
            self._os_clients[region] = {}

        if not self._os_clients[region].get(service):
            if service == 'compute':
                client = novaclient.Client(
                    self._conf['auth']['username'],
                    self._conf['auth']['password'],
                    self._conf['auth']['project_name'],
                    self._conf['auth']['auth_url'],
                    region_name=region,
                    insecure=self._conf['auth']['insecure'])
                self._os_clients[region][service] = client
            elif service == 'network':
                client = neutronclient.Client(
                    username=self._conf['auth']['username'],
                    password=self._conf['auth']['password'],
                    tenant_name=self._conf['auth']['project_name'],
                    auth_url=self._conf['auth']['auth_url'],
                    region_name=region,
                    insecure=self._conf['auth']['insecure'])
                self._os_clients[region][service] = client
            elif service == 'storage':
                client = cinderclient.Client(
                    self._conf['auth']['username'],
                    self._conf['auth']['password'],
                    self._conf['auth']['project_name'],
                    self._conf['auth']['auth_url'],
                    region_name=region,
                    insecure=self._conf['auth']['insecure'])
                self._os_clients[region][service] = client
            elif service == 'identity':
                client = keystoneclient.Client(
                    username=self._conf['auth']['username'],
                    password=self._conf['auth']['password'],
                    project_name=self._conf['auth']['project_name'],
                    auth_url=self._conf['auth']['auth_url'],
                    region_name=region,
                    insecure=self._conf['auth']['insecure'])
                self._os_clients[region][service] = client

        return self._os_clients[region][service]

    @contextmanager
    def timed(self, region, service):
        start = datetime.datetime.utcnow()
        yield
        end = datetime.datetime.utcnow()
        self._api_response(int((end - start).total_seconds() * 1000),
                           region, service)

    def _api_response(self, ms, region, service):
        self._response_cache['events']['region'].append(
            {'region': region, 'service': service, 'ms': ms})
        self._response_cache['events']['service'].append(
            {'region': region, 'service': service, 'ms': ms})

class CPUSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(CPUSampler, self).__init__(*args, **kwargs)
        self._last = 0

    def name(self):
        return 'cpu'

    def sample(self):
        max_cpu = 0
        cur_cpu = 0

        for region, allocation in self._conf['allocation'].iteritems():
            nova = self._client('compute', region)
            with self.timed(region, 'compute'):
                stats = nova.hypervisors.statistics()

            reserved = allocation['reserved_vcpus']
            for i in range(stats.count):
                reserved = reserved + allocation['reserved_vcpus_per_node']

            cpu_ratio = allocation['vcpus_allocation_ratio']

            max_cpu = max_cpu + (stats.vcpus * cpu_ratio) - reserved
            cur_cpu = cur_cpu + stats.vcpus_used

        s = {'min': 0,
             'max': max_cpu,
             'value': cur_cpu,
             'last': self._last}
        s['moreinfo'] = "%s out of %s" % (s['value'], s['max'])
        s['current'] = s['value']
        self._last = s['value']
        return s

class RAMSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(RAMSampler, self).__init__(*args, **kwargs)
        self._last = 0

    def name(self):
        return 'ram'

    def sample(self):
        max_ram = 0
        cur_ram = 0

        for region, allocation in self._conf['allocation'].iteritems():
            nova = self._client('compute', region)
            with self.timed(region, 'compute'):
                stats = nova.hypervisors.statistics()

            reserved = allocation['reserved_ram']
            for i in range(stats.count):
                reserved = reserved + allocation['reserved_ram_per_node']

            ram_ratio = allocation['ram_allocation_ratio']

            max_ram = (max_ram +
                       (stats.memory_mb * ram_ratio * 1024 * 1024) - reserved)
            cur_ram = cur_ram + stats.memory_mb_used * 1024 * 1024

        ram_converted, ram_converted_used = self._convert((max_ram, cur_ram), 5)

        s = {'min': 0,
             'max': ram_converted[0],
             'value': ram_converted_used[0],
             'last': self._last}
        s['moreinfo'] = "%s%s out of %s%s" % (ram_converted_used[0],
                                              ram_converted_used[1],
                                              ram_converted[0],
                                              ram_converted[1])
        s['current'] = s['value']
        self._last = s['value']
        return s

class IPSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(IPSampler, self).__init__(*args, **kwargs)
        self._last = 0

    def name(self):
        return 'ips'

    def sample(self):
        max_ips = 0
        cur_ips = 0

        for region in self._conf['allocation'].keys():
            max_ips = (max_ips +
                       self._conf['allocation'][region]['total_floating_ips'])

            neutron = self._client('network', region)

            with self.timed(region, 'network'):
                ips = neutron.list_floatingips()
            with self.timed(region, 'network'):
                routers = neutron.list_routers()

            net_gateways = 0
            for router in routers['routers']:
                if router['external_gateway_info'] is not None:
                    net_gateways = net_gateways + 1

            cur_ips = cur_ips + len(ips['floatingips']) + net_gateways

        s = {'min': 0,
             'max': max_ips,
             'value': cur_ips,
             'last': self._last}
        s['moreinfo'] = "%s out of %s" % (cur_ips, max_ips)
        s['current'] = s['value']
        self._last = s['value']
        return s

class RegionsCPUSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(RegionsCPUSampler, self).__init__(*args, **kwargs)

    def name(self):
        return 'cpu_regions'

    def sample(self):
        regions = []

        for region, allocation in self._conf['allocation'].iteritems():
            nova = self._client('compute', region)
            with self.timed(region, 'compute'):
                stats = nova.hypervisors.statistics()

            reserved = allocation['reserved_vcpus']
            for i in range(stats.count):
                reserved = reserved + allocation['reserved_vcpus_per_node']

            cpu_ratio = allocation['vcpus_allocation_ratio']

            max_cpu = (stats.vcpus * cpu_ratio) - reserved
            cur_cpu = stats.vcpus_used

            regions.append({'name': region,
                            'progress': (cur_cpu * 100.0) / max_cpu,
                            'max': max_cpu, 'value': cur_cpu})

        return {'progress_items': regions}

class RegionsRAMSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(RegionsRAMSampler, self).__init__(*args, **kwargs)

    def name(self):
        return 'ram_regions'

    def sample(self):
        regions = []

        for region, allocation in self._conf['allocation'].iteritems():
            nova = self._client('compute', region)
            with self.timed(region, 'compute'):
                stats = nova.hypervisors.statistics()

            reserved = allocation['reserved_ram']
            for i in range(stats.count):
                reserved = reserved + allocation['reserved_ram_per_node']

            ram_ratio = allocation['ram_allocation_ratio']

            max_ram = (stats.memory_mb * ram_ratio * 1024 * 1024) - reserved
            cur_ram = stats.memory_mb_used * 1024 * 1024

            ram_converted, ram_converted_used = self._convert((max_ram,
                                                               cur_ram), 5)

            regions.append({'name': region,
                            'progress': ((ram_converted_used[0] * 100.0) /
                                         ram_converted[0]),
                            'max': ram_converted,
                            'value': ram_converted_used[0]})

        return {'progress_items': regions}

class RegionIPSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(RegionIPSampler, self).__init__(*args, **kwargs)
        self._last = 0

    def name(self):
        return 'ips_regions'

    def sample(self):
        regions = []

        for region in self._conf['allocation'].keys():
            neutron = self._client('network', region)

            with self.timed(region, 'network'):
                ips = neutron.list_floatingips()
            with self.timed(region, 'network'):
                routers = neutron.list_routers()

            net_gateways = 0
            for router in routers['routers']:
                if router['external_gateway_info'] is not None:
                    net_gateways = net_gateways + 1

            cur_ips = len(ips['floatingips']) + net_gateways
            max_ips = self._conf['allocation'][region]['total_floating_ips']

            regions.append({'name': region,
                            'progress': ((cur_ips * 100.0) /
                                         max_ips),
                            'max': max_ips, 'value': cur_ips})

        return {'progress_items': regions}

class NagiosSampler(BaseOpenstackSampler):
    def __init__(self, *args, **kwargs):
        super(NagiosSampler, self).__init__(*args, **kwargs)
        self._last = 0

    def name(self):
        return 'nagios'

    def sample(self):

        try:
            servicestatus = nagios.get_statusfiles(self._conf['services'])
            criticals = servicestatus['critical']
            warnings = servicestatus['warning']
            status = 'green'

            if criticals > 0:
                status = 'red'
            elif warnings > 0:
                status = 'yellow'

            s = {'criticals': criticals,
                 'warnings': warnings,
                 'status': status}
            return s
        except Exception, e:
            print "NagiosSampler failed with %s" % e

class NagiosRegionSampler(BaseOpenstackSampler):
    def name(self):
        return 'nagios_regions'

    def sample(self):
        try:
            servicestatus = nagios.get_statusfiles(self._conf['services'])

            criticals = []
            warnings = []

            for region in self._conf['services'].keys():
                criticals.append({'label': region,
                                  'value': servicestatus[region]['critical']})
                warnings.append({'label': region,
                                 'value': servicestatus[region]['warning']})

            # (adriant) the following is for easy testing:
            # regions = ['region1', 'region2', 'region3']

            # criticals = []
            # warnings = []

            # for region in regions:
            #     criticals.append({'label': region, 'value': random.randint(0, 5)})
            #     warnings.append({'label': region, 'value': random.randint(0, 5)})

            return {'criticals': criticals, 'warnings': warnings}
        except Exception, e:
            print "NagiosRegionSampler failed with %s" % e

class ResourceSampler(BaseOpenstackSampler):

    def name(self):
        return 'resources'

    def sample(self):
        resources = {'instances': 0,
                     'routers': 0,
                     'networks': 0,
                     # 'volumes': 0,
                     # 'images': 0,
                     'vpns': 0}

        for region in self._conf['allocation'].keys():
            neutron = self._client('network', region)
            nova = self._client('compute', region)
            # cinder = self._client('storage', region)

            with self.timed(region, 'compute'):
                stats = nova.hypervisors.statistics()
            resources['instances'] = resources['instances'] + stats.running_vms

            with self.timed(region, 'network'):
                routers = neutron.list_routers()
            resources['routers'] = (resources['routers'] +
                                    len(routers['routers']))

            with self.timed(region, 'network'):
                networks = neutron.list_networks()
            resources['networks'] = (resources['networks'] +
                                     len(networks['networks']))

            with self.timed(region, 'network'):
                vpns = neutron.list_vpnservices()
            resources['vpns'] = (resources['vpns'] +
                                 len(vpns['vpnservices']))

            # with self.timed(region, 'volume'):
            #     volumes = cinder.volumes.list(search_opts={'all_tenants': 1})
            # resources['volumes'] = (resources['volumes'] +
            #                         len(volumes))

        items = []
        for key, value in resources.iteritems():
            items.append({'label': key, 'value': value})

        return {'items': items}

class BaseAPISamper(BaseOpenstackSampler):

    def _process_event(self, cache, key, ms, base_cache):

        if cache:
            cache['items'].append({'x': cache['x'],
                                   'y': ms})
        else:
            cache = {}
            cache['items'] = collections.deque()
            cache['x'] = 0
            cache['items'].append({'x': cache['x'],
                                   'y': ms})
            base_cache[key] = cache

        cache['x'] += 1

        # to stop the x value getting too high
        if cache['x'] == 1000000:
            # reset the x value, and adjust the items
            cache['x'] = 0
            for time in cache['items']:
                time['x'] = cache['x']
                cache['x'] += 1

        if len(cache['items']) > 100:
            cache['items'].popleft()

        stats = {'min': -1, 'max': -1, 'avg': -1}
        total = 0

        for time in cache['items']:
            total += time['y']
            if time['y'] > stats['max']:
                stats['max'] = time['y']
            if stats['min'] == -1 or time['y'] < stats['min']:
                stats['min'] = time['y']

        stats['avg'] = int(total / len(cache['items']))

        cache['stats'] = stats

class APIRegionSampler(BaseAPISamper):

    def __init__(self, app, interval, conf=None, client_cache={},
                 response_cache={}, resync_period=180):
        super(APIRegionSampler, self).__init__(app, interval, conf,
                                               client_cache, response_cache)
        self._no_sync = None
        self._resync_period = resync_period

    def name(self):
        return 'api_region_response'

    def sample(self):
        while self._response_cache['events']['region']:
            event = self._response_cache['events']['region'].popleft()
            cache = self._response_cache['regions'].get(event['region'])
            self._process_event(cache, event['region'], event['ms'],
                                self._response_cache['regions'])

        displayedValue = ""
        series = []

        x = None
        equal = True
        for region, cache in self._response_cache['regions'].iteritems():
            if x is None:
                x = cache['x']
            if x != cache['x']:
                equal = False
            displayedValue += ("%s - (min: %s  max: %s  avg: %s)\n" %
                               (region,
                                cache['stats']['min'],
                                cache['stats']['max'],
                                cache['stats']['avg']))
            series.append({'name': region, 'data': list(cache['items'])})

        if equal:
            self._no_sync = None
        elif self._no_sync is None:
                self._no_sync = datetime.datetime.utcnow()
        elif ((datetime.datetime.utcnow() - self._no_sync).total_seconds() >
              self._resync_period):
            self._response_cache['regions'].clear()
            displayedValue = "Clearing Cache to resync graphs"
            series = []
            self._no_sync = None

        return {'displayedValue': displayedValue, 'series': series}

class ServiceAPISampler(BaseAPISamper):
    def __init__(self, *args, **kwargs):
        super(ServiceAPISampler, self).__init__(*args, **kwargs)
        self.service_list = []

    def name(self):
        return 'api_service_response'

    def sample(self):
        while self._response_cache['events']['service']:
            event = self._response_cache['events']['service'].popleft()
            cache = self._response_cache['services'].get(event['service'])
            self._process_event(cache, event['service'], event['ms'],
                                self._response_cache['services'])

        if not self.service_list:
            self.service_list = self._response_cache['services'].keys()
            self.next_service = 0

        displayedValue = ""
        series = []

        while True:
            try:
                service = self.service_list[self.next_service]
                cache = self._response_cache['services'][service]
                displayedValue += ("%s - (min: %s  max: %s  avg: %s)\n" %
                                   (service,
                                    cache['stats']['min'],
                                    cache['stats']['max'],
                                    cache['stats']['avg']))
                series.append({'name': service, 'data': list(cache['items'])})
                self.next_service += 1
                return {'displayedValue': displayedValue, 'series': series}
            except IndexError:
                if self.next_service == 0:
                    break
                self.service_list = self._response_cache['services'].keys()
                self.next_service = 0


text:
using ATPTennisStat.Common;
using ATPTennisStat.Factories.Contracts;
using ATPTennisStat.Models.SqlServerModels;
using ATPTennisStat.Models.Enums;
using ATPTennisStat.SQLServerData;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ATPTennisStat.Factories
{
    public class ModelsFactory : IModelsFactory
    {
        private ISqlServerDataProvider dataProvider;

        public ModelsFactory(ISqlServerDataProvider dataProvider)
        {
            this.dataProvider = dataProvider;
        }

        public Match CreateMatch(string datePlayed,
                         string winnerName,
                         string loserName,
                         string result,
                         string tournamentName,
                         string roundName)
        {

            if (String.IsNullOrEmpty(winnerName))
            {
                throw new ArgumentException("Winner - null or empty");
            }

            if (String.IsNullOrEmpty(loserName))
            {
                throw new ArgumentException("Loser - null or empty");
            }
            string[] winnerNames = winnerName.Split(' ');

            if (winnerNames.Length < 2)
            {
                throw new ArgumentException("Winner name not formatted correctly - Firstname Lastname");
            }
            string[] loserNames = loserName.Split(' ');

            if (loserNames.Length < 2)
            {
                throw new ArgumentException("Loser name not formatted correctly - Firstname Lastname");
            }

            var winnerFirstName = winnerNames[0];
            var winnerFirstNameToLower = winnerFirstName.ToLower();
            var winnerLastName = string.Join(" ", winnerNames.Skip(1));
            var winnerLastNameToLower = winnerLastName.ToLower();

            var loserFirstName = loserNames[0];
            var loserFirstNameToLower = loserFirstName.ToLower();
            var loserLastName = string.Join(" ", loserNames.Skip(1));
            var loserLastNameToLower = loserLastName.ToLower();

            if (String.IsNullOrEmpty(datePlayed))
            {
                throw new ArgumentException("Match date is required");
            }

            DateTime datePlayedParsed;

            try
            {
                datePlayedParsed = DateTime.Parse(datePlayed);
            }
            catch (Exception)
            {

                throw new ArgumentException("Startdate cannot be parsed");
            }

            var matchFound = this.dataProvider.Matches.GetAll()
                                .FirstOrDefault(m => m.Winner.FirstName.ToLower() == winnerFirstNameToLower &&
                                          m.Winner.LastName.ToLower() == winnerLastNameToLower &&
                                          m.Loser.FirstName.ToLower() == loserFirstNameToLower &&
                                          m.Loser.LastName.ToLower() == loserLastNameToLower &&
                                          m.DatePlayed == datePlayedParsed); // working?
            if (matchFound != null)
            {
                throw new ArgumentException($"Match between {matchFound.Winner.LastName} and {matchFound.Loser.LastName} played on {matchFound.DatePlayed} already exists in the database under id: {matchFound.Id}");
            }

            if (String.IsNullOrEmpty(result))
            {
                throw new ArgumentException("Result - null or empty");
            }

            var winner = this.dataProvider.Players.GetAll()
                            .FirstOrDefault(p => p.FirstName.ToLower() == winnerFirstNameToLower &&
                                                 p.LastName.ToLower() == winnerLastNameToLower);

            if (String.IsNullOrEmpty(roundName))
            {
                throw new ArgumentException("Round - null or empty");
            }

            if (String.IsNullOrEmpty(tournamentName))
            {
                throw new ArgumentException("Tournament - null or empty");
            }

            if (winner == null)
            {
                winner = CreatePlayer(winnerFirstName, winnerLastName);

                this.dataProvider.Players.Add(winner);
            }

            var loser = this.dataProvider.Players.GetAll()
                .FirstOrDefault(p => p.FirstName.ToLower() == loserFirstNameToLower &&
                                     p.LastName.ToLower() == loserLastNameToLower);

            if (loser == null)
            {
                loser = CreatePlayer(loserFirstName, loserLastName);

                this.dataProvider.Players.Add(loser);
            }

            //RoundID
            RoundStage roundParsed;

            try
            {
                roundParsed = (RoundStage)Enum.Parse(typeof(RoundStage), roundName, true);
            }
            catch (Exception)
            {

                throw new ArgumentException("Round stage cannot be parsed - Available ones are Q1, Q2...");
            }

            var round = dataProvider.Rounds.GetAll()
                            .FirstOrDefault(r => r.Stage == roundParsed);

            if (round == null)
            {
                round = new Round
                {
                    Stage = roundParsed
                };

                this.dataProvider.Rounds.Add(round);
            }
            //TournamentID
            var tournamentNameToLower = tournamentName.ToLower();

            var tournament = dataProvider.Tournaments.GetAll()
                             .FirstOrDefault(t => t.Name.ToLower() == tournamentNameToLower);

            if (tournament == null)
            {
                throw new ArgumentException("Tournament cannot be found - please import tournaments" + tournamentName);
            }

            //Console.WriteLine("MatchImported " + tournamentName);

            return new Match
            {
                DatePlayed = datePlayedParsed,
                Winner = winner,
                Loser = loser,
                Result = result,
                Round = round,
                Tournament = tournament
            };
        }

        public PointDistribution CreatePointDistribution(string categoryName,
                                                         string playersNumber,
                                                         string roundName,
                                                         string points)
        {

            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentException("Category name is empty");
            }

            var categoryNameToLower = categoryName.ToLower();

            if (String.IsNullOrEmpty(roundName))
            {
                throw new ArgumentException("Round name is empty");
            }

            RoundStage roundNameParsed;

            try
            {
                roundNameParsed = (RoundStage)Enum.Parse(typeof(RoundStage), roundName, true);
            }
            catch (Exception)
            {

                throw new ArgumentException("Round stage cannot be parsed - Available ones are Q1, Q2...");
            }

            if (String.IsNullOrEmpty(playersNumber))
            {
                throw new ArgumentException("Players number is empty");
            }
            byte playersNumberParsed;

            try
            {
                playersNumberParsed = byte.Parse(playersNumber);
            }
            catch (Exception)
            {

                throw new ArgumentException("Players number cannot be parsed");
            }

            var foundPointDistribution = this.dataProvider.PointDistributions.GetAll()
                    .FirstOrDefault(pd => pd.TournamentCategory.Category.ToLower() == categoryNameToLower &&
                                pd.TournamentCategory.PlayersCount == playersNumberParsed &&
                                pd.Round.Stage == roundNameParsed);
            if (foundPointDistribution != null)
            {
                throw new ArgumentException($"Point distribution for already exists in the database under round id: {foundPointDistribution.RoundId} and tournament category id: {foundPointDistribution.TournamentCategoryId} ");
            }

            int pointsParsed;

            try
            {
                pointsParsed = int.Parse(points);
            }
            catch (Exception)
            {

                throw new ArgumentException("Points cannot be parsed");
            }

            var tournamentCategory = dataProvider.TournamentCategories.GetAll()
                                        .FirstOrDefault(c => c.Category.ToLower() == categoryNameToLower &&
                                            c.PlayersCount == playersNumberParsed);

            if (tournamentCategory == null)
            {
                tournamentCategory = CreateTournamentCategory(categoryName, playersNumberParsed);

                this.dataProvider.TournamentCategories.Add(tournamentCategory);
            }

            var round = dataProvider.Rounds.GetAll()
                                        .FirstOrDefault(r => r.Stage == roundNameParsed);

            if (round == null)
            {
                round = new Round
                {
                    Stage = roundNameParsed
                };

                this.dataProvider.Rounds.Add(round);
            }

            return new PointDistribution
            {
                TournamentCategory = tournamentCategory,
                Round = round,
                Points = pointsParsed

            };
        }

        public Tournament CreateTournament(string name,
                                           string startDate,
                                           string endDate,
                                           string prizeMoney,
                                           string categoryName,
                                           string playersCount,
                                           string cityName,
                                           string countryName,
                                           string surfaceType,
                                           string surfaceSpeed)
        {

            //Name is Unique

            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Tournament name is empty");
            }

            var nameToLower = name.ToLower();

            var tournamentFound = this.dataProvider.Tournaments.GetAll()
                                .FirstOrDefault(t => t.Name.ToLower() == nameToLower);
            if (tournamentFound != null)
            {
                throw new ArgumentException($"{tournamentFound.Name} already in the database under id {tournamentFound.Id}");
            }

            //START DATE
            if (String.IsNullOrEmpty(startDate))
            {
                throw new ArgumentException("Tournament startdate is required");
            }

            DateTime startDateParsed;

            try
            {
                startDateParsed = DateTime.Parse(startDate);
            }
            catch (Exception)
            {

                throw new ArgumentException("Startdate cannot be parsed");
            }

            //END DATE
            if (String.IsNullOrEmpty(endDate))
            {
                throw new ArgumentException("Tournament enddate is required");
            }

            DateTime endDateParsed;

            try
            {
                endDateParsed = DateTime.Parse(endDate);
            }
            catch (Exception)
            {

                throw new ArgumentException("Enddate cannot be parsed");
            }

            //prizeMoney

            if (String.IsNullOrEmpty(prizeMoney))
            {
                throw new ArgumentException("Prize money is required");
            }

            decimal prizeMoneyParsed;

            try
            {
                prizeMoneyParsed = decimal.Parse(prizeMoney);
            }
            catch (Exception)
            {

                throw new ArgumentException("Prize money cannot be parsed");
            }

            //look for existing category -> + PlayersCount
            //categoryName
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentException("Category name is required");
            }

            if (String.IsNullOrEmpty(playersCount))
            {
                throw new ArgumentException("Players number is required");
            }

            var categoryNameToLower = categoryName.ToLower();

            byte playersCountParsed;

            try
            {
                playersCountParsed = byte.Parse(playersCount);
            }
            catch (Exception)
            {
                throw new ArgumentException("Prize money cannot be parsed");
            }

            var list = this.dataProvider.TournamentCategories.GetAll();

            var tournamentCategory = list.FirstOrDefault(c => c.Category.ToLower() == categoryNameToLower &&
                                            c.PlayersCount == playersCountParsed);

            if (tournamentCategory == null)
            {
                tournamentCategory = CreateTournamentCategory(categoryName, playersCountParsed);

                this.dataProvider.TournamentCategories.Add(tournamentCategory);
            }

            //create new city
            if (String.IsNullOrEmpty(cityName))
            {
                throw new ArgumentException("City name is required");
            }

            if (String.IsNullOrEmpty(countryName))
            {
                throw new ArgumentException("Country name is required");
            }

            var cityNameToLower = cityName.ToLower();

            var countryNameToLower = countryName.ToLower();

            var city = this.dataProvider.Cities.GetAll()
                        .FirstOrDefault(c => c.Name.ToLower() == cityNameToLower);

            if (city == null)
            {
                city = CreateCity(cityName, countryName);

                this.dataProvider.Cities.Add(city);
            }

            //surface type + surface speed

            if (String.IsNullOrEmpty(surfaceType))
            {
                throw new ArgumentException("Surface type is required");
            }

            if (String.IsNullOrEmpty(surfaceSpeed))
            {
                throw new ArgumentException("Surface speed is required");
            }

            var surfaceTypeToLower = surfaceType.ToLower();

            var surfaceSpeedToLower = surfaceSpeed.ToLower();

            var surfacesList = this.dataProvider.Surfaces.GetAll();

            var surface = surfacesList
                                .FirstOrDefault(s => s.Type.ToLower() == surfaceTypeToLower &&
                                            s.Speed.ToLower() == surfaceSpeedToLower);

            if (surface == null)
            {
                surface = CreateSurface(surfaceType, surfaceSpeed);

                this.dataProvider.Surfaces.Add(surface);
            }

            return new Tournament
            {
                Name = name,
                StartDate = startDateParsed,
                EndDate = endDateParsed,
                PrizeMoney = prizeMoneyParsed,
                Category = tournamentCategory,
                City = city,
                Type = surface

            };
        }

        public Surface CreateSurface(string surfaceType, string surfaceSpeed)
        {

            if (String.IsNullOrEmpty(surfaceType))
            {
                throw new ArgumentException("Surface type - null or empty");
            }

            if (String.IsNullOrEmpty(surfaceType))
            {
                throw new ArgumentException("Surface speed - null or empty");
            }

            var surfaceTypeToLower = surfaceType.ToLower();
            var surfaceSpeedToLower = surfaceSpeed.ToLower();

            bool surfaceExists = this.dataProvider.Surfaces.GetAll()
                                .Any(s => s.Type.ToLower() == surfaceTypeToLower &&
                                            s.Speed.ToLower() == surfaceSpeedToLower);

            if (surfaceExists)
            {
                throw new ArgumentException("Surface already in the database");
            }

            return new Surface
            {
                Type = surfaceType,
                Speed = surfaceSpeed
            };
        }

        public TournamentCategory CreateTournamentCategory(string categoryName, byte playersCount)
        {
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentException("Category name - null or empty");
            }

            var nameToLower = categoryName.ToLower();

            var tournamentCategoryFound = this.dataProvider.TournamentCategories.GetAll()
                                .FirstOrDefault(tc => tc.Category.ToLower() == nameToLower &&
                                        tc.PlayersCount == playersCount);

            if (tournamentCategoryFound != null)
            {
                throw new ArgumentException($"{tournamentCategoryFound.Category} already exists in the database under id: {tournamentCategoryFound.Id}");
            }

            return new TournamentCategory
            {
                Category = categoryName,
                PlayersCount = playersCount
            };
        }

        public Player CreatePlayer(string firstName,
                                   string lastName,
                                   string ranking = null,
                                   string birthDate = null,
                                   string height = null,
                                   string weight = null,
                                   string cityName = null,
                                   string countryName = null)
        {

            if (String.IsNullOrEmpty(firstName))
            {
                throw new ArgumentException("First name - null or empty");
            }

            if (String.IsNullOrEmpty(lastName))
            {
                throw new ArgumentException("Last name - null or empty");
            }

            var firstNameToLower = firstName.ToLower();
            var lastNameToLower = lastName.ToLower();

            var playerFound = this.dataProvider.Players.GetAll()
                                .FirstOrDefault(p => p.FirstName.ToLower() == firstNameToLower &&
                                            p.LastName.ToLower() == lastNameToLower);
            if (playerFound != null)
            {
                throw new ArgumentException($"{playerFound.FirstName} {playerFound.LastName} already in the database under id {playerFound.Id}");
            }

            int? rankingParsed = null;

            if (String.IsNullOrEmpty(ranking) == false)
            {
                try
                {
                    rankingParsed = int.Parse(ranking);
                }
                catch (Exception)
                {

                    throw new ArgumentException("Ranking cannot be parsed");
                }
            }

            DateTime? birthDateParsed = null;
            if (String.IsNullOrEmpty(birthDate) == false)
            {
                try
                {
                    birthDateParsed = DateTime.Parse(birthDate);
                }
                catch (Exception)
                {

                    throw new ArgumentException("Birthdate cannot be parsed");
                }
            }

            float? heightParsed = null;
            if (String.IsNullOrEmpty(height) == false)
            {
                try
                {
                    heightParsed = float.Parse(height);
                }
                catch (Exception)
                {

                    throw new ArgumentException("Height cannot be parsed");
                }
            }

            float? weightParsed = null;
            if (String.IsNullOrEmpty(weight) == false)
            {
                try
                {
                    weightParsed = float.Parse(weight);
                }
                catch (Exception)
                {

                    throw new ArgumentException("Weight cannot be parsed");
                }
            }

            City city = null;

            if (String.IsNullOrEmpty(cityName) == false)
            {
                if (String.IsNullOrEmpty(countryName))
                {
                    throw new ArgumentException("Country name - null or empty");
                }

                var cityNameToLowerCase = cityName.ToLower();

                var countryNameLowerCase = countryName.ToLower();

                var list = this.dataProvider.Cities.GetAll();

                city = list.FirstOrDefault(c => c.Name.ToLower() == cityNameToLowerCase);

                if (city == null)
                {
                    city = CreateCity(cityName, countryName);

                    this.dataProvider.Cities.Add(city);
                }
            }

            return new Player
            {
                FirstName = firstName,
                LastName = lastName,
                Ranking = rankingParsed,
                BirthDate = birthDateParsed,
                Height = heightParsed,
                Weight = weightParsed,
                City = city

            };
        }

        public Country CreateCountry(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Country name - null or empty");
            }

            var nameToLower = name.ToLower();
            var countryFound = this.dataProvider.Countries.GetAll()
                                .FirstOrDefault(c => c.Name.ToLower() == nameToLower);

            if (countryFound != null)
            {
                throw new ArgumentException($"{countryFound.Name} already exists in the database under {countryFound.Id}");
            }

            return new Country
            {
                Name = name
            };
        }

        public City CreateCity(string name, string countryName)
        {

            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("City name - null or empty");
            }

            var cityNameLowerCase = name.ToLower();

            var cityFound = this.dataProvider.Cities.GetAll()
                                .FirstOrDefault(c => c.Name.ToLower() == cityNameLowerCase);

            if (cityFound != null)
            {
                throw new ArgumentException($"{cityFound.Name} already in the database under id: {cityFound.Id}");
            }

            if (String.IsNullOrEmpty(countryName))
            {
                throw new ArgumentException("Country name - null or empty");
            }

            var countryNameLowerCase = countryName.ToLower();

            var list = this.dataProvider.Countries.GetAll();

            var country = list.FirstOrDefault(c => c.Name.ToLower() == countryNameLowerCase);

            if (country == null)
            {
                country = CreateCountry(countryName);

                this.dataProvider.Countries.Add(country);
            }

            return new City
            {
                Name = name,
                Country = country
            };

        }
    }
}


text:
require 'spec_helper'

describe 'cloud::network::dhcp' do

  shared_examples_for 'openstack network dhcp' do

    let :pre_condition do
      "class { 'cloud::network':
        rabbit_hosts             => ['10.0.0.1'],
        rabbit_password          => 'secrete',
        api_eth                  => '10.0.0.1',
        verbose                  => true,
        debug                    => true,
        use_syslog               => true,
        dhcp_lease_duration      => '10',
        log_facility             => 'LOG_LOCAL0' }"
    end

    let :params do
      { :veth_mtu => '1400',
        :debug    => true }
    end

    it 'configure neutron common' do
      is_expected.to contain_class('neutron').with(
          :allow_overlapping_ips   => true,
          :dhcp_agents_per_network => '2',
          :verbose                 => true,
          :debug                   => true,
          :log_facility            => 'LOG_LOCAL0',
          :use_syslog              => true,
          :rabbit_user             => 'neutron',
          :rabbit_hosts            => ['10.0.0.1'],
          :rabbit_password         => 'secrete',
          :rabbit_virtual_host     => '/',
          :bind_host               => '10.0.0.1',
          :core_plugin             => 'neutron.plugins.ml2.plugin.Ml2Plugin',
          :service_plugins         => ['neutron.services.loadbalancer.plugin.LoadBalancerPlugin','neutron.services.metering.metering_plugin.MeteringPlugin','neutron.services.l3_router.l3_router_plugin.L3RouterPlugin'],
          :log_dir                 => false,
          :dhcp_lease_duration     => '10',
          :report_interval         => '30'
      )
    end

    it 'configure neutron dhcp' do
      is_expected.to contain_class('neutron::agents::dhcp').with(
          :debug                    => true,
          :dnsmasq_config_file      => '/etc/neutron/dnsmasq-neutron.conf',
          :enable_isolated_metadata => true
      )

      is_expected.to contain_neutron_dhcp_agent_config('DEFAULT/dnsmasq_dns_servers').with_ensure('absent')

      is_expected.to contain_file('/etc/neutron/dnsmasq-neutron.conf').with(
        :mode => '0755',
        :owner => 'root',
        :group => 'root'
      )
      is_expected.to contain_file('/etc/neutron/dnsmasq-neutron.conf').with_content(/^dhcp-option-force=26,1400$/)
    end
  end

  shared_examples_for 'openstack network dhcp with custom nameserver' do

    let :pre_condition do
      "class { 'cloud::network':
        rabbit_hosts             => ['10.0.0.1'],
        rabbit_password          => 'secrete',
        api_eth                  => '10.0.0.1',
        verbose                  => true,
        debug                    => true,
        use_syslog               => true,
        dhcp_lease_duration      => '10',
        log_facility             => 'LOG_LOCAL0' }"
    end

    let :params do
      { :veth_mtu           => '1400',
        :debug              => true,
        :dnsmasq_dns_servers => ['1.2.3.4'] }
    end

    it 'configure neutron dhcp' do
      is_expected.to contain_class('neutron::agents::dhcp').with(
          :debug => true
      )

      is_expected.to contain_neutron_dhcp_agent_config('DEFAULT/dnsmasq_config_file').with_value('/etc/neutron/dnsmasq-neutron.conf')
      is_expected.to contain_neutron_dhcp_agent_config('DEFAULT/enable_isolated_metadata').with_value(true)
      is_expected.to contain_neutron_dhcp_agent_config('DEFAULT/dnsmasq_dns_servers').with_value('1.2.3.4')

      is_expected.to contain_file('/etc/neutron/dnsmasq-neutron.conf').with(
        :mode => '0755',
        :owner => 'root',
        :group => 'root'
      )
      is_expected.to contain_file('/etc/neutron/dnsmasq-neutron.conf').with_content(/^dhcp-option-force=26,1400$/)

    end

    context 'with more than one dns server' do
      before { params.merge!(:dnsmasq_dns_servers => ['1.2.3.4','4.3.2.1','2.2.2.2']) }
      it { is_expected.to contain_neutron_dhcp_agent_config('DEFAULT/dnsmasq_dns_servers').with_value('1.2.3.4,4.3.2.1,2.2.2.2') }
    end

    context 'with default firewall enabled' do
      let :pre_condition do
        "class { 'cloud': manage_firewall => true }"
      end
      it 'configure neutron-server firewall rules' do
        is_expected.to contain_firewall('100 allow dhcp in access').with(
          :port   => '67',
          :proto  => 'udp',
          :chain  => 'INPUT',
          :action => 'accept',
        )
        is_expected.to contain_firewall('100 allow dhcp out access').with(
          :port   => '68',
          :proto  => 'udp',
          :chain  => 'OUTPUT',
          :action => 'accept',
        )
      end
    end

    context 'with custom firewall enabled' do
      let :pre_condition do
        "class { 'cloud': manage_firewall => true }"
      end
      before :each do
        params.merge!(:firewall_settings => { 'limit' => '50/sec' } )
      end
      it 'configure neutrons-server firewall rules with custom parameter' do
        is_expected.to contain_firewall('100 allow dhcp in access').with(
          :port   => '67',
          :proto  => 'udp',
          :chain  => 'INPUT',
          :action => 'accept',
          :limit  => '50/sec',
        )
        is_expected.to contain_firewall('100 allow dhcp out access').with(
          :port   => '68',
          :proto  => 'udp',
          :chain  => 'OUTPUT',
          :action => 'accept',
          :limit  => '50/sec',
        )
      end
    end

  end

  context 'on Debian platforms' do
    let :facts do
      { :osfamily => 'Debian' }
    end

    it_configures 'openstack network dhcp'
    it_configures 'openstack network dhcp with custom nameserver'
  end

  context 'on RedHat platforms' do
    let :facts do
      { :osfamily => 'RedHat' }
    end

    it_configures 'openstack network dhcp'
    it_configures 'openstack network dhcp with custom nameserver'
  end

end


text:
package li.l1t.tingo;

import li.l1t.tingo.config.TingoProperties;
import li.l1t.tingo.model.Teacher;
import li.l1t.tingo.model.TingoField;
import li.l1t.tingo.service.FieldService;
import li.l1t.tingo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Controller for serving Tingo's main template, aka the AngularJS client.
 *
 * @author xxyy
 * @since 2016-02-06
 */
@Controller
public class LandingController {
    @Autowired
    private TingoProperties configuration;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private FieldService fieldService;

    @GetMapping("")
    public String main(Model model) {
        model.addAttribute("footerText", configuration.getFooterText());
        model.addAttribute("navbarLinks", configuration.getNavbarLinks());
        return "main";
    }

    @GetMapping("/secure/print/teacher/by/id/{id}/pages/{boardCount}")
    public String teacherPrint(Model model, @PathVariable int id,
                               @PathVariable @Valid @Max(142) @Min(1) int boardCount) {
        Teacher teacher = teacherService.getById(id);
        model.addAttribute("teacher", teacher);
        List<TingoField> fields = fieldService.getAllFieldsByTeacher(teacher);
        List<List<TingoField>> boards = new ArrayList<>(boardCount);
        for(int i = 0; i < boardCount; i++) {
            boards.add(prepareFields(fields));
        }
        model.addAttribute("boards", boards);
        return "teacher-print";
    }

    private List<TingoField> prepareFields(List<TingoField> fields) {
        List<TingoField> newFields = new ArrayList<>(fields);
        Collections.shuffle(newFields);
        Collections.shuffle(newFields); //subjective feeling of safety
        return newFields.size() < 25 ? newFields : newFields.subList(0, 25);
    }
}


text:
package org.finra.jtaf.core.utilities;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.finra.jtaf.core.asserts.AssertionFailedError;

/**
 * Utility class to perform comparison of lists and maps
 *
 */
public class CompositeDataComparator {

	private List<String> errorList;
	private boolean accumulateErrors;

	public CompositeDataComparator() {
		accumulateErrors = false;
	}

	public CompositeDataComparator(boolean accumulateErrors) {
		this.accumulateErrors = accumulateErrors;
		errorList = new ArrayList<String>();
	}

	public void compareMap(String title, String element, Map<?, ?> expComp,
			Map<?, ?> actualComp) {
		String prefix = getPrefix(title, element);
		Set<?> keySet = expComp.keySet();

		for (Iterator<?> iter = keySet.iterator(); iter.hasNext();) {
			String obj = (String) iter.next();

			Object eValue = expComp.get(obj);

			if (!actualComp.containsKey(obj)) {
				reportError(prefix + " Couldn't find Element [" + obj
						+ "] in Actual Data");

			}
			Object aValue = actualComp.get(obj);

			assessAndCompare(prefix, obj, eValue, aValue);
		}
	}

	public void compareList(String title, String element, List<?> expList,
			List<?> actualList) {
		String prefix = getPrefix(title, element);

		if (compareSize(prefix, expList, actualList)) {

			for (int i = 0; i < expList.size(); i++) {
				Object expected = expList.get(i);
				Object actual = actualList.get(i);

				assessAndCompare(prefix + "[position : " + (i + 1) + "]", null,
						expected, actual);
			}
		}
	}

	/*
	 * for comparing untyped objects that may be instances of Boolean, String, String[], Timestamp, List, or Map
	 * lists and maps are internally tested for the same types recursively
	 *
	 * any other types on the basic or internal levels are compared as type Object
	 *
	 * if basic or internal Objects are both null they are considered equal
	 */
	public void compareObject(String title, String element, Object expected, Object actual) {
		assessAndCompare(title, element, expected, actual);
	}

	public List<String> getErrorList() {
		return errorList;
	}

	/**
	 * Sets the accumulate errors flag
	 *
	 * @param accumulateErrors determines if the comparator will throw
	 *     an exception with errors found, or accumulate them for later reporting
	 */
	public void setAccumulateErrors(boolean accumulateErrors) {
	    this.accumulateErrors = accumulateErrors;
	    if(accumulateErrors && errorList == null) {
	        errorList = new ArrayList<String>();
	    }
	}

	/**
	 * Gets the accumulate errors flag
	 *
	 * @return the accumulate errors flag
	 */
	public boolean getAccumulateErrors() {
	    return this.accumulateErrors;
	}

	private void reportError(String error) {
		if (!accumulateErrors)
			throw new AssertionFailedError(error);
		else
			errorList.add(error);

	}

	private String getPrefix(String title, String element) {
		return (element == null && !"".equals(element)) ? title : title + "-> "
				+ element + " : ";
	}

	private void assessAndCompare(String title, String element,
			Object expected, Object actual) {
		String prefix = getPrefix(title, element);

		if (expected == null && actual == null) {
			return;
		} else if (expected == null || actual == null) {
			if ("".equals(expected) || "".equals(actual))
				return;
			reportError(prefix + " didn't match. Expected Value[" + expected
					+ "] and Actual Value [" + actual + "].");
		} else if (expected instanceof Map) {
			compareMap(title, element, (Map<?, ?>) expected, (Map<?, ?>) actual);
		} else if (expected instanceof List) {
			compareList(title, element, (List<?>) expected, (List<?>) actual);
		} else if (expected instanceof Timestamp) {
			Timestamp expTimestamp = (Timestamp) expected;
			if (!(actual instanceof Timestamp))
				reportError(prefix + " Expected value [" + expTimestamp
						+ "] and Actual Value [" + actual + "].");

			else
				compareObject(prefix, expTimestamp, (Timestamp) actual);
		} else if (expected instanceof String[]) {
			String e[] = (String[]) expected;
			String a[] = (String[]) actual;

			if (e.length != a.length)
				reportError(prefix
						+ " Length of string array didn't match. Expected ["
						+ e.length + "] and Actual [" + a.length + "].");

			for (int i = 0; i < e.length; i++) {
				try {
					Double expD = Double.valueOf((String) e[i]);
					Double actD = Double.valueOf((String) a[i]);

					compareObject(prefix, expD, actD);
				} catch (NumberFormatException ignore) {
					compareObject(prefix, e[i], a[i]);
				}
			}
		} else if (expected instanceof String) {

			try {
				Double expD = Double.valueOf((String) expected);
				Double actD = Double.valueOf((String) actual);

				compareObject(prefix, expD, actD);
			} catch (NumberFormatException ignore) {
				compareObject(prefix, expected, actual);
			}
		} else if (expected instanceof Boolean && actual instanceof String) {

			try {

				String actualString = Boolean.FALSE.toString();
				if ("y".equalsIgnoreCase((String) actual)
						|| "true".equalsIgnoreCase((String) actual)) {
					actualString = Boolean.TRUE.toString();
				}

				compareObject(prefix, expected.toString(), actualString);
			} catch (NumberFormatException ignore) {
				compareObject(prefix, expected, actual);
			}
		} else if (expected instanceof Integer && actual instanceof BigDecimal) {
			BigDecimal expectedBigDecimal = new BigDecimal((Integer) expected);
			compareObject(prefix, expectedBigDecimal, actual);

		} else {
			compareObject(prefix, expected, actual);
		}
	}

	private void compareObject(String prefix, Object expected, Object actual) {
		if (!expected.equals(actual)) {
			reportError(prefix + " didn't match. Expected Value[" + expected
					+ "] and Actual Value [" + actual + "].");
		}
	}

	private boolean compareSize(String comp, List<?> expSessions, List<?> actualSessions) {
		boolean equal = true;
		if (expSessions.size() != actualSessions.size()) {
			reportError(comp + "didn't match; Expected List size: "
					+ expSessions.size() + " -- Actual List size: "
					+ actualSessions.size());
			equal = false;
		}
		return equal;
	}
}


text:
'use strict'

const test = require('ava')

const loadImages = require('../load-images')
const { addPropertyMacro, overridePropertyMacro } = require('./helpers/macros')

test('loadImages output', (t) => {
  const result = loadImages()
  t.is(typeof result, 'object', 'should return a object')
  t.is(Object.keys(result).length, 1, 'should return a object with one property')
  t.is(result.module.rules.length, 1, 'object', 'result.module.rules should be an array with 1 rule')
})

test('loadImages add option', addPropertyMacro, loadImages)

test('loadImages override option', overridePropertyMacro, loadImages)


text:
using Markdig;
using Markdig.Renderers;

namespace ITGlobal.MarkDocs.Format.Impl.Extensions.Icons
{
    internal sealed class IconExtension : IMarkdownExtension
    {
        // TODO add support for fortawesome

        public void Setup(MarkdownPipelineBuilder pipeline)
        {
            pipeline.InlineParsers.Insert(0, new IconParser());
        }

        public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
        {
            if (renderer is HtmlRenderer htmlRenderer && !htmlRenderer.ObjectRenderers.Contains<IconInlineRenderer>())
            {
                htmlRenderer.ObjectRenderers.Insert(0, new IconInlineRenderer());
            }
        }
    }
}


text:
<resources>
    <string name="app_name">/r/Android App store</string>
    <string name="button_refresh">Aggiorna</string>
    <string name="button_filter">Filtra</string>
    <string name="button_search">Cerca</string>
    <string name="screen_details">Dettagli</string>
    <string name="button_contact">Contatti</string>
    <string name="button_download">Scarica</string>
    <string name="gplay">Google Play</string>
    <string name="fdroid">F-Droid</string>
    <string name="website">Sito web</string>
    <string name="mail">Email</string>
    <string name="reddit">Reddit</string>
    <string name="twitter">Twitter</string>
    <string name="instagram">Instagram</string>
    <string name="hint_type_to_filter">Digita per filtrare</string>
    <string name="button_about">Informazioni</string>
    <string name="text_contributors">Contributori</string>
    <string name="licenses">Licenze</string>
    <string name="version">Versione</string>
    <string name="bugreport">Segnala bug</string>
    <string name="settings">Impostazioni</string>
    <string name="more">Più</string>
    <string name="appearance">Aspetto</string>
    <string name="preference_theme">Tema</string>
    <string name="preference_theme_desc">Tema da usare</string>
    <string name="restart">È necessario riavviare per cambiare il tema</string>
    <string name="later">Dopo</string>
    <string name="app_category_everything">Tutto</string>
    <string name="app_category_new">Nuovo</string>
    <string name="view_update">Mostra aggiornamenti</string>
    <string name="error">Errore nell\'ottenere il repository</string>
    <string name="options">Opzioni dei dati</string>
    <string name="screenshots">Screenshot</string>
    <string name="options_loadmedia_title">Icone e schermate</string>
    <string name="options_loadmedia_summary">Carica icone e schermate delle app</string>
    <string name="update">Aggiornamento disponibile</string>
    <string name="update_error">Errore nel controllo degli aggiornamenti</string>
    <string name="update_confirm">Aggiorna</string>
    <string name="cancel">Annulla</string>
    <string name="flag">Segnala app</string>
    <string name="no_message">Inserisci un messaggio</string>
    <string name="no_email_client">Nessun client email disponibile</string>
    <string name="flag_text">Per favore descrivi perché stai segnalando quest\'app. Sarai reindirizzato su Reddit per inviare un messaggio ai moderatori di /r/Android</string>
    <plurals name="x_items">
        <item quantity="one">%s elemento</item>
        <item quantity="other">%s elementi</item>
    </plurals>
        <string-array name="themes">
        <item>Chiaro</item>
        <item>Scuro</item>
        <item>AMOLED</item>
    </string-array>
    <string-array name="themesValues">
        <item>0</item>
        <item>1</item>
        <item>2</item>
    </string-array>
 <string name="no_download_client">Nessun client disponibile per questo download</string>
 <string name="submitapp">Suggerisci un\'app</string>
</resources>