text:
from collections import namedtuple
from unittest import mock

from .common import AlwaysEqual, AttrDict, BuiltinTest
from .. import make_env

from bfg9000 import file_types, options as opts
from bfg9000.backends.make import syntax as make
from bfg9000.backends.ninja import syntax as ninja
from bfg9000.builtins import (compile, link, packages, project,  # noqa: F401
                              regenerate)
from bfg9000.environment import LibraryMode
from bfg9000.iterutils import listify, unlistify
from bfg9000.packages import CommonPackage
from bfg9000.path import Path, Root
from bfg9000.tools.msvc import MsvcBuilder

MockCompile = namedtuple('MockCompile', ['file'])

def mock_which(*args, **kwargs):
    return ['command']

def mock_execute(*args, **kwargs):
    return 'version'

class CompileTest(BuiltinTest):
    def output_file(self, name, step={}, lang='c++', mode=None, extra={}):
        compiler = getattr(self.env.builder(lang), mode or self.mode)
        step = AttrDict(**step)

        output = compiler.output_file(name, step)
        public_output = compiler.post_output(self.build, [], output, step)

        result = [i for i in listify(public_output or output) if not i.private]
        for i in result:
            for k, v in extra.items():
                setattr(i, k, v)
        return unlistify(result)

class TestObjectFile(CompileTest):
    mode = 'compiler'

    def setUp(self):
        super().setUp()
        with mock.patch('bfg9000.shell.which', mock_which), \
             mock.patch('bfg9000.shell.execute', mock_execute):
            self.env.builder('qrc')
            self.env.builder('qtmoc')

    def test_identity(self):
        expected = file_types.ObjectFile(Path('object', Root.srcdir), None)
        self.assertIs(self.context['object_file'](expected), expected)

    def test_src_file(self):
        expected = file_types.ObjectFile(
            Path('object', Root.srcdir),
            self.env.target_platform.object_format, 'c'
        )
        self.assertSameFile(self.context['object_file']('object'), expected)
        self.assertEqual(list(self.build.sources()), [self.bfgfile, expected])

        self.context['project'](lang='c++')
        expected.lang = 'c++'
        self.assertSameFile(self.context['object_file']('object'), expected)

    def test_no_dist(self):
        expected = file_types.ObjectFile(
            Path('object', Root.srcdir),
            self.env.target_platform.object_format, 'c'
        )
        self.assertSameFile(self.context['object_file']('object', dist=False),
                            expected)
        self.assertEqual(list(self.build.sources()), [self.bfgfile])

    def test_make_simple(self):
        result = self.context['object_file'](file='main.cpp')
        self.assertSameFile(result, self.output_file('main'))

        result = self.context['object_file']('object', 'main.cpp')
        self.assertSameFile(result, self.output_file('object'))

        src = self.context['source_file']('main.cpp')
        result = self.context['object_file']('object', src)
        self.assertSameFile(result, self.output_file('object'))

    def test_make_no_lang(self):
        result = self.context['object_file']('object', 'main.goofy',
                                             lang='c++')
        self.assertSameFile(result, self.output_file('object'))

        with self.assertRaises(ValueError):
            self.context['object_file']('object', 'main.goofy')

        src = self.context['source_file']('main.goofy')
        with self.assertRaises(ValueError):
            self.context['object_file']('object', src)

        with self.assertRaises(ValueError):
            self.context['object_file']('object', 'main.hpp')

    def test_make_override_lang(self):
        src = self.context['source_file']('main.c', 'c')
        result = self.context['object_file']('object', src, lang='c++')
        self.assertSameFile(result, self.output_file('object'))
        self.assertEqual(result.creator.compiler.lang, 'c++')

    def test_make_directory(self):
        object_file = self.context['object_file']

        result = object_file(file='main.cpp', directory='dir')
        self.assertSameFile(result, self.output_file('dir/main'))

        src = self.context['source_file']('main.cpp')
        result = object_file(file=src, directory='dir')
        self.assertSameFile(result, self.output_file('dir/main'))

        result = object_file(file='main.cpp', directory='dir/')
        self.assertSameFile(result, self.output_file('dir/main'))

        result = object_file(file='main.cpp', directory=Path('dir'))
        self.assertSameFile(result, self.output_file('dir/main'))

        result = object_file(file='dir1/main.cpp', directory='dir2')
        self.assertSameFile(result, self.output_file('dir2/dir1/main'))

        result = object_file('object', 'main.cpp', directory='dir')
        self.assertSameFile(result, self.output_file('object'))

        self.assertRaises(ValueError, object_file, file='main.cpp',
                          directory=Path('dir', Root.srcdir))

    def test_make_submodule(self):
        with self.context.push_path(Path('dir/build.bfg', Root.srcdir)):
            object_file = self.context['object_file']

            result = object_file(file='main.cpp')
            self.assertSameFile(result, self.output_file('dir/main'))
            result = object_file(file='sub/main.cpp')
            self.assertSameFile(result, self.output_file('dir/sub/main'))
            result = object_file(file='../main.cpp')
            self.assertSameFile(result, self.output_file('main'))

            result = object_file('object', 'main.cpp')
            self.assertSameFile(result, self.output_file('dir/object'))
            result = object_file('../object', 'main.cpp')
            self.assertSameFile(result, self.output_file('object'))

            result = object_file(file='main.cpp', directory='sub')
            self.assertSameFile(result, self.output_file('dir/sub/main'))
            result = object_file(file='foo/main.cpp', directory='sub')
            self.assertSameFile(result, self.output_file('dir/sub/foo/main'))
            result = object_file(file='../main.cpp', directory='sub')
            self.assertSameFile(result, self.output_file('dir/sub/PAR/main'))

            result = object_file(file='main.cpp', directory=Path('dir2'))
            self.assertSameFile(result, self.output_file('dir2/dir/main'))
            result = object_file(file='sub/main.cpp', directory=Path('dir2'))
            self.assertSameFile(result, self.output_file('dir2/dir/sub/main'))
            result = object_file(file='../main.cpp', directory=Path('dir2'))
            self.assertSameFile(result, self.output_file('dir2/main'))

            result = object_file(file='main.cpp', directory=Path('dir'))
            self.assertSameFile(result, self.output_file('dir/dir/main'))
            result = object_file(file='sub/main.cpp', directory=Path('dir'))
            self.assertSameFile(result, self.output_file('dir/dir/sub/main'))
            result = object_file(file='../main.cpp', directory=Path('dir'))
            self.assertSameFile(result, self.output_file('dir/main'))

    def test_includes(self):
        object_file = self.context['object_file']

        result = object_file(file='main.cpp', includes='include')
        self.assertEqual(result.creator.includes, [
            file_types.HeaderDirectory(Path('include', Root.srcdir))
        ])
        self.assertEqual(result.creator.include_deps, [])

        hdr = self.context['header_file']('include/main.hpp')
        result = object_file(file='main.cpp', includes=hdr)
        self.assertEqual(result.creator.includes, [
            file_types.HeaderDirectory(Path('include', Root.srcdir))
        ])
        self.assertEqual(result.creator.include_deps, [hdr])

        inc = self.context['header_directory']('include')
        inc.creator = 'foo'
        result = object_file(file='main.cpp', includes=inc)
        self.assertEqual(result.creator.includes, [inc])
        self.assertEqual(result.creator.include_deps, [inc])

    def test_include_order(self):
        fmt = self.env.target_platform.object_format
        incdir = opts.include_dir(file_types.HeaderDirectory(
            Path('include', Root.srcdir)
        ))
        pkg_incdir = opts.include_dir(file_types.HeaderDirectory(
            Path('/usr/include', Root.absolute)
        ))
        pkg = CommonPackage('pkg', format=fmt,
                            compile_options=opts.option_list(pkg_incdir))

        result = self.context['object_file'](file='main.cpp',
                                             includes='include', packages=pkg)
        self.assertEqual(result.creator.options,
                         opts.option_list(incdir, pkg_incdir))

    def test_libs(self):
        self.env.library_mode = LibraryMode(True, False)

        result = self.context['object_file'](file='main.java', libs='lib')
        self.assertEqual(result.creator.libs, [
            file_types.StaticLibrary(Path('lib', Root.srcdir), 'java')
        ])

    def test_pch(self):
        pch = file_types.PrecompiledHeader(Path('pch', Root.builddir), 'c')
        pch.object_file = 'foo'

        result = self.context['object_file'](file='main.cpp', pch=pch)
        self.assertIs(result.creator.pch, pch)

        self.assertRaises(TypeError, self.context['object_file'],
                          file='main.java', pch=pch)

    def test_auto_generate_source(self):
        result = self.context['object_file'](file='main.qrc')
        intermediate = result.creator.file
        self.assertSameFile(result, self.output_file('main'))
        self.assertSameFile(intermediate, file_types.SourceFile(
            Path('main.cpp'), lang='c++'
        ))
        self.assertSameFile(intermediate.creator.file, file_types.SourceFile(
            Path('main.qrc', Root.srcdir), lang='qrc'
        ))

        src = self.context['auto_file']('main.hpp', lang='qtmoc')
        result = self.context['object_file'](file=src)
        intermediate = result.creator.file
        self.assertSameFile(result, self.output_file('moc_main'))
        self.assertSameFile(intermediate, file_types.SourceFile(
            Path('moc_main.cpp', Root.builddir), lang='c++'
        ))
        self.assertSameFile(intermediate.creator.file, file_types.HeaderFile(
            Path('main.hpp', Root.srcdir), lang='qtmoc'
        ))

        result = self.context['object_file'](file='main.qrc', directory='dir')
        intermediate = result.creator.file
        self.assertSameFile(result, self.output_file('dir/main'))
        self.assertSameFile(intermediate, file_types.SourceFile(
            Path('dir/main.cpp'), lang='c++'
        ))
        self.assertSameFile(intermediate.creator.file, file_types.SourceFile(
            Path('main.qrc', Root.srcdir), lang='qrc'
        ))

    def test_extra_deps(self):
        dep = self.context['generic_file']('dep.txt')
        result = self.context['object_file'](file='main.cpp', extra_deps=[dep])
        self.assertSameFile(result, self.output_file('main'))
        self.assertEqual(result.creator.extra_deps, [dep])

    def test_make_no_name_or_file(self):
        self.assertRaises(TypeError, self.context['object_file'])

    def test_description(self):
        result = self.context['object_file'](
            file='main.cpp', description='my description'
        )
        self.assertEqual(result.creator.description, 'my description')

class TestPrecompiledHeader(CompileTest):
    class MockFile:
        def write(self, data):
            pass

    mode = 'pch_compiler'

    def output_file(self, name, pch_source='main.cpp', *args, **kwargs):
        pch_source_path = Path(name).parent().append(pch_source)
        step = {'pch_source': file_types.SourceFile(pch_source_path, 'c++')}
        return super().output_file(name, step, *args, **kwargs)

    def test_identity(self):
        ex = file_types.PrecompiledHeader(Path('header', Root.srcdir), None)
        self.assertIs(self.context['precompiled_header'](ex), ex)

    def test_src_file(self):
        expected = file_types.PrecompiledHeader(
            Path('header', Root.srcdir), 'c'
        )
        self.assertSameFile(self.context['precompiled_header']('header'),
                            expected)
        self.assertEqual(list(self.build.sources()), [self.bfgfile, expected])

        self.context['project'](lang='c++')
        expected.lang = 'c++'
        self.assertSameFile(self.context['precompiled_header']('header'),
                            expected)

    def test_no_dist(self):
        expected = file_types.PrecompiledHeader(
            Path('header', Root.srcdir), 'c'
        )
        self.assertSameFile(
            self.context['precompiled_header']('header', dist=False),
            expected
        )
        self.assertEqual(list(self.build.sources()), [self.bfgfile])

    def test_make_simple(self):
        with mock.patch('bfg9000.builtins.file_types.make_immediate_file',
                        return_value=self.MockFile()):
            pch = self.context['precompiled_header']

            result = pch(file='main.hpp')
            self.assertSameFile(result, self.output_file('main.hpp'))

            result = pch('object', 'main.hpp')
            self.assertSameFile(result, self.output_file('object'))

            src = self.context['header_file']('main.hpp')
            result = pch('object', src)
            self.assertSameFile(result, self.output_file('object'))

    def test_make_no_lang(self):
        with mock.patch('bfg9000.builtins.file_types.make_immediate_file',
                        return_value=self.MockFile()):
            pch = self.context['precompiled_header']

            result = pch('object', 'main.goofy', lang='c++')
            self.assertSameFile(result, self.output_file('object'))
            self.assertRaises(ValueError, pch, 'object', 'main.goofy')

            src = self.context['header_file']('main.goofy')
            self.assertRaises(ValueError, pch, 'object', src)

    def test_make_override_lang(self):
        with mock.patch('bfg9000.builtins.file_types.make_immediate_file',
                        return_value=self.MockFile()):
            pch = self.context['precompiled_header']

            src = self.context['header_file']('main.h', 'c')
            result = pch('object', src, lang='c++')
            self.assertSameFile(result, self.output_file('object'))
            self.assertEqual(result.creator.compiler.lang, 'c++')

    def test_make_directory(self):
        with mock.patch('bfg9000.builtins.file_types.make_immediate_file',
                        return_value=self.MockFile()):
            pch = self.context['precompiled_header']

            result = pch(file='main.hpp', directory='dir')
            self.assertSameFile(result, self.output_file('dir/main.hpp'))

            src = self.context['header_file']('main.hpp')
            result = pch(file=src, directory='dir')
            self.assertSameFile(result, self.output_file('dir/main.hpp'))

            result = pch(file='main.hpp', directory='dir/')
            self.assertSameFile(result, self.output_file('dir/main.hpp'))

            result = pch(file='main.hpp', directory=Path('dir'))
            self.assertSameFile(result, self.output_file('dir/main.hpp'))

            result = pch(file='dir1/main.hpp', directory='dir2')
            self.assertSameFile(result, self.output_file('dir2/dir1/main.hpp'))

            result = pch('object', 'main.hpp', directory='dir')
            self.assertSameFile(result, self.output_file('object'))

            self.assertRaises(ValueError, pch, file='main.hpp',
                              directory=Path('dir', Root.srcdir))

    def test_make_submodule(self):
        with self.context.push_path(Path('dir/build.bfg', Root.srcdir)):
            pch = self.context['precompiled_header']

            res = pch(file='main.hpp')
            self.assertSameFile(res, self.output_file('dir/main.hpp'))
            res = pch(file='sub/main.hpp')
            self.assertSameFile(res, self.output_file('dir/sub/main.hpp'))
            res = pch(file='../main.hpp')
            self.assertSameFile(res, self.output_file('main.hpp'))

            res = pch('object', 'main.hpp')
            self.assertSameFile(res, self.output_file('dir/object'))
            res = pch('../object', 'main.hpp')
            self.assertSameFile(res, self.output_file('object'))

            res = pch(file='main.hpp', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/main.hpp'))
            res = pch(file='foo/main.hpp', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/foo/main.hpp'))
            res = pch(file='../main.hpp', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/PAR/main.hpp'))

            res = pch(file='main.hpp', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/dir/main.hpp'))
            res = pch(file='sub/main.hpp', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/dir/sub/main.hpp'))
            res = pch(file='../main.hpp', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/main.hpp'))

            res = pch(file='main.hpp', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/dir/main.hpp'))
            res = pch(file='sub/main.hpp', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/dir/sub/main.hpp'))
            res = pch(file='../main.hpp', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/main.hpp'))

    def test_extra_deps(self):
        dep = self.context['generic_file']('dep.txt')
        with mock.patch('bfg9000.builtins.file_types.make_immediate_file',
                        return_value=self.MockFile()):
            pch = self.context['precompiled_header']

            result = pch(file='main.hpp', extra_deps=[dep])
            self.assertSameFile(result, self.output_file('main.hpp'))
            self.assertEqual(result.creator.extra_deps, [dep])

    def test_make_no_name_or_file(self):
        self.assertRaises(TypeError, self.context['precompiled_header'])

    def test_description(self):
        result = self.context['precompiled_header'](
            file='main.hpp', description='my description'
        )
        self.assertEqual(result.creator.description, 'my description')

class TestGeneratedSource(CompileTest):
    mode = 'transpiler'

    def setUp(self):
        super().setUp()
        with mock.patch('bfg9000.shell.which', mock_which), \
             mock.patch('bfg9000.shell.execute', mock_execute):
            self.env.builder('qrc')

    def output_file(self, name, step={}, lang='qrc', *args, **kwargs):
        return super().output_file(name, step, lang, *args, **kwargs)

    def test_make_simple(self):
        result = self.context['generated_source'](file='file.qrc')
        self.assertSameFile(result, self.output_file('file.cpp'))

        result = self.context['generated_source']('file.qrc')
        self.assertSameFile(result, self.output_file('file.cpp'))

        result = self.context['generated_source']('name.cpp', 'file.qrc')
        self.assertSameFile(result, self.output_file('name.cpp'))

        src = self.context['source_file']('file.qrc')
        result = self.context['generated_source']('name.cpp', src)
        self.assertSameFile(result, self.output_file('name.cpp'))

    def test_make_no_lang(self):
        gen_src = self.context['generated_source']
        result = gen_src('file.cpp', 'file.goofy', lang='qrc')
        self.assertSameFile(result, self.output_file('file.cpp'))

        self.assertRaises(ValueError, gen_src, 'file.cpp', 'file.goofy')

        src = self.context['source_file']('file.goofy')
        self.assertRaises(ValueError, gen_src, 'file.cpp', src)

    def test_make_override_lang(self):
        src = self.context['source_file']('main.ui', 'qtui')
        result = self.context['generated_source']('main.cpp', src, lang='qrc')
        self.assertSameFile(result, self.output_file('main.cpp'))
        self.assertEqual(result.creator.compiler.lang, 'qrc')

    def test_make_directory(self):
        gen_src = self.context['generated_source']

        res = gen_src(file='main.qrc', directory='dir')
        self.assertSameFile(res, self.output_file('dir/main.cpp'))

        src = self.context['source_file']('main.qrc')
        res = gen_src(file=src, directory='dir')
        self.assertSameFile(res, self.output_file('dir/main.cpp'))

        res = gen_src(file='main.qrc', directory='dir/')
        self.assertSameFile(res, self.output_file('dir/main.cpp'))

        res = gen_src(file='main.qrc', directory=Path('dir'))
        self.assertSameFile(res, self.output_file('dir/main.cpp'))

        res = gen_src(file='dir1/main.qrc', directory='dir2')
        self.assertSameFile(res, self.output_file('dir2/dir1/main.cpp'))

        res = gen_src('name.cpp', 'main.qrc', directory='dir')
        self.assertSameFile(res, self.output_file('name.cpp'))

        self.assertRaises(ValueError, gen_src, file='main.qrc',
                          directory=Path('dir', Root.srcdir))

    def test_make_submodule(self):
        with self.context.push_path(Path('dir/build.bfg', Root.srcdir)):
            gen_src = self.context['generated_source']

            res = gen_src(file='main.qrc')
            self.assertSameFile(res, self.output_file('dir/main.cpp'))
            res = gen_src(file='sub/main.qrc')
            self.assertSameFile(res, self.output_file('dir/sub/main.cpp'))
            res = gen_src(file='../main.qrc')
            self.assertSameFile(res, self.output_file('main.cpp'))

            res = gen_src('name.cpp', 'main.qrc')
            self.assertSameFile(res, self.output_file('dir/name.cpp'))
            res = gen_src('../name.cpp', 'main.qrc')
            self.assertSameFile(res, self.output_file('name.cpp'))

            res = gen_src(file='main.qrc', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/main.cpp'))
            res = gen_src(file='foo/main.qrc', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/foo/main.cpp'))
            res = gen_src(file='../main.qrc', directory='sub')
            self.assertSameFile(res, self.output_file('dir/sub/PAR/main.cpp'))

            res = gen_src(file='main.qrc', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/dir/main.cpp'))
            res = gen_src(file='sub/main.qrc', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/dir/sub/main.cpp'))
            res = gen_src(file='../main.qrc', directory=Path('dir2'))
            self.assertSameFile(res, self.output_file('dir2/main.cpp'))

            res = gen_src(file='main.qrc', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/dir/main.cpp'))
            res = gen_src(file='sub/main.qrc', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/dir/sub/main.cpp'))
            res = gen_src(file='../main.qrc', directory=Path('dir'))
            self.assertSameFile(res, self.output_file('dir/main.cpp'))

    def test_description(self):
        result = self.context['generated_source'](file='main.qrc',
                                                  description='my description')
        self.assertEqual(result.creator.description, 'my description')

    def test_extra_deps(self):
        dep = self.context['generic_file']('dep.txt')
        result = self.context['generated_source'](file='file.qrc',
                                                  extra_deps=[dep])
        self.assertSameFile(result, self.output_file('file.cpp'))
        self.assertEqual(result.creator.extra_deps, [dep])

class TestObjectFiles(BuiltinTest):
    def make_file_list(self, make_src=False, prefix=''):
        files = [file_types.ObjectFile(Path(i, Root.srcdir), None)
                 for i in [prefix + 'obj1', prefix + 'obj2']]
        if make_src:
            src_files = [file_types.SourceFile(Path(i, Root.srcdir), None)
                         for i in [prefix + 'src1', prefix + 'src2']]
            for f, s in zip(files, src_files):
                f.creator = MockCompile(s)

        file_list = self.context['object_files'](files)

        if make_src:
            return file_list, files, src_files
        return file_list, files

    def test_initialize(self):
        file_list, files = self.make_file_list()
        self.assertEqual(list(file_list), files)

    def test_getitem_index(self):
        file_list, files = self.make_file_list()
        self.assertEqual(file_list[0], files[0])

    def test_getitem_string(self):
        file_list, files, src_files = self.make_file_list(True)
        self.assertEqual(file_list['src1'], files[0])

    def test_getitem_string_submodule(self):
        file_list, files, src_files = self.make_file_list(True, 'dir/')
        self.assertEqual(file_list['dir/src1'], files[0])
        with self.context.push_path(Path('dir/build.bfg', Root.srcdir)):
            self.assertEqual(file_list['src1'], files[0])

    def test_getitem_path(self):
        file_list, files, src_files = self.make_file_list(True)
        self.assertEqual(file_list[src_files[0].path], files[0])

    def test_getitem_file(self):
        file_list, files, src_files = self.make_file_list(True)
        self.assertEqual(file_list[src_files[0]], files[0])

    def test_getitem_not_found(self):
        file_list, files, src_files = self.make_file_list(True)
        self.assertRaises(IndexError, lambda: file_list[2])
        self.assertRaises(IndexError, lambda: file_list['src3'])
        self.assertRaises(IndexError, lambda: file_list[Path(
            'src3', Root.srcdir
        )])

class TestGeneratedSources(TestObjectFiles):
    def setUp(self):
        super().setUp()
        with mock.patch('bfg9000.shell.which', mock_which), \
             mock.patch('bfg9000.shell.execute', mock_execute):
            self.env.builder('qrc')

    def make_file_list(self, return_src=False, prefix=''):
        files = [file_types.SourceFile(Path(i, Root.builddir), 'c++')
                 for i in [prefix + 'src1.cpp', prefix + 'src2.cpp']]
        src_files = [file_types.SourceFile(Path(i, Root.srcdir), 'qrc')
                     for i in [prefix + 'src1', prefix + 'src2']]

        file_list = self.context['generated_sources'](src_files)

        if return_src:
            return file_list, files, src_files
        return file_list, files

class TestMakeBackend(BuiltinTest):
    def test_simple(self):
        makefile = make.Makefile(None)
        src = self.context['source_file']('main.cpp')
        result = self.context['object_file'](file=src)

        with mock.patch.object(make.Makefile, 'rule') as mrule, \
             mock.patch('logging.log'):
            compile.make_compile(result.creator, self.build, makefile,
                                 self.env)
            mrule.assert_called_once_with(
                result, [src], [], AlwaysEqual(), AlwaysEqual(), None
            )

    def test_dir_sentinel(self):
        makefile = make.Makefile(None)
        src = self.context['source_file']('dir/main.cpp')
        result = self.context['object_file'](file=src)

        with mock.patch.object(make.Makefile, 'rule') as mrule, \
             mock.patch('logging.log'):
            compile.make_compile(result.creator, self.build, makefile,
                                 self.env)
            mrule.assert_called_once_with(
                result, [src], [Path('dir/.dir')], AlwaysEqual(),
                AlwaysEqual(), None,
            )

    def test_extra_deps(self):
        makefile = make.Makefile(None)
        dep = self.context['generic_file']('dep.txt')
        src = self.context['source_file']('main.cpp')
        result = self.context['object_file'](file=src, extra_deps=dep)

        with mock.patch.object(make.Makefile, 'rule'), \
             mock.patch('logging.log'):
            compile.make_compile(result.creator, self.build, makefile,
                                 self.env)
            makefile.rule.assert_called_once_with(
                result, [src, dep], [], AlwaysEqual(), AlwaysEqual(), None,
            )

    def test_local_options(self):
        env = make_env('winnt', clear_variables=True,
                       variables={'CXX': 'nonexist'})
        build, context = self._make_context(env)
        with mock.patch('bfg9000.tools.c_family._builders', (MsvcBuilder,)), \
             mock.patch('logging.log'):
            context['global_options'](opts.debug(), lang='c++')
            src = context['source_file']('main.cpp')
            result = context['object_file'](file=src, options=[opts.static()])

        makefile = make.Makefile(None)
        with mock.patch.object(make.Makefile, 'rule') as mrule, \
             mock.patch.object(make.Makefile, 'variable',
                               wraps=makefile.variable) as mvar, \
             mock.patch('logging.log'):
            compile.make_compile(result.creator, build, makefile, env)
            mrule.assert_called_once_with(result, [src], [], AlwaysEqual(), {
                make.var('CXXFLAGS'): [make.var('GLOBAL_CXXFLAGS'), '/MTd']
            }, None)
            mvar.assert_any_call('GLOBAL_CXXFLAGS', ['/Zi'],
                                 make.Section.flags, True)

class TestNinjaBackend(BuiltinTest):
    def test_simple(self):
        ninjafile = ninja.NinjaFile(None)
        src = self.context['source_file']('main.cpp')
        result = self.context['object_file'](file=src)

        with mock.patch.object(ninja.NinjaFile, 'build') as mbuild:
            compile.ninja_compile(result.creator, self.build, ninjafile,
                                  self.env)
            mbuild.assert_called_once_with(
                output=[result], rule='cxx', inputs=[src], implicit=[],
                variables=AlwaysEqual(),
            )

    def test_extra_deps(self):
        ninjafile = ninja.NinjaFile(None)
        dep = self.context['generic_file']('dep.txt')
        src = self.context['source_file']('main.cpp')
        result = self.context['object_file'](file=src, extra_deps=dep)

        with mock.patch.object(ninja.NinjaFile, 'build') as mbuild:
            compile.ninja_compile(result.creator, self.build, ninjafile,
                                  self.env)
            mbuild.assert_called_once_with(
                output=[result], rule='cxx', inputs=[src], implicit=[dep],
                variables=AlwaysEqual(),
            )

    def test_local_options(self):
        env = make_env('winnt', clear_variables=True,
                       variables={'CXX': 'nonexist'})
        build, context = self._make_context(env)
        with mock.patch('bfg9000.tools.c_family._builders', (MsvcBuilder,)), \
             mock.patch('logging.log'):
            context['global_options'](opts.debug(), lang='c++')
            src = context['source_file']('main.cpp')
            result = context['object_file'](file=src, options=[opts.static()])

        ninjafile = ninja.NinjaFile(None)
        with mock.patch.object(ninja.NinjaFile, 'build') as mbuild, \
             mock.patch.object(ninja.NinjaFile, 'variable',
                               wraps=ninjafile.variable) as mvar:
            compile.ninja_compile(result.creator, build, ninjafile, env)
            mbuild.assert_called_once_with(
                output=[result], rule='cxx', inputs=[src], implicit=[],
                variables={ninja.var('cxxflags'): [
                    ninja.var('global_cxxflags'), '/MTd'
                ]},
            )
            mvar.assert_any_call('global_cxxflags', ['/Zi'],
                                 ninja.Section.flags, True)


text:
var dbURI    = 'mongodb://localhost/expressTest'
    , should   = require('chai').should()
    , mongoose = require('mongoose')
    , Dummy    = mongoose.model('Dummy', new mongoose.Schema({companyName:String, rate:Number}))
    , clearDB  = require('mocha-mongoose')(dbURI)
    ;

describe("Users -> Companies", function() {
    beforeEach(function(done) {
        if (mongoose.connection.db) return done();

        mongoose.connect(dbURI, done);
    });

    it("can be saved", function(done) {
        new Dummy({companyName: 'AVIVA'}).save(done);
    });

    it("can be listed", function(done) {
        new Dummy({companyName: 'AVIVA', rate: 7}).save(function(err, model){
            if (err) return done(err);

            new Dummy({companyName: 'Fernando Llodra', rate: 7}).save(function(err, model){
                if (err) return done(err);

                Dummy.find({}, function(err, docs){
                    if (err) return done(err);

                    // without clearing the DB between specs, this would be 3
                    docs.length.should.equal(2);
                    done();
                });
            });
        });
    });

    it("can clear the DB on demand", function(done) {
        new Dummy({companyName: 'MICROSOFT'}).save(function(err, model){
            if (err) return done(err);

            clearDB(function(err){
                if (err) return done(err);

                Dummy.find({}, function(err, docs){
                    if (err) return done(err);

                    console.log(docs);

                    docs.length.should.equal(0);
                    done();
                });
            });
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
package cgeo.geocaching.utils;

import org.junit.Test;

import static org.assertj.core.api.Java6Assertions.assertThat;

public class CalculationUtilsTest {

    private static double eval(final String expression) {
        return new CalculationUtils(expression).eval();
    }

    @Test
    public void testEval() {
        assertThat(eval("-2.5 + 3 * (4-1) + 3^3")).isEqualTo(33.5d);
    }

    @Test
    public void testEvalSqrt() {
        assertThat(eval("sqrt(9)")).isEqualTo(3d);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEvalUnknownOperator() {
        eval("2 & 5");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEvalUnknownFunction() {
        eval("uknown(42)");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testUnbalancedParentheses() {
        eval("3 * (2 + 4 * 2");
    }

}


text:
#define _COLLECTION_ATTRIBUTES [::Platform::Metadata::RuntimeClassName] [::Windows::Foundation::Metadata::Default]

#define _COLLECTION_TRANSLATE } \
catch( const ::std::bad_alloc& ){throw ref new OutOfMemoryException;} \
catch( const ::std::exception& ){throw ref new FailureException;}

#ifndef _COLLECTION_WUXI
#define _COLLECTION_WUXI 1
#endif

#ifdef _WIN64
#pragma pack( push, 16 )
#else
#pragma pack( push, 8 )
#endif

#pragma warning( push, 4 )
#pragma warning( disable: 4451 )

namespace Platform { namespace Collections {

	namespace Details {

		template<typename T, typename E>
		inline bool DequeIndexOf( const ::std::deque<typename Wrap<T>::type>& v, T value, unsigned int * index )
		{
			auto pred = [&]( const typename Wrap<T>::type& elem ) { return E()( Unwrap( elem ), value ); };

			*index = static_cast<unsigned int>( ::std::find_if( v.begin(), v.end(), pred ) - v.begin() );

			return *index < v.size();
		}

		template<typename T>
		inline unsigned int DequeGetMany( const ::std::deque<typename Wrap<T>::type>& v, unsigned int startIndex, WriteOnlyArray<T>^ dest )
		{
			unsigned int capacity = dest->Length;

			unsigned int actual = static_cast<unsigned int>( v.size() ) - startIndex;

			if( actual > capacity )
			{
				actual = capacity;
			}

			for( unsigned int i = 0; i < actual; ++i )
			{
				dest->set( i, Unwrap( v[startIndex + i] ) );
			}

			return actual;
		}

#if _COLLECTION_WUXI
		template<typename T, typename E>
		inline bool DequeBindableIndexOf( ::std::false_type, const ::std::deque<typename Wrap<T>::type>& v, Object^ o, unsigned int * index )
		{
			IBox<T>^ ib = dynamic_cast<IBox<T>^>( o );

			if( ib )
			{
				return DequeIndexOf<T, E>( v, ib->Value, index );
			}
			else
			{
				*index = static_cast<unsigned int>( v.size() );
				return false;
			}
		}

		template<typename T, typename E>
		inline bool DequeBindableIndexOf( ::std::true_type, const ::std::deque<typename Wrap<T>::type>& v, Object^ o, unsigned int * index )
		{
			T t = dynamic_cast<T>( o );

			if( !o || t )
			{
				return DequeIndexOf<T, E>( v, t, index );
			}
			else
			{
				*index = static_cast<unsigned int>( v.size() );
				return false;
			}
		}

		template <typename T, typename E>
		inline bool DequeBindableIndexOf( const ::std::deque<typename Wrap<T>::type>& v, Object^ o, unsigned int * index )
		{
			return DequeBindableIndexOf<T, E>( is_hat<T>(), v, o, index );
		}
#endif

		template<typename T>
		ref class IteratorForDequeView sealed
			: public _COLLECTION_ATTRIBUTES WFC::IIterator<T>
#if _COLLECTION_WUXI
			, public WUXI::IBindableIterator
#endif
		{
		private:
			typedef ::std::deque<typename Wrap<T>::type> WrappedDeque;
			typedef WFC::IIterator<T> WFC_Base;

#if _COLLECTION_WUXI
			typedef WUXI::IBindableIterator WUXI_Base;
#endif

		internal:
			IteratorForDequeView( const ::std::shared_ptr<unsigned int>& ctr, const ::std::shared_ptr<WrappedDeque>& vec )
				: m_ctr( ctr )
				, m_vec( vec )
				, m_good_ctr( *ctr )
				, m_index( 0 )
			{ }

		public:
			virtual property T Current
			{
				virtual T get() = WFC_Base::Current::get
				{
					ValidateCounter( m_ctr, m_good_ctr );

					ValidateBounds( m_index < m_vec->size() );

					return Unwrap( ( *m_vec )[m_index] );
				}
			}

			virtual property bool HasCurrent
			{
				virtual bool get()
				{
					ValidateCounter( m_ctr, m_good_ctr );

					return m_index < m_vec->size();
				}
			}

			virtual bool MoveNext()
			{
				ValidateCounter( m_ctr, m_good_ctr );

				ValidateBounds( m_index < m_vec->size() );

				++m_index;
				return m_index < m_vec->size();
			}

			virtual unsigned int GetMany( WriteOnlyArray<T>^ dest )
			{
				ValidateCounter( m_ctr, m_good_ctr );

				unsigned int actual = DequeGetMany( *m_vec, m_index, dest );

				m_index += actual;

				return actual;
			}

		private:

#if _COLLECTION_WUXI
			virtual Object^ BindableCurrent() = WUXI_Base::Current::get
			{
				return Current;
			}
#endif

			::std::shared_ptr<unsigned int> m_ctr;
			::std::shared_ptr<WrappedDeque> m_vec;
			unsigned int m_good_ctr;
			unsigned int m_index;
		};

	}

	template<typename T, typename E = ::std::equal_to<T>, bool = __is_valid_winrt_type( T )> ref class Deque;
	template<typename T, typename E = ::std::equal_to<T>, bool = __is_valid_winrt_type( T )> ref class DequeView;

	template<typename T, typename E>
	ref class DequeView<T, E, false>
	{
		static_assert( Details::AlwaysFalse<T>::value, "Platform::Collections::DequeView<T, E> requires T to be a valid Windows Runtime type." );
	};

	template<typename T, typename E, bool>
	ref class DequeView sealed
		: public _COLLECTION_ATTRIBUTES Details::WFC::IVectorView<T>
#if _COLLECTION_WUXI
		, public Details::WUXI::IBindableVectorView
#endif
	{
	private:
		typedef ::std::deque<typename Details::Wrap<T>::type> WrappedDeque;
		typedef Details::WFC::IVectorView<T> WFC_Base;

#if _COLLECTION_WUXI
		typedef Details::WUXI::IBindableVectorView WUXI_Base;
#endif

	internal:
		DequeView()
		{
			Details::Init( m_ctr, m_vec );

			m_good_ctr = 0;
		}

		explicit DequeView( unsigned int size )
		{
			Details::Init( m_ctr, m_vec, size );

			m_good_ctr = 0;
		}

		DequeView( unsigned int size, T value )
		{
			Details::Init( m_ctr, m_vec, size, Details::MakeWrap( value ) );

			m_good_ctr = 0;
		}

		template<typename U>
		explicit DequeView( const ::std::deque<U>& v, typename Details::VectorEnableIf<T, U>::type = nullptr )
		{
			Details::Init( m_ctr, m_vec, v.begin(), v.end() );

			m_good_ctr = 0;
		}

		template<typename U>
		explicit DequeView( ::std::deque<U>&& v, typename Details::VectorEnableIf<T, U>::type = nullptr )
		{
			Details::InitMoveVector( m_ctr, m_vec, ::std::move( v ) );

			m_good_ctr = 0;
		}

		DequeView( const T * ptr, unsigned int size )
		{
			Details::Init( m_ctr, m_vec, ptr, ptr + size );

			m_good_ctr = 0;
		}

		template<size_t N>
		explicit DequeView( const T( &arr )[N] )
		{
			Details::Init( m_ctr, m_vec, arr, arr + N );

			m_good_ctr = 0;
		}

		template<size_t N>
		explicit DequeView( const ::std::array<T, N>& a )
		{
			Details::Init( m_ctr, m_vec, a.begin(), a.end() );

			m_good_ctr = 0;
		}

		explicit DequeView( const Array<T>^ arr )
		{
			Details::Init( m_ctr, m_vec, arr->begin(), arr->end() );

			m_good_ctr = 0;
		}

		template<typename InIt>
		DequeView( InIt first, InIt last )
		{
			Details::Init( m_ctr, m_vec, first, last );

			m_good_ctr = 0;
		}

		DequeView( ::std::initializer_list<T> il )
		{
			Details::Init( m_ctr, m_vec, il.begin(), il.end() );

			m_good_ctr = 0;
		}

	public:
		virtual Details::WFC::IIterator<T>^ First() = WFC_Base::First
		{
			Details::ValidateCounter( m_ctr, m_good_ctr );

			return ref new Details::IteratorForDequeView<T>( m_ctr, m_vec );
		}

		virtual T GetAt( unsigned int index ) = WFC_Base::GetAt
		{
			Details::ValidateCounter( m_ctr, m_good_ctr );

			Details::ValidateBounds( index < m_vec->size() );

			return Details::Unwrap( ( *m_vec )[index] );
		}

		virtual property unsigned int Size
		{
			virtual unsigned int get()
			{
				Details::ValidateCounter( m_ctr, m_good_ctr );

				return static_cast<unsigned int>( m_vec->size() );
			}
		}

		virtual bool IndexOf( T value, unsigned int * index ) = WFC_Base::IndexOf
		{
			*index = 0;

			Details::ValidateCounter( m_ctr, m_good_ctr );

			return Details::DequeIndexOf<T, E>( *m_vec, value, index );
		}

		virtual unsigned int GetMany( unsigned int startIndex, WriteOnlyArray<T>^ dest )
		{
			Details::ValidateCounter( m_ctr, m_good_ctr );

			Details::ValidateBounds( startIndex <= m_vec->size() );

			return Details::DequeGetMany( *m_vec, startIndex, dest );
		}

	private:
		friend ref class Deque<T, E>;

		DequeView( const ::std::shared_ptr<unsigned int>& ctr, const ::std::shared_ptr<WrappedDeque>& vec )
			: m_ctr( ctr )
			, m_vec( vec )
			, m_good_ctr( *ctr )
		{ }

#if _COLLECTION_WUXI
		virtual Details::WUXI::IBindableIterator^ BindableFirst() = WUXI_Base::First
		{
			return safe_cast<Details::WUXI::IBindableIterator^>( First() );
		}

		virtual Object^ BindableGetAt( unsigned int index ) = WUXI_Base::GetAt
		{
			return GetAt( index );
		}

		virtual bool BindableIndexOf( Object^ value, unsigned int * index ) = WUXI_Base::IndexOf
		{
			*index = 0;

			Details::ValidateCounter( m_ctr, m_good_ctr );

			return Details::DequeBindableIndexOf<T, E>( *m_vec, value, index );
		}
#endif

		::std::shared_ptr<unsigned int> m_ctr;
		::std::shared_ptr<WrappedDeque> m_vec;
		unsigned int m_good_ctr;
	};

	template<typename T, typename E>
	ref class Deque<T, E, false>
	{
		static_assert( Details::AlwaysFalse<T>::value, "Platform::Collections::Deque<T, E> requires T to be a valid Windows Runtime type." );
	};

	template<typename T, typename E, bool>
	ref class Deque sealed
		: public _COLLECTION_ATTRIBUTES Details::WFC::IObservableVector<T>
#if _COLLECTION_WUXI
		, public Details::WUXI::IBindableObservableVector
#endif
	{
	private:
		typedef ::std::deque<typename Details::Wrap<T>::type> WrappedDeque;
		typedef Details::WFC::IObservableVector<T> WFC_Base;
		typedef Details::WFC::VectorChangedEventHandler<T> WFC_Handler;

#if _COLLECTION_WUXI
		typedef Details::WUXI::IBindableObservableVector WUXI_Base;
		typedef Details::WUXI::BindableVectorChangedEventHandler WUXI_Handler;
#endif

	internal:
		Deque()
		{
			Details::Init( m_ctr, m_vec );

			m_observed = false;
		}

		explicit Deque( unsigned int size )
		{
			Details::Init( m_ctr, m_vec, size );

			m_observed = false;
		}

		Deque( unsigned int size, T value )
		{
			Details::Init( m_ctr, m_vec, size, Details::MakeWrap( value ) );

			m_observed = false;
		}

		template<typename U>
		explicit Deque( const ::std::deque<U>& v, typename Details::VectorEnableIf<T, U>::type = nullptr )
		{
			Details::Init( m_ctr, m_vec, v.begin(), v.end() );

			m_observed = false;
		}

		template<typename U>
		explicit Deque( ::std::deque<U>&& v, typename Details::VectorEnableIf<T, U>::type = nullptr )
		{
			Details::InitMoveVector( m_ctr, m_vec, ::std::move( v ) );

			m_observed = false;
		}

		Deque( const T * ptr, unsigned int size )
		{
			Details::Init( m_ctr, m_vec, ptr, ptr + size );

			m_observed = false;
		}

		template<size_t N>
		explicit Deque( const T( &arr )[N] )
		{
			Details::Init( m_ctr, m_vec, arr, arr + N );

			m_observed = false;
		}

		template<size_t N>
		explicit Deque( const ::std::array<T, N>& a )
		{
			Details::Init( m_ctr, m_vec, a.begin(), a.end() );

			m_observed = false;
		}

		explicit Deque( const Array<T>^ arr )
		{
			Details::Init( m_ctr, m_vec, arr->begin(), arr->end() );

			m_observed = false;
		}

		template<typename InIt>
		Deque( InIt first, InIt last )
		{
			Details::Init( m_ctr, m_vec, first, last );

			m_observed = false;
		}

		Deque( ::std::initializer_list<T> il )
		{
			Details::Init( m_ctr, m_vec, il.begin(), il.end() );

			m_observed = false;
		}

	public:
		virtual Details::WFC::IIterator<T>^ First() = WFC_Base::First
		{
			return ref new Details::IteratorForDequeView<T>( m_ctr, m_vec );
		}

		virtual T GetAt( unsigned int index ) = WFC_Base::GetAt
		{
			Details::ValidateBounds( index < m_vec->size() );

			return Details::Unwrap( ( *m_vec )[index] );
		}

		virtual property unsigned int Size
		{
			virtual unsigned int get()
			{
				return static_cast<unsigned int>( m_vec->size() );
			}
		}

		virtual bool IndexOf( T value, unsigned int * index ) = WFC_Base::IndexOf
		{
			*index = 0;

			return Details::DequeIndexOf<T, E>( *m_vec, value, index );
		}

		virtual unsigned int GetMany( unsigned int startIndex, WriteOnlyArray<T>^ dest )
		{
			Details::ValidateBounds( startIndex <= m_vec->size() );

			return Details::DequeGetMany( *m_vec, startIndex, dest );
		}

		virtual Details::WFC::IVectorView<T>^ GetView() = WFC_Base::GetView
		{
			return ref new DequeView<T, E>( m_ctr, m_vec );
		}

		virtual void SetAt( unsigned int index, T item ) = WFC_Base::SetAt
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateBounds( index < m_vec->size() );

				( *m_vec )[index] = item;

				NotifyChanged( index );
			_COLLECTION_TRANSLATE
		}

		virtual void InsertAt( unsigned int index, T item ) = WFC_Base::InsertAt
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateBounds( index <= m_vec->size() );

				Details::ValidateSize( m_vec->size() + 1 );

				Emplace( m_vec->begin() + index, item, ::std::is_same<T, bool>() );

				NotifyInserted( index );
			_COLLECTION_TRANSLATE
		}

		void Prepend( T item )
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				size_t n = m_vec->size();

				Details::ValidateSize( n + 1 );

				EmplaceFront( item, ::std::is_same<T, bool>() );

				NotifyInserted( static_cast<unsigned int>( 0 ) );
			_COLLECTION_TRANSLATE
		}

		virtual void Append( T item ) = WFC_Base::Append
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				size_t n = m_vec->size();

				Details::ValidateSize( n + 1 );

				EmplaceBack( item, ::std::is_same<T, bool>() );

				NotifyInserted( static_cast<unsigned int>( n ) );
			_COLLECTION_TRANSLATE
		}

		virtual void RemoveAt( unsigned int index )
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateBounds( index < m_vec->size() );

				m_vec->erase( m_vec->begin() + index );

				NotifyRemoved( index );
			_COLLECTION_TRANSLATE
		}

		virtual void RemoveAtBegin()
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateBounds( !m_vec->empty() );

				m_vec->pop_front();

				NotifyRemoved( static_cast<unsigned int>( 0 ) );
			_COLLECTION_TRANSLATE
		}

		virtual void RemoveAtEnd()
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateBounds( !m_vec->empty() );

				m_vec->pop_back();

				NotifyRemoved( static_cast<unsigned int>( m_vec->size() ) );
			_COLLECTION_TRANSLATE
		}

		virtual void Clear()
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				m_vec->clear();

				NotifyReset();
			_COLLECTION_TRANSLATE
		}

		virtual void ReplaceAll( const Array<T>^ arr )
		{
			try
			{
				Details::IncrementCounter( m_ctr );

				Details::ValidateSize( arr->Length );

				m_vec->assign( arr->begin(), arr->end() );

				NotifyReset();
			_COLLECTION_TRANSLATE
		}

		virtual event WFC_Handler^ VectorChanged
		{
			virtual Details::Token add( WFC_Handler^ e ) = WFC_Base::VectorChanged::add
			{
				m_observed = true;
				return m_wfc_event += e;
			}
			virtual void remove( Details::Token t ) = WFC_Base::VectorChanged::remove
			{
				m_wfc_event -= t;
			}
		};

	private:
		template<typename A, typename B>
		void Emplace( A&& a, B&& b, ::std::false_type )
		{
			m_vec->emplace( ::std::forward<A>( a ), ::std::forward<B>( b ) );
		}

		template<typename A, typename B>
		void Emplace( A&& a, B&& b, ::std::true_type )
		{
			m_vec->insert( ::std::forward<A>( a ), ::std::forward<B>( b ) );
		}

		template<typename A>
		void EmplaceFront( A&& a, ::std::false_type )
		{
			m_vec->emplace_front( ::std::forward<A>( a ) );
		}

		template<typename A>
		void EmplaceFront( A&& a, ::std::true_type )
		{
			m_vec->push_front( ::std::forward<A>( a ) );
		}

		template<typename A>
		void EmplaceBack( A&& a, ::std::false_type )
		{
			m_vec->emplace_back( ::std::forward<A>( a ) );
		}

		template<typename A>
		void EmplaceBack( A&& a, ::std::true_type )
		{
			m_vec->push_back( ::std::forward<A>( a ) );
		}

		void Notify( Details::WFC::CollectionChange change, unsigned int index )
		{
			if( m_observed )
			{
				auto args = ref new Details::VectorChangedEventArgs( change, index );
				m_wfc_event( this, args );

#if _COLLECTION_WUXI
				m_wuxi_event( this, args );
#endif
			}
		}

		void NotifyReset()
		{
			Notify( Details::WFC::CollectionChange::Reset, 0 );
		}

		void NotifyInserted( unsigned int index )
		{
			Notify( Details::WFC::CollectionChange::ItemInserted, index );
		}

		void NotifyRemoved( unsigned int index )
		{
			Notify( Details::WFC::CollectionChange::ItemRemoved, index );
		}

		void NotifyChanged( unsigned int index )
		{
			Notify( Details::WFC::CollectionChange::ItemChanged, index );
		}

#if _COLLECTION_WUXI
		virtual Details::WUXI::IBindableIterator^ BindableFirst() = WUXI_Base::First
		{
			return safe_cast<Details::WUXI::IBindableIterator^>( First() );
		}

		virtual Object^ BindableGetAt( unsigned int index ) = WUXI_Base::GetAt
		{
			return GetAt( index );
		}

		virtual bool BindableIndexOf( Object^ value, unsigned int * index ) = WUXI_Base::IndexOf
		{
			*index = 0;

			return Details::DequeBindableIndexOf<T, E>( *m_vec, value, index );
		}

		virtual Details::WUXI::IBindableVectorView^ BindableGetView() = WUXI_Base::GetView
		{
			return safe_cast<Details::WUXI::IBindableVectorView^>( GetView() );
		}

		virtual void BindableSetAt( unsigned int index, Object^ item ) = WUXI_Base::SetAt
		{
			SetAt( index, safe_cast<T>( item ) );
		}

		virtual void BindableInsertAt( unsigned int index, Object^ item ) = WUXI_Base::InsertAt
		{
			InsertAt( index, safe_cast<T>( item ) );
		}

		virtual void BindableAppend( Object^ item ) = WUXI_Base::Append
		{
			Append( safe_cast<T>( item ) );
		}

		virtual Details::Token BindableEventAdd( WUXI_Handler^ e ) = WUXI_Base::VectorChanged::add
		{
			m_observed = true;
			return m_wuxi_event += e;
		}

		virtual void BindableEventRemove( Details::Token t ) = WUXI_Base::VectorChanged::remove
		{
			m_wuxi_event -= t;
		}
#endif // _COLLECTION_WUXI

		::std::shared_ptr<unsigned int> m_ctr;
		::std::shared_ptr<WrappedDeque> m_vec;
		bool m_observed;

		event WFC_Handler^ m_wfc_event;

#if _COLLECTION_WUXI
		event WUXI_Handler^ m_wuxi_event;
#endif
	};

	namespace Details {

		template<typename T, typename I>
		inline ::std::deque<T> ToDeque( I^ v )
		{
			unsigned int size = v->Size;

			::std::deque<T> ret( size );

			for( unsigned int actual = 0; actual < size; )
			{
				Array<T>^ arr = ref new Array<T>( size - actual );

				unsigned int n = v->GetMany( actual, arr );

				if( n == 0 )
				{
					throw ref new FailureException;
				}

				::std::copy_n( arr->begin(), n, ret.begin() + actual );

				actual += n;
			}

			return ret;
		}

	}
} }

namespace Windows { namespace Foundation { namespace Collections {

	template<typename T>
	inline ::std::deque<T> to_deque( IVector<T>^ v )
	{
		return ::Platform::Collections::Details::ToDeque<T>( v );
	}

	template<typename T>
	inline ::std::deque<T> to_deque( IVectorView<T>^ v )
	{
		return ::Platform::Collections::Details::ToDeque<T>( v );
	}

} } }

#undef _COLLECTION_ATTRIBUTES
#undef _COLLECTION_TRANSLATE
#undef _COLLECTION_WUXI

#pragma warning(pop)
#pragma pack(pop)


text:
<component name="libraryTable">
  <library name="Maven: com.bedatadriven:jackson-datatype-jts:1.1-SNAPSHOT">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/bedatadriven/jackson-datatype-jts/1.1-SNAPSHOT/jackson-datatype-jts-1.1-SNAPSHOT.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/bedatadriven/jackson-datatype-jts/1.1-SNAPSHOT/jackson-datatype-jts-1.1-SNAPSHOT-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/bedatadriven/jackson-datatype-jts/1.1-SNAPSHOT/jackson-datatype-jts-1.1-SNAPSHOT-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
/// <reference path="../../typings/knockout/knockout.d.ts" />
/// <reference path="../System/Debug.ts" />
/// <reference path="../System/AdManager.ts" />
/// <reference path="../Support/AccessProviders.ts" />
/// <reference path="_Model.ts" />
/// <reference path="TetrisGame.ts" />
/// <reference path="Levels.ts" />
var Told;
(function (Told) {
    (function (TableMath) {
        (function (UI) {
            var MainViewModel = (function () {
                function MainViewModel(providers) {
                    var _this = this;
                    this.board = ko.observable(null);
                    //gameOverStars = ko.observable<boolean[]>([false, false, false]);
                    this.gameOverStarsClass = ko.observable("");
                    this.gameOverHasWon = ko.observable(false);
                    this.isGameOver = ko.observable(false);
                    this.isPaused = ko.observable(false);
                    this.shouldDisplayGameOver_ad = ko.observable(false);
                    this.shouldDisplayGameOver_normal = ko.computed(function () {
                        return !_this.shouldDisplayGameOver_ad();
                    }, this);
                    this.shouldDisplayGameMenu = ko.observable(false);
                    this.shouldDisplayGameOver = ko.computed(function () {
                        return _this.isGameOver() && !_this.shouldDisplayGameMenu();
                    }, this);
                    this.shouldDisplayGame = ko.computed(function () {
                        return !_this.isGameOver() && !_this.shouldDisplayGameMenu();
                    }, this);
                    this.menu = ko.observable({
                        shouldDisplayWorlds: ko.observable(true),
                        shouldDisplayLevels: ko.observable(false),
                        shouldDisplayUsers: ko.observable(false),
                        worlds: ko.observable([]),
                        levelsById: {},
                        currentWorld: ko.observable(null),
                        currentUser: ko.observable(""),
                        users: ko.observable([])
                    });
                    this._levelIndex = 0;
                    this.world = ko.observable(1);
                    //stage = ko.observable<number>(1);
                    this.level = ko.observable(1);
                    this._levels = Told.TableMath.Game.Levels.GetLevels();
                    this._isNewGame = true;
                    this.score = ko.observable(0);
                    this.scoreChange = ko.observable("");
                    this.scoreChangeClassName = ko.observable("scoreGood");
                    this.scoreChangeAtId = ko.observable("");
                    if (providers == null) {
                        providers = Told.TableMath.Data.createDefaultProviders();
                    }

                    this.providers = providers;

                    var self = this;

                    // Always set up a game to prevent errors
                    self._levelIndex = 0;
                    self.setupGame();

                    if (!self.providers.userSettings.hasModifiedUsers) {
                        if (self.providers.userSettings.currentUserState.levels.length === 0) {
                            // Do nothing else
                        } else {
                            self.showMenu();
                            self.changeWorld();
                        }
                    } else {
                        self.showMenu();
                        self.changeUser();
                    }
                }
                MainViewModel.prototype.pause = function (shouldPause) {
                    var self = this;
                    self.game.pause(shouldPause);
                    self.isPaused(self.game.isPaused);

                    Told.log("Pause", "" + self.isPaused(), true);
                };

                MainViewModel.prototype.showAd = function () {
                    var self = this;
                    self.shouldDisplayGameOver_ad(true);
                    Told.Ads.show(function () {
                        self.shouldDisplayGameOver_ad(false);
                    });
                };

                MainViewModel.prototype.menuChooseWorld = function (world) {
                    if (world.isLocked()) {
                        return;
                    }

                    var self = window['mainViewModel'];

                    self.menu().currentWorld(world);

                    self.menu().shouldDisplayWorlds(false);
                    self.menu().shouldDisplayLevels(true);
                    self.menu().shouldDisplayUsers(false);
                };

                MainViewModel.prototype.menuChooseLevel = function (level) {
                    if (level.isLocked()) {
                        return;
                    }

                    var self = window['mainViewModel'];

                    var lIndex = -1;

                    self._levels.forEach(function (l, index) {
                        if (l.id === level.levelId) {
                            lIndex = index;
                        }
                    });

                    self._levelIndex = lIndex;

                    self.setupGame();
                    self.shouldDisplayGameMenu(false);
                };

                MainViewModel.prototype.menuChooseUser = function (user) {
                    if (user.isEditing()) {
                        return;
                    }

                    Told.log("Menu", "menuChooseUser", true);

                    var self = window['mainViewModel'];
                    self.providers.userSettings.currentUserName = user.user();

                    //self.menu().currentUser(user.user());
                    //self.populateMenu();
                    // Reset menu for new user
                    self.showMenu();
                };

                MainViewModel.prototype.menuEditUser_Change = function (user, e) {
                    var newValue = (e || { currentTarget: {} }).currentTarget['value'];

                    if (user == null) {
                        return;
                    }

                    if (newValue === undefined) {
                        if (!user.isAddUser()) {
                            user.isEditing(false);
                            return;
                        } else {
                            newValue = "Player " + user.index;
                        }
                    }

                    Told.log("User", "userEditText changed", true);
                    Told.log("User", "userEditText changed: '" + newValue + "'", false);

                    var self = window['mainViewModel'];

                    var uList = self.providers.userSettings.userList;

                    if (user.isAddUser()) {
                        user.isAddUser(false);
                        uList.push(newValue);
                    } else {
                        var iUser = user.index;
                        uList[iUser] = newValue;
                    }

                    self.providers.userSettings.userList = uList;

                    user.user(newValue);
                    user.isEditing(false);
                    //self.menuChooseUser(user);
                };

                MainViewModel.prototype.menuEditUser = function (user) {
                    Told.log("Menu", "menuEditUser", true);

                    var self = window['mainViewModel'];
                    self.menu().users().forEach(function (u, i) {
                        if (i != self.menu().users().length - 1) {
                            self.menuEditUser_Change(u, null);
                        }
                    });

                    user.isEditing(true);
                };

                MainViewModel.prototype.menuAddUser = function (user) {
                    Told.log("Menu", "menuAddUser", true);

                    var self = window['mainViewModel'];

                    self.menu().users().push({
                        index: self.menu().users().length,
                        user: ko.observable("Player"),
                        userEditText: ko.observable("Player"),
                        isEditing: ko.observable(false),
                        isAddUser: ko.observable(true)
                    });

                    self.menu().users.valueHasMutated();

                    self.menuEditUser(user);
                };

                MainViewModel.prototype.showMenu = function () {
                    var self = this;
                    self.populateMenu();
                    self.shouldDisplayGameMenu(true);
                    self.menu().shouldDisplayWorlds(true);
                    self.menu().shouldDisplayLevels(false);
                    self.menu().shouldDisplayUsers(false);

                    self.menu.valueHasMutated();
                };

                MainViewModel.prototype.changeUser = function () {
                    var self = this;
                    self.menu().shouldDisplayWorlds(false);
                    self.menu().shouldDisplayLevels(false);
                    self.menu().shouldDisplayUsers(true);
                };

                MainViewModel.prototype.changeWorld = function () {
                    var self = this;
                    self.menu().shouldDisplayWorlds(true);
                    self.menu().shouldDisplayLevels(false);
                    self.menu().shouldDisplayUsers(false);
                };

                MainViewModel.prototype.populateMenu = function () {
                    var self = this;
                    var menu = self.menu();
                    var worlds = menu.worlds();

                    // Populate user info
                    menu.currentUser(self.providers.userSettings.currentUserName);
                    menu.users(self.providers.userSettings.userList.map(function (u, index) {
                        return {
                            index: index,
                            user: ko.observable(u),
                            userEditText: ko.observable(u),
                            isEditing: ko.observable(false),
                            isAddUser: ko.observable(false)
                        };
                    }));

                    menu.users().push({
                        index: self.menu().users().length,
                        user: ko.observable("Player"),
                        userEditText: ko.observable("Player"),
                        isEditing: ko.observable(false),
                        isAddUser: ko.observable(true)
                    });

                    // Populate level definitions
                    self._levels.forEach(function (l) {
                        while (worlds.length < l.world) {
                            worlds.push({
                                isLocked: ko.observable(true),
                                worldNumber: ko.observable(worlds.length + 1),
                                levels: ko.observable([]),
                                stars: ko.observable(0),
                                maxStars: ko.observable(0)
                            });
                        }

                        var w = worlds[l.world - 1];

                        while (w.levels().length < l.level) {
                            w.levels().push({
                                isLocked: ko.observable(true),
                                levelId: l.id,
                                levelNumber: ko.observable(w.levels().length + 1),
                                stars: ko.observable(0),
                                starsClass: ko.observable("star-" + 0)
                            });
                        }

                        var level = w.levels()[l.level - 1];
                        menu.levelsById[l.id] = level;
                    });

                    // Reset all levels
                    worlds.forEach(function (w) {
                        w.levels().forEach(function (l) {
                            l.stars(0);
                            l.starsClass("star-0");
                        });
                    });

                    // Set to level states
                    var levelStates = self.providers.userSettings.currentUserState.levels;

                    levelStates.forEach(function (ls) {
                        menu.levelsById[ls.levelID].stars(ls.stars);
                        menu.levelsById[ls.levelID].starsClass("star-" + ls.stars);
                    });

                    // Unlock levels & count world stars
                    var lastLevelWasFinished = true;
                    var wStars = 0;
                    var wMaxStars = 0;

                    worlds.forEach(function (w) {
                        wStars = 0;
                        wMaxStars = 0;

                        w.isLocked(!lastLevelWasFinished);

                        w.levels().forEach(function (l) {
                            l.isLocked(!lastLevelWasFinished);

                            if (lastLevelWasFinished) {
                                if (l.stars() === 0) {
                                    lastLevelWasFinished = false;
                                }
                            }

                            wStars += l.stars();
                            wMaxStars += 3;
                        });

                        w.stars(wStars);
                        w.maxStars(wMaxStars);
                    });
                };

                MainViewModel.prototype.setupGame = function () {
                    var self = this;

                    self._isNewGame = true;

                    self.score(0);
                    self.isGameOver(false);

                    self.game = new Told.TableMath.Game.TetrisGame(self);
                    var size = 5;
                    var iLevel = self._levelIndex;
                    var levelData = self._levels[iLevel];

                    self.world(levelData.world);
                    self.level(levelData.level);

                    self.game.setup(levelData);
                    self.updateBoard();
                };

                MainViewModel.prototype.gameOver = function (hasWon, mistakes) {
                    var self = this;

                    // Record user state
                    // Calculate Stars
                    var stars = !hasWon ? 0 : mistakes === 0 ? 3 : mistakes <= 2 ? 2 : 1;

                    // Update level score
                    var iLevel = self._levelIndex;
                    var levelData = self._levels[iLevel];
                    var levelId = levelData.id;

                    var uState = self.providers.userSettings.currentUserState;
                    var mLevelState = uState.levels.filter(function (l) {
                        return l.levelID === levelId;
                    });
                    if (mLevelState.length > 0) {
                        var lState = mLevelState[0];
                        if (lState.stars < stars) {
                            lState.stars = stars;
                        }
                    } else {
                        uState.levels.push({ levelID: levelId, stars: stars });
                    }

                    // Save state
                    self.providers.userSettings.currentUserState = uState;

                    // Reset Game
                    self.gameOverHasWon(hasWon);

                    //self.gameOverStars(stars >= 3 ? [true, true, true] : stars >= 2 ? [true, true, false] : stars >= 1 ? [true, false, false] : [false, false, false]);
                    self.gameOverStarsClass("star-" + stars);
                    self.isGameOver(true);

                    self.showAd();
                };

                MainViewModel.prototype.toBoardPosition = function (gamePositon) {
                    // This supports only cleared lines at the bottom of the game board
                    return { iRow: this.game.board.rows.length - 1 - gamePositon.iRow, iCol: gamePositon.iCol + 1 };
                };

                MainViewModel.prototype.updateBoard = function () {
                    var self = this;
                    var gBoard = self.game.board;

                    // Create the board initially
                    if (self._isNewGame) {
                        self._isNewGame = false;

                        var board = { rows: [] };
                        var rows = board.rows;

                        // Create the header row
                        var headerRow = { cells: [], isVisible: true };

                        var symbol = "x";

                        if (gBoard.isAddition) {
                            symbol = "+";
                        }

                        headerRow.cells.push({ id: ko.observable(""), isHeading: true, text: ko.observable(symbol), gameBoardPosition: null, cellClassName: ko.observable("") });

                        for (var iCol = gBoard.minColumnValue; iCol <= gBoard.maxColumnValue; iCol++) {
                            headerRow.cells.push({ id: ko.observable(""), isHeading: true, text: ko.observable("" + iCol), gameBoardPosition: null, cellClassName: ko.observable("") });
                        }

                        // Right Side
                        headerRow.cells.push({ id: ko.observable(""), isHeading: true, text: ko.observable(symbol), gameBoardPosition: null, cellClassName: ko.observable("") });

                        rows.unshift(headerRow);

                        self.board(board);
                    }

                    // Fix the row count
                    var showClearedRows = true;

                    var gRowCount = gBoard.rows.length;

                    if (!showClearedRows) {
                        gRowCount = gBoard.rows.filter(function (r) {
                            return !r.isCleared;
                        }).length;
                    }

                    var gCellCount = gBoard.rows[0].cells.length;

                    if (gRowCount < self.board().rows.length - 1) {
                        self.board().rows.splice(0, self.board().rows.length - 1 - gRowCount);
                    }

                    while (gRowCount > self.board().rows.length - 1) {
                        var nRow = { cells: [] };
                        self.board().rows.unshift(nRow);

                        // Left side header
                        nRow.cells.push({ id: ko.observable(""), isHeading: true, text: ko.observable(""), cellClassName: ko.observable("") });

                        for (var iCol = 0; iCol < gCellCount; iCol++) {
                            // Value cells
                            nRow.cells.push({ id: ko.observable(""), isHeading: false, text: ko.observable(""), cellClassName: ko.observable("") });
                        }

                        // Right side header
                        nRow.cells.push({ id: ko.observable(""), isHeading: true, text: ko.observable(""), cellClassName: ko.observable("") });
                    }

                    for (var iGameRow = 0; iGameRow < gBoard.rows.length; iGameRow++) {
                        var gRow = gBoard.rows[iGameRow];

                        if (!gRow.isCleared || showClearedRows) {
                            var iRow_UI = self.toBoardPosition({ iRow: iGameRow, iCol: 0 }).iRow;

                            var cRow = self.board().rows[iRow_UI];

                            if (!gRow.isSpecial) {
                                // Left side header
                                cRow.cells[0].text("" + gRow.value);

                                // Right side header
                                cRow.cells[cRow.cells.length - 1].text("" + gRow.value);
                            } else {
                                // Left side header
                                cRow.cells[0].text("");

                                // Right side header
                                cRow.cells[cRow.cells.length - 1].text("");
                            }

                            for (var iCol = 0; iCol < gRow.cells.length; iCol++) {
                                // Put values in rows
                                var iCol_UI = self.toBoardPosition({ iRow: iGameRow, iCol: iCol }).iCol;

                                cRow.cells[iCol_UI].id(gRow.cells[iCol].id);

                                var cssName = gRow.isCleared ? "cleared" : "";

                                cRow.cells[iCol_UI].cellClassName(cssName);

                                if (gRow.cells[iCol].isAnswered) {
                                    cRow.cells[iCol_UI].text("" + gRow.cells[iCol].value);
                                } else {
                                    cRow.cells[iCol_UI].text("");
                                }
                            }
                        }
                    }

                    // Show falling value
                    if (self.game.fallingNumber != null) {
                        var fPos = self.toBoardPosition(self.game.fallingNumberPosition);
                        self.board().rows[fPos.iRow].cells[fPos.iCol].text("" + self.game.fallingNumber);
                    }

                    self.board.valueHasMutated();
                };

                MainViewModel.prototype.changeScore = function (change, showChangeAtId) {
                    if (typeof showChangeAtId === "undefined") { showChangeAtId = ""; }
                    if (showChangeAtId != "") {
                        this.scoreChangeAtId(showChangeAtId);

                        if (change > 0) {
                            this.scoreChange("+" + change);
                            this.scoreChangeClassName("scoreGood");
                        } else {
                            this.scoreChange("" + change);
                            this.scoreChangeClassName("scoreBad");
                        }
                    }

                    this.scoreChange.valueHasMutated();

                    this.score(this.score() + change);
                };

                MainViewModel.prototype.handleLevelNext = function () {
                    Told.log("Command", "LevelNext", true);

                    var self = this;

                    if (self.isPaused()) {
                        self.pause(false);
                    }

                    if (self.isGameOver()) {
                        // Level up
                        self._levelIndex++;
                        self.setupGame();
                    }
                };

                MainViewModel.prototype.handleLevelMenu = function () {
                    Told.log("Command", "LevelMenu", true);

                    var self = this;

                    if (self.isPaused()) {
                        self.pause(false);
                    }

                    self.showMenu();
                };

                MainViewModel.prototype.handleLevelReplay = function () {
                    Told.log("Command", "LevelReplay", true);

                    var self = this;

                    if (self.isPaused()) {
                        self.pause(false);
                    }

                    if (!self.isGameOver()) {
                        self.game.stop();
                    }

                    self.setupGame();
                };

                MainViewModel.prototype.handleLevelResume = function () {
                    Told.log("Command", "LevelResume", true);

                    var self = this;

                    if (self.isPaused()) {
                        self.pause(false);
                    }

                    if (self.isGameOver()) {
                        self.setupGame();
                    }
                };

                MainViewModel.prototype.keydown = function (keyCode) {
                    var self = this;

                    if (self.isPaused()) {
                        self.pause(false);
                        return;
                    }

                    if (event.keyCode === 32) {
                        self.pause(true);
                    } else if (event.keyCode === 37) {
                        self.game.inputDirection(0 /* Left */);
                    } else if (event.keyCode === 38) {
                        self.game.inputDirection(3 /* Up */);
                    } else if (event.keyCode === 39) {
                        self.game.inputDirection(1 /* Right */);
                    } else if (event.keyCode === 40) {
                        self.game.inputDirection(2 /* Down */);
                    }
                };
                return MainViewModel;
            })();
            UI.MainViewModel = MainViewModel;

            ko.bindingHandlers["globalInput"] = {
                init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
                    var value = ko.utils.unwrapObservable(valueAccessor());

                    var doIsGameActive = function () {
                        return viewModel.shouldDisplayGame();
                        //if (viewModel.isGameOver()) {
                        //    // Allow standard input to click on menu buttons
                        //    return false;
                        //} else if (viewModel.shouldDisplayGame()) {
                        //    // Allow standard input to click on menu buttons
                        //    return false;
                        //} else {
                        //    return true;
                        //}
                    };

                    document.onkeydown = function (e) {
                        if (doIsGameActive()) {
                            viewModel.keydown(e.keyCode);
                        }
                    };

                    //            //$(document).keydown(
                    //    function (e) {
                    //if (doIsGameActive()) {
                    //    viewModel.keydown(e.keyCode);
                    //}
                    var upCount = 0;

                    Hammer(document).on("tap", function (ev) {
                        ev.gesture.preventDefault();

                        if (ev.gesture.center.pageY < window.innerHeight * 0.2) {
                            upCount++;

                            Told.log("Logging", "upCount: " + upCount, false);
                        } else if (upCount > 5) {
                            if (ev.gesture.center.pageX > window.innerWidth * 0.8) {
                                Told.log("Logging", "Enabled", false);

                                // Turn on logging
                                Told.enableLogging("log");
                            }
                        } else {
                            upCount = 0;
                            Told.log("Logging", "upCount reset", false);
                        }

                        if (viewModel.isPaused()) {
                            viewModel.pause(false);
                            return;
                        }

                        if (doIsGameActive()) {
                            // If right side, move right
                            if (ev.gesture.center.pageX > window.innerWidth * 0.8) {
                                viewModel.game.inputDirection(1 /* Right */);
                            } else if (ev.gesture.center.pageX < window.innerWidth * 0.2) {
                                // If left side, move left
                                viewModel.game.inputDirection(0 /* Left */);
                            } else if (ev.gesture.center.pageY < window.innerHeight * 0.2) {
                                // If top side, pause
                                viewModel.pause(true);
                            } else {
                                // If center, down
                                viewModel.game.inputDirection(2 /* Down */);
                            }
                        }
                    });

                    Hammer(document).on("dragleft dragright dragdown swipeleft swiperight swipedown", function (ev) {
                        ev.gesture.preventDefault();
                        if (ev.type == 'dragleft' || ev.type == 'dragright' || ev.type == 'dragdown') {
                            return;
                        }

                        // handle the swipes
                        if (doIsGameActive()) {
                            if (ev.type == "swipedown") {
                                viewModel.game.inputDirection(2 /* Down */);
                            } else if (ev.type == "swipeleft") {
                                viewModel.game.inputDirection(0 /* Left */);
                            } else if (ev.type == "swiperight") {
                                viewModel.game.inputDirection(1 /* Right */);
                            }
                        }
                    });
                }
            };

            ko.bindingHandlers["animScoreChange"] = {
                init: function (element) {
                    element.style.display = "none";
                },
                update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
                    Told.log("Animation", "slideUpAndFadeOut Update:" + element.id, false);

                    ko.utils.unwrapObservable(valueAccessor()); // to subscribe

                    if (viewModel.scoreChange() == "") {
                        return;
                    }

                    var atElement = document.getElementById(viewModel.scoreChangeAtId());

                    if (atElement == null) {
                        return;
                    }

                    var sPos = atElement.getBoundingClientRect();

                    var startPositionLeft = sPos.left;
                    var startPositionTop = sPos.top;

                    //var startPositionLeft = atElement.offsetLeft;
                    //var startPositionTop = atElement.offsetTop;
                    var endPositionLeft = startPositionLeft;
                    var endPositionTop = startPositionTop - 100;

                    var duration = 500;

                    var changeLeft = endPositionLeft - startPositionLeft;
                    var changeTop = endPositionTop - startPositionTop;

                    var startFontSize = 2;
                    var endFontSize = 4;
                    var changeFontSize = endFontSize - startFontSize;

                    var scoreElement = element;

                    var startTime = Date.now();
                    var updatePosition = function () {
                        var timeChange = Date.now() - startTime;
                        var ratioChange = timeChange / duration;

                        if (ratioChange > 1) {
                            ratioChange = 1;
                        }

                        scoreElement.style.display = "block";

                        scoreElement.style.left = startPositionLeft + (ratioChange * changeLeft) + "px";
                        scoreElement.style.top = startPositionTop + (ratioChange * changeTop) + "px";

                        scoreElement.style.fontSize = (startFontSize + (ratioChange * changeFontSize)) + "em";

                        if (ratioChange < 1) {
                            setTimeout(updatePosition, 10);
                        } else {
                            scoreElement.style.display = "none";
                        }
                    };

                    updatePosition();
                    //// Use jQuery animation
                    //var atElement = $("#" + viewModel.scoreChangeAtId());
                    //if (atElement.length === 0) {
                    //    return;
                    //}
                    //var startPosition = atElement.offset();
                    //// Go to score
                    ////var endPosition = $("#score").offset();
                    //// Go up
                    //var endPosition = startPosition;
                    //endPosition = { left: endPosition.left, top: endPosition.top - 100 };
                    //var scElement = $(element);
                    //scElement.stop(true, true);
                    //scElement.css({ fontSize: "2em", opacity: "100", top: startPosition.top, left: startPosition.left });
                    ////scElement.offset(startPosition);
                    //scElement.show();
                    //scElement.animate({ fontSize: "+=2em", top: endPosition.top, left: endPosition.left },
                    //    500,
                    //    "swing", () => {
                    //        //scElement.animate({ opacity: "0" }, 500, () => { scElement.hide(); });
                    //        scElement.hide();
                    //    });
                    //// At end make it nothing
                    ////viewModel.scoreChange("");
                }
            };

            ko.bindingHandlers["fastclick"] = {
                init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    new FastButton(element, function () {
                        var f = valueAccessor();
                        f.call(bindingContext["$root"], bindingContext["$data"], event);
                    });
                }
            };
        })(TableMath.UI || (TableMath.UI = {}));
        var UI = TableMath.UI;
    })(Told.TableMath || (Told.TableMath = {}));
    var TableMath = Told.TableMath;
})(Told || (Told = {}));


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.counter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.counter.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.counter.AddCounterActivity"
            android:label="@string/title_activity_add_counter" >
        </activity>
        <activity
            android:name="com.example.counter.Remove_counter"
            android:label="@string/title_activity_remove_counter" >
        </activity>
        <activity
            android:name="com.example.counter.Edit_counter"
            android:label="@string/title_activity_edit_counter" >
        </activity>
        <activity
            android:name="com.example.counter.Reset_counter"
            android:label="@string/title_activity_reset_counter" >
        </activity>
        <activity
            android:name="com.example.counter.Results"
            android:label="@string/title_activity_results" >
        </activity>
        <activity
            android:name="com.example.counter.Counters"
            android:label="@string/title_activity_counters" >
        </activity>
        <activity
            android:name="com.example.counter.All_counters"
            android:label="@string/title_activity_all_counters" >
        </activity>
        <activity
            android:name="com.example.counter.Save_data"
            android:label="@string/title_activity_save_data" >
        </activity>
        <activity
            android:name="com.example.counter.ResultsActivity"
            android:label="@string/title_activity_results" >
        </activity>
    </application>

</manifest>


text:
package com.lkland.videocompressor;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class Activity1 extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 5000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(Activity1.this, Activity2.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}


text:
package pl.polak.designpattern.command.impl;

import pl.polak.designpattern.command.Command;
import pl.polak.designpattern.command.FileReceiver;

/**
 * User: marcin
 * Date: 26.11.13
 * Time: 21:05
 */
public class OpenFileCommand implements Command {

    private FileReceiver fileReceiver;

    public OpenFileCommand(FileReceiver fileReceiver) {
        this.fileReceiver = fileReceiver;
    }

    @Override
    public void execute() {
        System.out.println("Executing...");
        fileReceiver.openFile("file");
    }

}


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

    <META http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>ddl.Utils</title>

ddl.Utils

class ExtSprintClassT(T);

Extended Sprintf class.  Features an internally expanding buffer for formatting data,
	and an optional opCall vararg syntax.

this(int size, Format.DblFormat df = null, T[] workspace = null);

uint sink(void[] v
, uint type
);

T[] opCall(T[] fmt
,...);


text:
module Net; module SSH; module Authentication

# Loads ED25519 support which requires optinal dependecies like
# rbnacl, bcrypt_pbkdf
module ED25519Loader

begin
  require 'net/ssh/authentication/ed25519'
  LOADED = true
  ERROR = nil
rescue LoadError => e
  ERROR = e
  LOADED = false
end

def self.raiseUnlessLoaded(message)
  description = ERROR.is_a?(LoadError) ? dependenciesRequiredForED25519 : ''
  description << "#{ERROR.class} : \"#{ERROR.message}\"\n" if ERROR
  raise NotImplementedError, "#{message}\n#{description}" unless LOADED
end

def self.dependenciesRequiredForED25519
  result = "net-ssh requires the following gems for ed25519 support:\n"
  result << " * rbnacl (>= 3.2, < 5.0)\n"
  result << " * rbnacl-libsodium, if your system doesn't have libsodium installed.\n"
  result << " * bcrypt_pbkdf (>= 1.0, < 2.0)\n" unless RUBY_PLATFORM == "java"
  result << "See https://github.com/net-ssh/net-ssh/issues/478 for more information\n"
end

end
end; end; end


text:
package org.febit.arango;

import java.io.Serializable;
import java.util.Objects;
import org.febit.arango.meta.ArangoId;

/**
 *
 * @author zqq90
 */
public abstract class Entity implements Serializable {

    @ArangoId
    protected String _id;

    public String id() {
        return _id;
    }

    public String id(String id) {
        setId(id);
        return id;
    }

    public String getId() {
        return _id;
    }

    public void setId(String id) {
        this._id = id;
    }

    public boolean _isPersistent() {
        return this._id != null;
    }

    @Override
    public int hashCode() {
        if (_id == null) {
            return 0;
        }
        return _id.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Entity other = (Entity) obj;
        if (!Objects.equals(this._id, other._id)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "[ _id=" + id() + " ]";
    }
}


text:
using BooksLibrary.Data;
using BooksLibrary.Models;
using ChatSystem.Data.Repository;
using System;
namespace BooksLibrary.Web.Authors
{
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class All : System.Web.UI.Page
    {
        IRepository<Author> authors = new EfGenericRepository<Author>(new BooksLibraryDbContext());

        protected void Page_Load(object sender, EventArgs e)
        {
            var qp = Request.QueryString["id"];
        }

        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<Author> AuthorsGridView_GetData()
        {
            return authors.All();
        }

        protected void AuthorsGridView_PageIndexChanged(object sender, EventArgs e)
        {
            var page = AuthorsGridView.PageIndex;
            var pageSize = AuthorsGridView.PageSize;
        }
    }
}


text:
class MultiUserNotificationBlockerChromeOS
    : public message_center::NotificationBlocker {
 public:
  MultiUserNotificationBlockerChromeOS(
      message_center::MessageCenter* message_center,
      const std::string& initial_user_id);
  virtual ~MultiUserNotificationBlockerChromeOS();

  // Called by MultiUserWindowManager when the active user has changed.
  void ActiveUserChanged(const std::string& user_id);

  // message_center::NotificationBlocker overrides:
  virtual bool ShouldShowNotification(
      const message_center::NotifierId& notifier_id) const override;
  virtual bool ShouldShowNotificationAsPopup(
      const message_center::NotifierId& notifier_id) const override;

 private:
  // Returns true if this blocker is actively working.
  bool IsActive() const;

  std::string active_user_id_;
  std::map<std::string, bool> quiet_modes_;

  DISALLOW_COPY_AND_ASSIGN(MultiUserNotificationBlockerChromeOS);
};

#endif  // CHROME_BROWSER_UI_ASH_MULTI_USER_MULTI_USER_NOTIFICATION_BLOCKER_CHROMEOS_H_


text:
layout: post
title: 'Medal of Honor: Allied Assault Dedicated Servers Released'
date: 2008-12-24 11:33
comments: true
categories : [Apple/OSX, Games, MoHAA, Software]
---

So I finally got around to releasing a package of the Medal of Honor: Allied Assault Dedicated Servers.

They can be downloaded here.

I plan on releasing new versions of the Game Server Configurator: MoHAA in the next few weeks and you will need these to use that tool.

NOTE:
These are command line server binaries that allow you to host a MoHAA server without running the MoHAA client.

DISCLAIMER:
These binaries are released as a non-supported product. That means that neither Aspyr Media, Inc. nor Damage Studios technical support center can answer or help with any issues you may encounter with this release. Aspyr Media, Inc. and Damage Studios make no representation or warranty of any kind regarding: