text:
from __future__ import absolute_import, division

import gc
import re
import sys
import textwrap
import types

from twisted.python import util
from twisted.python.compat import NativeStringIO
from twisted.python.filepath import FilePath
from twisted.python.usage import UsageError
from twisted.scripts import trial
from twisted.trial import unittest
from twisted.trial._dist.disttrial import DistTrialRunner
from twisted.trial.runner import TestLoader
from twisted.trial.runner import TrialRunner, TestSuite, DestructiveTestSuite
from twisted.trial.test.test_loader import testNames

pyunit = __import__('unittest')

def sibpath(filename):
    """
    For finding files in twisted/trial/test
    """
    return util.sibpath(__file__, filename)

class ForceGarbageCollectionTests(unittest.SynchronousTestCase):
    """
    Tests for the --force-gc option.
    """

    def setUp(self):
        self.config = trial.Options()
        self.log = []
        self.patch(gc, 'collect', self.collect)
        test = pyunit.FunctionTestCase(self.simpleTest)
        self.test = TestSuite([test, test])

    def simpleTest(self):
        """
        A simple test method that records that it was run.
        """
        self.log.append('test')

    def collect(self):
        """
        A replacement for gc.collect that logs calls to itself.
        """
        self.log.append('collect')

    def makeRunner(self):
        """
        Return a L{TrialRunner} object that is safe to use in tests.
        """
        runner = trial._makeRunner(self.config)
        runner.stream = NativeStringIO()
        return runner

    def test_forceGc(self):
        """
        Passing the --force-gc option to the trial script forces the garbage
        collector to run before and after each test.
        """
        self.config['force-gc'] = True
        self.config.postOptions()
        runner = self.makeRunner()
        runner.run(self.test)
        self.assertEqual(self.log, ['collect', 'test', 'collect',
                                    'collect', 'test', 'collect'])

    def test_unforceGc(self):
        """
        By default, no garbage collection is forced.
        """
        self.config.postOptions()
        runner = self.makeRunner()
        runner.run(self.test)
        self.assertEqual(self.log, ['test', 'test'])

class SuiteUsedTests(unittest.SynchronousTestCase):
    """
    Check the category of tests suite used by the loader.
    """

    def setUp(self):
        """
        Create a trial configuration object.
        """
        self.config = trial.Options()

    def test_defaultSuite(self):
        """
        By default, the loader should use L{DestructiveTestSuite}
        """
        loader = trial._getLoader(self.config)
        self.assertEqual(loader.suiteFactory, DestructiveTestSuite)

    def test_untilFailureSuite(self):
        """
        The C{until-failure} configuration uses the L{TestSuite} to keep
        instances alive across runs.
        """
        self.config['until-failure'] = True
        loader = trial._getLoader(self.config)
        self.assertEqual(loader.suiteFactory, TestSuite)

class TestModuleTests(unittest.SynchronousTestCase):
    def setUp(self):
        self.config = trial.Options()

    def tearDown(self):
        self.config = None

    def test_testNames(self):
        """
        Check that the testNames helper method accurately collects the
        names of tests in suite.
        """
        self.assertEqual(testNames(self), [self.id()])

    def assertSuitesEqual(self, test1, names):
        loader = TestLoader()
        names1 = testNames(test1)
        names2 = testNames(TestSuite(map(loader.loadByName, names)))
        names1.sort()
        names2.sort()
        self.assertEqual(names1, names2)

    def test_baseState(self):
        self.assertEqual(0, len(self.config['tests']))

    def test_testmoduleOnModule(self):
        """
        Check that --testmodule loads a suite which contains the tests
        referred to in test-case-name inside its parameter.
        """
        self.config.opt_testmodule(sibpath('moduletest.py'))
        self.assertSuitesEqual(trial._getSuite(self.config),
                               ['twisted.trial.test.test_log'])

    def test_testmoduleTwice(self):
        """
        When the same module is specified with two --testmodule flags, it
        should only appear once in the suite.
        """
        self.config.opt_testmodule(sibpath('moduletest.py'))
        self.config.opt_testmodule(sibpath('moduletest.py'))
        self.assertSuitesEqual(trial._getSuite(self.config),
                               ['twisted.trial.test.test_log'])

    def test_testmoduleOnSourceAndTarget(self):
        """
        If --testmodule is specified twice, once for module A and once for
        a module which refers to module A, then make sure module A is only
        added once.
        """
        self.config.opt_testmodule(sibpath('moduletest.py'))
        self.config.opt_testmodule(sibpath('test_log.py'))
        self.assertSuitesEqual(trial._getSuite(self.config),
                               ['twisted.trial.test.test_log'])

    def test_testmoduleOnSelfModule(self):
        """
        When given a module that refers to *itself* in the test-case-name
        variable, check that --testmodule only adds the tests once.
        """
        self.config.opt_testmodule(sibpath('moduleself.py'))
        self.assertSuitesEqual(trial._getSuite(self.config),
                               ['twisted.trial.test.moduleself'])

    def test_testmoduleOnScript(self):
        """
        Check that --testmodule loads tests referred to in test-case-name
        buffer variables.
        """
        self.config.opt_testmodule(sibpath('scripttest.py'))
        self.assertSuitesEqual(trial._getSuite(self.config),
                               ['twisted.trial.test.test_log',
                                'twisted.trial.test.test_runner'])

    def test_testmoduleOnNonexistentFile(self):
        """
        Check that --testmodule displays a meaningful error message when
        passed a non-existent filename.
        """
        buffy = NativeStringIO()
        stderr, sys.stderr = sys.stderr, buffy
        filename = 'test_thisbetternoteverexist.py'
        try:
            self.config.opt_testmodule(filename)
            self.assertEqual(0, len(self.config['tests']))
            self.assertEqual("File %r doesn't exist\n" % (filename,),
                                 buffy.getvalue())
        finally:
            sys.stderr = stderr

    def test_testmoduleOnEmptyVars(self):
        """
        Check that --testmodule adds no tests to the suite for modules
        which lack test-case-name buffer variables.
        """
        self.config.opt_testmodule(sibpath('novars.py'))
        self.assertEqual(0, len(self.config['tests']))

    def test_testmoduleOnModuleName(self):
        """
        Check that --testmodule does *not* support module names as arguments
        and that it displays a meaningful error message.
        """
        buffy = NativeStringIO()
        stderr, sys.stderr = sys.stderr, buffy
        moduleName = 'twisted.trial.test.test_script'
        try:
            self.config.opt_testmodule(moduleName)
            self.assertEqual(0, len(self.config['tests']))
            self.assertEqual("File %r doesn't exist\n" % (moduleName,),
                                 buffy.getvalue())
        finally:
            sys.stderr = stderr

    def test_parseLocalVariable(self):
        declaration = '-*- test-case-name: twisted.trial.test.test_tests -*-'
        localVars = trial._parseLocalVariables(declaration)
        self.assertEqual({'test-case-name':
                              'twisted.trial.test.test_tests'},
                             localVars)

    def test_trailingSemicolon(self):
        declaration = '-*- test-case-name: twisted.trial.test.test_tests; -*-'
        localVars = trial._parseLocalVariables(declaration)
        self.assertEqual({'test-case-name':
                              'twisted.trial.test.test_tests'},
                             localVars)

    def test_parseLocalVariables(self):
        declaration = ('-*- test-case-name: twisted.trial.test.test_tests; '
                       'foo: bar -*-')
        localVars = trial._parseLocalVariables(declaration)
        self.assertEqual({'test-case-name':
                              'twisted.trial.test.test_tests',
                              'foo': 'bar'},
                             localVars)

    def test_surroundingGuff(self):
        declaration = ('## -*- test-case-name: '
                       'twisted.trial.test.test_tests -*- #')
        localVars = trial._parseLocalVariables(declaration)
        self.assertEqual({'test-case-name':
                              'twisted.trial.test.test_tests'},
                             localVars)

    def test_invalidLine(self):
        self.assertRaises(ValueError, trial._parseLocalVariables,
                              'foo')

    def test_invalidDeclaration(self):
        self.assertRaises(ValueError, trial._parseLocalVariables,
                              '-*- foo -*-')
        self.assertRaises(ValueError, trial._parseLocalVariables,
                              '-*- foo: bar; qux -*-')
        self.assertRaises(ValueError, trial._parseLocalVariables,
                              '-*- foo: bar: baz; qux: qax -*-')

    def test_variablesFromFile(self):
        localVars = trial.loadLocalVariables(sibpath('moduletest.py'))
        self.assertEqual({'test-case-name':
                              'twisted.trial.test.test_log'},
                             localVars)

    def test_noVariablesInFile(self):
        localVars = trial.loadLocalVariables(sibpath('novars.py'))
        self.assertEqual({}, localVars)

    def test_variablesFromScript(self):
        localVars = trial.loadLocalVariables(sibpath('scripttest.py'))
        self.assertEqual(
            {'test-case-name': ('twisted.trial.test.test_log,'
                                'twisted.trial.test.test_runner')},
            localVars)

    def test_getTestModules(self):
        modules = trial.getTestModules(sibpath('moduletest.py'))
        self.assertEqual(modules, ['twisted.trial.test.test_log'])

    def test_getTestModules_noVars(self):
        modules = trial.getTestModules(sibpath('novars.py'))
        self.assertEqual(len(modules), 0)

    def test_getTestModules_multiple(self):
        modules = trial.getTestModules(sibpath('scripttest.py'))
        self.assertEqual(set(modules),
                             set(['twisted.trial.test.test_log',
                                  'twisted.trial.test.test_runner']))

    def test_looksLikeTestModule(self):
        for filename in ['test_script.py', 'twisted/trial/test/test_script.py']:
            self.assertTrue(trial.isTestFile(filename),
                            "%r should be a test file" % (filename,))
        for filename in ['twisted/trial/test/moduletest.py',
                         sibpath('scripttest.py'), sibpath('test_foo.bat')]:
            self.assertFalse(trial.isTestFile(filename),
                        "%r should *not* be a test file" % (filename,))

class WithoutModuleTests(unittest.SynchronousTestCase):
    """
    Test the C{without-module} flag.
    """

    def setUp(self):
        """
        Create a L{trial.Options} object to be used in the tests, and save
        C{sys.modules}.
        """
        self.config = trial.Options()
        self.savedModules = dict(sys.modules)

    def tearDown(self):
        """
        Restore C{sys.modules}.
        """
        for module in ('imaplib', 'smtplib'):
            if module in self.savedModules:
                sys.modules[module] = self.savedModules[module]
            else:
                sys.modules.pop(module, None)

    def _checkSMTP(self):
        """
        Try to import the C{smtplib} module, and return it.
        """
        import smtplib
        return smtplib

    def _checkIMAP(self):
        """
        Try to import the C{imaplib} module, and return it.
        """
        import imaplib
        return imaplib

    def test_disableOneModule(self):
        """
        Check that after disabling a module, it can't be imported anymore.
        """
        self.config.parseOptions(["--without-module", "smtplib"])
        self.assertRaises(ImportError, self._checkSMTP)
        # Restore sys.modules
        del sys.modules["smtplib"]
        # Then the function should succeed
        self.assertIsInstance(self._checkSMTP(), types.ModuleType)

    def test_disableMultipleModules(self):
        """
        Check that several modules can be disabled at once.
        """
        self.config.parseOptions(["--without-module", "smtplib,imaplib"])
        self.assertRaises(ImportError, self._checkSMTP)
        self.assertRaises(ImportError, self._checkIMAP)
        # Restore sys.modules
        del sys.modules["smtplib"]
        del sys.modules["imaplib"]
        # Then the functions should succeed
        self.assertIsInstance(self._checkSMTP(), types.ModuleType)
        self.assertIsInstance(self._checkIMAP(), types.ModuleType)

    def test_disableAlreadyImportedModule(self):
        """
        Disabling an already imported module should produce a warning.
        """
        self.assertIsInstance(self._checkSMTP(), types.ModuleType)
        self.assertWarns(RuntimeWarning,
                "Module 'smtplib' already imported, disabling anyway.",
                trial.__file__,
                self.config.parseOptions, ["--without-module", "smtplib"])
        self.assertRaises(ImportError, self._checkSMTP)

class CoverageTests(unittest.SynchronousTestCase):
    """
    Tests for the I{coverage} option.
    """
    if getattr(sys, 'gettrace', None) is None:
        skip = (
            "Cannot test trace hook installation without inspection API.")

    def setUp(self):
        """
        Arrange for the current trace hook to be restored when the
        test is complete.
        """
        self.addCleanup(sys.settrace, sys.gettrace())

    def test_tracerInstalled(self):
        """
        L{trial.Options} handles C{"--coverage"} by installing a trace
        hook to record coverage information.
        """
        options = trial.Options()
        options.parseOptions(["--coverage"])
        self.assertEqual(sys.gettrace(), options.tracer.globaltrace)

    def test_coverdirDefault(self):
        """
        L{trial.Options.coverdir} returns a L{FilePath} based on the default
        for the I{temp-directory} option if that option is not specified.
        """
        options = trial.Options()
        self.assertEqual(
            options.coverdir(),
            FilePath(".").descendant([options["temp-directory"], "coverage"]))

    def test_coverdirOverridden(self):
        """
        If a value is specified for the I{temp-directory} option,
        L{trial.Options.coverdir} returns a child of that path.
        """
        path = self.mktemp()
        options = trial.Options()
        options.parseOptions(["--temp-directory", path])
        self.assertEqual(
            options.coverdir(), FilePath(path).child("coverage"))

class OptionsTests(unittest.TestCase):
    """
    Tests for L{trial.Options}.
    """

    def setUp(self):
        """
        Build an L{Options} object to be used in the tests.
        """
        self.options = trial.Options()

    def test_getWorkerArguments(self):
        """
        C{_getWorkerArguments} discards options like C{random} as they only
        matter in the manager, and forwards options like C{recursionlimit} or
        C{disablegc}.
        """
        self.addCleanup(sys.setrecursionlimit, sys.getrecursionlimit())
        if gc.isenabled():
            self.addCleanup(gc.enable)

        self.options.parseOptions(["--recursionlimit", "2000", "--random",
                                   "4", "--disablegc"])
        args = self.options._getWorkerArguments()
        self.assertIn("--disablegc", args)
        args.remove("--disablegc")
        self.assertEqual(["--recursionlimit", "2000"], args)

    def test_jobsConflictWithDebug(self):
        """
        C{parseOptions} raises a C{UsageError} when C{--debug} is passed along
        C{--jobs} as it's not supported yet.

        @see: U{http://twistedmatrix.com/trac/ticket/5825}
        """
        error = self.assertRaises(
            UsageError, self.options.parseOptions, ["--jobs", "4", "--debug"])
        self.assertEqual("You can't specify --debug when using --jobs",
                         str(error))

    def test_jobsConflictWithProfile(self):
        """
        C{parseOptions} raises a C{UsageError} when C{--profile} is passed
        along C{--jobs} as it's not supported yet.

        @see: U{http://twistedmatrix.com/trac/ticket/5827}
        """
        error = self.assertRaises(
            UsageError, self.options.parseOptions,
            ["--jobs", "4", "--profile"])
        self.assertEqual("You can't specify --profile when using --jobs",
                         str(error))

    def test_jobsConflictWithDebugStackTraces(self):
        """
        C{parseOptions} raises a C{UsageError} when C{--debug-stacktraces} is
        passed along C{--jobs} as it's not supported yet.

        @see: U{http://twistedmatrix.com/trac/ticket/5826}
        """
        error = self.assertRaises(
            UsageError, self.options.parseOptions,
            ["--jobs", "4", "--debug-stacktraces"])
        self.assertEqual(
            "You can't specify --debug-stacktraces when using --jobs",
            str(error))

    def test_jobsConflictWithExitFirst(self):
        """
        C{parseOptions} raises a C{UsageError} when C{--exitfirst} is passed
        along C{--jobs} as it's not supported yet.

        @see: U{http://twistedmatrix.com/trac/ticket/6436}
        """
        error = self.assertRaises(
            UsageError, self.options.parseOptions,
            ["--jobs", "4", "--exitfirst"])
        self.assertEqual(
            "You can't specify --exitfirst when using --jobs",
            str(error))

    def test_orderConflictWithRandom(self):
        """
        C{parseOptions} raises a C{UsageError} when C{--order} is passed along
        with C{--random}.
        """
        error = self.assertRaises(
            UsageError,
            self.options.parseOptions,
            ["--order", "alphabetical", "--random", "1234"])
        self.assertEqual("You can't specify --random when using --order",
                         str(error))

class MakeRunnerTests(unittest.TestCase):
    """
    Tests for the L{_makeRunner} helper.
    """

    def setUp(self):
        self.options = trial.Options()

    def test_jobs(self):
        """
        L{_makeRunner} returns a L{DistTrialRunner} instance when the C{--jobs}
        option is passed, and passes the C{workerNumber} and C{workerArguments}
        parameters to it.
        """
        self.options.parseOptions(["--jobs", "4", "--force-gc"])
        runner = trial._makeRunner(self.options)
        self.assertIsInstance(runner, DistTrialRunner)
        self.assertEqual(4, runner._workerNumber)
        self.assertEqual(["--force-gc"], runner._workerArguments)

    def test_dryRunWithJobs(self):
        """
        L{_makeRunner} returns a L{TrialRunner} instance in C{DRY_RUN} mode
        when the C{--dry-run} option is passed, even if C{--jobs} is set.
        """
        self.options.parseOptions(["--jobs", "4", "--dry-run"])
        runner = trial._makeRunner(self.options)
        self.assertIsInstance(runner, TrialRunner)
        self.assertEqual(TrialRunner.DRY_RUN, runner.mode)

    def test_DebuggerNotFound(self):
        namedAny = trial.reflect.namedAny

        def namedAnyExceptdoNotFind(fqn):
            if fqn == "doNotFind":
                raise trial.reflect.ModuleNotFound(fqn)
            return namedAny(fqn)

        self.patch(trial.reflect, "namedAny", namedAnyExceptdoNotFind)

        options = trial.Options()
        options.parseOptions(["--debug", "--debugger", "doNotFind"])

        self.assertRaises(trial._DebuggerNotFound, trial._makeRunner, options)

    def test_exitfirst(self):
        """
        Passing C{--exitfirst} wraps the reporter with a
        L{reporter._ExitWrapper} that stops on any non-success.
        """
        self.options.parseOptions(["--exitfirst"])
        runner = trial._makeRunner(self.options)
        self.assertTrue(runner._exitFirst)

class RunTests(unittest.TestCase):
    """
    Tests for the L{run} function.
    """

    def setUp(self):
        # don't re-parse cmdline options, because if --reactor was passed to
        # the test run trial will try to restart the (already running) reactor
        self.patch(trial.Options, "parseOptions", lambda self: None)

    def test_debuggerNotFound(self):
        """
        When a debugger is not found, an error message is printed to the user.

        """

        def _makeRunner(*args, **kwargs):
            raise trial._DebuggerNotFound('foo')
        self.patch(trial, "_makeRunner", _makeRunner)

        try:
            trial.run()
        except SystemExit as e:
            self.assertIn("foo", str(e))
        else:
            self.fail("Should have exited due to non-existent debugger!")

class TestArgumentOrderTests(unittest.TestCase):
    """
    Tests for the order-preserving behavior on provided command-line tests.
    """

    def setUp(self):
        self.config = trial.Options()
        self.loader = TestLoader()

    def test_preserveArgumentOrder(self):
        """
        Multiple tests passed on the command line are not reordered.
        """
        tests = [
            "twisted.trial.test.test_tests",
            "twisted.trial.test.test_assertions",
            "twisted.trial.test.test_deferred",
            ]
        self.config.parseOptions(tests)

        suite = trial._getSuite(self.config)
        names = testNames(suite)

        expectedSuite = TestSuite(map(self.loader.loadByName, tests))
        expectedNames = testNames(expectedSuite)

        self.assertEqual(names, expectedNames)

class OrderTests(unittest.TestCase):
    """
    Tests for the --order option.
    """
    def setUp(self):
        self.config = trial.Options()

    def test_alphabetical(self):
        """
        --order=alphabetical causes trial to run tests alphabetically within
        each test case.
        """
        self.config.parseOptions([
            "--order", "alphabetical",
            "twisted.trial.test.ordertests.FooTest"])

        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        self.assertEqual(
            testNames(suite), [
            'twisted.trial.test.ordertests.FooTest.test_first',
            'twisted.trial.test.ordertests.FooTest.test_fourth',
            'twisted.trial.test.ordertests.FooTest.test_second',
            'twisted.trial.test.ordertests.FooTest.test_third'])

    def test_alphabeticalModule(self):
        """
        --order=alphabetical causes trial to run test classes within a given
        module alphabetically.
        """
        self.config.parseOptions([
            "--order", "alphabetical", "twisted.trial.test.ordertests"])
        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        self.assertEqual(
            testNames(suite), [
            'twisted.trial.test.ordertests.BarTest.test_bar',
            'twisted.trial.test.ordertests.BazTest.test_baz',
            'twisted.trial.test.ordertests.FooTest.test_first',
            'twisted.trial.test.ordertests.FooTest.test_fourth',
            'twisted.trial.test.ordertests.FooTest.test_second',
            'twisted.trial.test.ordertests.FooTest.test_third'])

    def test_alphabeticalPackage(self):
        """
        --order=alphabetical causes trial to run test modules within a given
        package alphabetically, with tests within each module alphabetized.
        """
        self.config.parseOptions([
            "--order", "alphabetical", "twisted.trial.test"])
        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        names = testNames(suite)
        self.assertTrue(names, msg="Failed to load any tests!")
        self.assertEqual(names, sorted(names))

    def test_toptobottom(self):
        """
        --order=toptobottom causes trial to run test methods within a given
        test case from top to bottom as they are defined in the body of the
        class.
        """
        self.config.parseOptions([
            "--order", "toptobottom",
            "twisted.trial.test.ordertests.FooTest"])

        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        self.assertEqual(
            testNames(suite), [
            'twisted.trial.test.ordertests.FooTest.test_first',
            'twisted.trial.test.ordertests.FooTest.test_second',
            'twisted.trial.test.ordertests.FooTest.test_third',
            'twisted.trial.test.ordertests.FooTest.test_fourth'])

    def test_toptobottomModule(self):
        """
        --order=toptobottom causes trial to run test classes within a given
        module from top to bottom as they are defined in the module's source.
        """
        self.config.parseOptions([
            "--order", "toptobottom", "twisted.trial.test.ordertests"])
        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        self.assertEqual(
            testNames(suite), [
            'twisted.trial.test.ordertests.FooTest.test_first',
            'twisted.trial.test.ordertests.FooTest.test_second',
            'twisted.trial.test.ordertests.FooTest.test_third',
            'twisted.trial.test.ordertests.FooTest.test_fourth',
            'twisted.trial.test.ordertests.BazTest.test_baz',
            'twisted.trial.test.ordertests.BarTest.test_bar'])

    def test_toptobottomPackage(self):
        """
        --order=toptobottom causes trial to run test modules within a given
        package alphabetically, with tests within each module run top to
        bottom.
        """
        self.config.parseOptions([
            "--order", "toptobottom", "twisted.trial.test"])
        loader = trial._getLoader(self.config)
        suite = loader.loadByNames(self.config['tests'])

        names = testNames(suite)
        # twisted.trial.test.test_module, so split and key on the first 4 to
        # get stable alphabetical sort on those
        self.assertEqual(
            names, sorted(names, key=lambda name : name.split(".")[:4]),
        )

    def test_toptobottomMissingSource(self):
        """
        --order=toptobottom detects the source line of methods from modules
        whose source file is missing.
        """
        tempdir = self.mktemp()
        package = FilePath(tempdir).child('twisted_toptobottom_temp')
        package.makedirs()
        package.child('__init__.py').setContent(b'')
        package.child('test_missing.py').setContent(textwrap.dedent('''
        from twisted.trial.unittest import TestCase
        class TestMissing(TestCase):
            def test_second(self): pass
            def test_third(self): pass
            def test_fourth(self): pass
            def test_first(self): pass
        ''').encode('utf8'))
        pathEntry = package.parent().path
        sys.path.insert(0, pathEntry)
        self.addCleanup(sys.path.remove, pathEntry)
        from twisted_toptobottom_temp import test_missing
        self.addCleanup(sys.modules.pop, 'twisted_toptobottom_temp')
        self.addCleanup(sys.modules.pop, test_missing.__name__)
        package.child('test_missing.py').remove()

        self.config.parseOptions([
            "--order", "toptobottom", "twisted.trial.test.ordertests"])
        loader = trial._getLoader(self.config)
        suite = loader.loadModule(test_missing)

        self.assertEqual(
            testNames(suite), [
            'twisted_toptobottom_temp.test_missing.TestMissing.test_second',
            'twisted_toptobottom_temp.test_missing.TestMissing.test_third',
            'twisted_toptobottom_temp.test_missing.TestMissing.test_fourth',
            'twisted_toptobottom_temp.test_missing.TestMissing.test_first'])

    def test_unknownOrder(self):
        """
        An unknown order passed to --order raises a L{UsageError}.
        """

        self.assertRaises(
            UsageError, self.config.parseOptions, ["--order", "I don't exist"])

class HelpOrderTests(unittest.TestCase):
    """
    Tests for the --help-orders flag.
    """
    def test_help_ordersPrintsSynopsisAndQuits(self):
        """
        --help-orders prints each of the available orders and then exits.
        """
        self.patch(sys, "stdout", NativeStringIO())

        exc = self.assertRaises(
            SystemExit, trial.Options().parseOptions, ["--help-orders"])
        self.assertEqual(exc.code, 0)

        output = sys.stdout.getvalue()

        msg = "%r with its description not properly described in %r"
        for orderName, (orderDesc, _) in trial._runOrders.items():
            match = re.search(
                "%s.*%s" % (re.escape(orderName), re.escape(orderDesc)),
                output,
            )

            self.assertTrue(match, msg=msg % (orderName, output))


text:
title: "A brand new blog"
tags: ["Code", "Design"]
layout: "post"
comments: true
link: false
---

I've yet again redesigned the layout of this site and this time it's a hell of
a lot different. I grew tired of the old look since it in all honestly looked
boring and decided to give it some colors. I found the typeface
[Roboto](http://www.google.com/webfonts/specimen/Roboto) a few weeks ago and
I like it so much that I decided to use it, which was the first step.

## Hey, what is THAT theme?

The theme is based on [Noah Frederick's](http://noahfrederick.com/) beautiful
[Peppermint
theme](http://noahfrederick.com/blog/2011/lion-terminal-theme-peppermint/) for
the OS X's terminal. I remember stumbling onto his [Hemisu
colorscheme](http://noahfrederick.com/vim-color-scheme-hemisu/) for
[Vim](http://www.vim.org/) and for some reason I also found Peppermint. I even
liked it so much that I hacked together a Vim colorscheme for it that I use
quite a lot.

## Sass + Compass = ♥

I also used [Sass](http://sass-lang.com/) and
[Compass](http://compass-style.org/) exclusively for the CSS writing. I've been
wanting to use it for a long time and I even tried to convert the old design's
CSS to it, but I gave up pretty quickly. This time I didn't and I of course used
[Smallwork](https://github.com/gummesson/smallwork) as a base which made the
process a lot more easier and faster. Redesigning this site was also one of the
things that made me re-write Smallwork.

using Compass with Jekyll is also relatively easy by the way. I first tried out
a couple of plugins, but I decided to implement it in my Rake task instead.
While the plugins worked great it really bugged me that I couldn't decide when
to use `compass compile` and when to use `compass watch`. All I had to do was to
add this to my `build` task in my `Rakefile`, before `jekyll` is run:

{% highlight ruby %}
system "cd assets/ && compass compile && cd ../"
{% endhighlight %}

Simple and effective!

## Fun(ish) trivia

- I started the redesign on March 1st and I've made a total of 28
commits[^20130309-1] to the git repository I used for the development.
- I "skipped" support for Internet Explorer 8 in favor of using
`[class^="column-"]:last-child` to remove the `margin-right` on the grid
system[^20130309-2].
- I also found a pretty cool Sass function called `darken()`, which made it easy
finding a good background color for my `code` and `pre` tags and the subtle text
shadow. All of the color functions for Sass are pretty cool, in fact.
- The pink line at the bottom of the site uses the ["James Dean Sticky
Footer"](http://mystrd.at/modern-clean-css-sticky-footer/) approach, which is
a nice little hack. I love the name too!
- I tried to change as little as possible when I did the CSS for the media
queries. I pratically just changed the font size and some margins. That's it.

* * *

[^20130309-1]: I'm an obsessive commiter.

[^20130309-2]: I doubt that that will cause any problems. I don't think I know anyone that actually use Internet Explorer.

redpajama_set_name: RedPajamaGithub


text:
package org.mengyun.tcctransaction.spring;

import org.aspectj.lang.annotation.Aspect;
import org.mengyun.tcctransaction.interceptor.CompensableTransactionAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;

/**
 * Created by changmingxie on 10/30/15.
 */
@Aspect
public class ConfigurableTransactionAspect extends CompensableTransactionAspect implements Ordered {

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Autowired
    public void setTransactionManager(TransactionManagerFactory transactionManagerFactory) {
        super.setTransactionManager(transactionManagerFactory.getTransactionManager());
    }
}


text:
package de.marx_labs.utilities.common.util;

import java.io.File;
import java.io.FileNotFoundException;

public class FileUtils {
	/**
	 * By default File#delete fails for non-empty directories, it works like "rm". We need something a little more
	 * brutual - this does the equivalent of "rm -r"
	 *
	 * @param path
	 *            Root File Path
	 * @return true iff the file and all sub files/directories have been removed
	 * @throws FileNotFoundException
	 */
	public static boolean deleteRecursive(File path) throws FileNotFoundException {
		if (!path.exists())
			throw new FileNotFoundException(path.getAbsolutePath());
		boolean ret = true;
		if (path.isDirectory()) {
			for (File f : path.listFiles()) {
				ret = ret && FileUtils.deleteRecursive(f);
			}
		}
		return ret && path.delete();
	}
}


text:
1. Create a `config.php` file in the root directory with the database configuration:

```php
<?php

$config['db'] = array(
    'host'     => "localhost",
    'username' => "newuser",
    'password' => "password",
    'dbname'   => "erettsegik",
    'charset'  => 'utf8'
  );
```

For creating users in MySQL, see [this link](https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql).

2. Create the database

```
mysql> create database erettsegik;
```

```
$ mysql -u newuser -p erettsegik < schema.sql
```

3. Install composer dependencies

```
$ composer install
```

4. Run the local PHP server

```
$ php -S localhost:8000
```


text:
import DS from 'ember-data';

export default DS.Model.extend({
    value: DS.attr('number'),
    researcher: DS.attr('string'),
    journal: DS.attr('string'),
    state: DS.attr('number'), // TODO: create transform mapping enum
    fileHash: DS.attr('string'),
    transactionHash: DS.attr('string'),
    contractAddress: DS.attr('string')
});


text:
package com.microsoft.office365.msgraphsnippetapp.snippet;

import com.microsoft.office365.msgraphapiservices.MSGraphMeService;
import com.microsoft.office365.msgraphsnippetapp.R;
import com.microsoft.office365.msgraphsnippetapp.application.SnippetApp;

import retrofit.Callback;
import retrofit.client.Response;

import static com.microsoft.office365.msgraphsnippetapp.R.array.get_me_contacts;

public abstract class MeSnippets<Result> extends AbstractSnippet<MSGraphMeService, Result> {
    /**
     * Snippet constructor
     *
     * @param descriptionArray The String array for the specified snippet
     */
    public MeSnippets(Integer descriptionArray) {
        super(SnippetCategory.meSnippetCategory, descriptionArray);
    }

    static MeSnippets[] getMeSnippets() {
        return new MeSnippets[]{
                // Marker element
                new MeSnippets(null) {
                    @Override
                    public void request(MSGraphMeService service, Callback callback) {
                        // Not implemented
                    }
                },
                // Snippets

                /* Get information about signed in user
                 * HTTP GET https://graph.microsoft.com/{version}/me
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/user_get
                 */
                new MeSnippets<Response>(get_me_contacts) {
                    @Override
                    public void request(MSGraphMeService service, Callback<Response> callback) {
                        service.getMeContacts(
                                getVersion(),
                                callback);
                    }
                }
        };
    }

    @Override
    public abstract void request(MSGraphMeService service, Callback<Result> callback);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-parent</artifactId>
        <version>2.1.0-SNAPSHOT</version>
        <relativePath>../dropwizard-parent</relativePath>
    </parent>

    <artifactId>dropwizard-views-mustache</artifactId>
    <name>Dropwizard Mustache Views</name>

    <dependencies>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-views</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.spullara.mustache.java</groupId>
            <artifactId>compiler</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </dependency>
        <dependency>
            <groupId>jakarta.ws.rs</groupId>
            <artifactId>jakarta.ws.rs-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.test-framework</groupId>
            <artifactId>jersey-test-framework-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-inmemory</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
LIB=	lldReaderWriter

.include <bsd.init.mk>

.PATH: ${LLD_SRCDIR}/lib/ReaderWriter

SRCS+=	CoreLinkingContext.cpp \
	LinkerScript.cpp \
	Reader.cpp \
	ReaderLinkerScript.cpp \
	Writer.cpp

.if defined(HOSTLIB)
.include <bsd.hostlib.mk>
.else
.include <bsd.lib.mk>
.endif


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace WlanProfileViewer.Views.Converters
{
	/// <summary>
	/// Inverse Boolean if indicated and convert it to Visibility.
	/// </summary>
	[ValueConversion(typeof(bool), typeof(Visibility))]
	public class BooleanToVisibilityConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (!(value is bool))
				return DependencyProperty.UnsetValue;

			var sourceValue = (bool)value;

			if (ShouldBeInversed(parameter))
				sourceValue = !sourceValue;

			return sourceValue ? Visibility.Visible : Visibility.Collapsed;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (!(value is Visibility))
				return DependencyProperty.UnsetValue;

			var convertedValue = ((Visibility)value == Visibility.Visible);

			if (ShouldBeInversed(parameter))
				convertedValue = !convertedValue;

			return convertedValue;
		}

		private static bool ShouldBeInversed(object parameter)
		{
			var indication = parameter?.ToString().Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase);

			// If parameter is given and it is false string, the value will be inversed.
			return (indication == true);
		}
	}
}


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>The Work Programme - Government initiatives - GOV.UK</title>
<link href="https://assets.digital.cabinet-office.gov.uk/static/govuk-template-6820d35a129a3ffde628d8447156c5dc.css" media="screen" rel="stylesheet" type="text/css">
<link href="https://assets.digital.cabinet-office.gov.uk/static/govuk-template-print-95606431bbfe23b0e4ee9e5ed3346c47.css" media="print" rel="stylesheet" type="text/css">
<link href="https://assets.digital.cabinet-office.gov.uk/static/fonts-83e596ae63d072e22b7f34d2b5482bde.css" media="all" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="https://assets.digital.cabinet-office.gov.uk/static/favicon-9269d2d9f40d20236f60a3dbc448679a.ico" type="image/x-icon">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://assets.digital.cabinet-office.gov.uk/static/apple-touch-icon-152x152-58591dcff066ba321b89a9e208ccedab.png">
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://assets.digital.cabinet-office.gov.uk/static/apple-touch-icon-120x120-b6a680ead8eb531b9c28cc056836ad06.png">
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="https://assets.digital.cabinet-office.gov.uk/static/apple-touch-icon-76x76-17dd3f1e168561f9099ba92e3292e607.png">
<link rel="apple-touch-icon-precomposed" href="https://assets.digital.cabinet-office.gov.uk/static/apple-touch-icon-60x60-dc9aa421bedcf2c08c4e8f3f230f780d.png">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:image" content="https://assets.digital.cabinet-office.gov.uk/static/opengraph-image-85fc698c83c77d8d8cb5467a44cc12a5.png">
<link href="https://assets.digital.cabinet-office.gov.uk/static/header-footer-only-ee5a70cd95d6d0a46678d701e422ed11.css" media="screen" rel="stylesheet" type="text/css">
<link href="https://assets.digital.cabinet-office.gov.uk/static/print-a510f019943a387a36079430ead3dda8.css" media="print" rel="stylesheet" type="text/css">
<link href="https://assets.digital.cabinet-office.gov.uk/government/assets/frontend/base-32de62f14953cde7e15d596b7cb572aa.css" media="screen" rel="stylesheet" type="text/css">
<link href="https://assets.digital.cabinet-office.gov.uk/government/assets/frontend/print-c7cd828c0de1f797a1dbeda384ee3265.css" media="print" rel="stylesheet" type="text/css">
<link href="https://www.gov.uk/government/feed" rel="alternate" title="Recent updates" type="application/atom+xml">
<meta content="True" name="HandheldFriendly">
<meta content="320" name="MobileOptimized">
<meta content="How the government is getting Britain working and helping people break the cycle of benefit dependency." name="description">
<meta content="authenticity_token" name="csrf-param">
<meta content="PeH+b9OlESVVbXMUBTDKOEzojDbZ5KObWJe+PBGIV0Y=" name="csrf-token">

        Skip to main content

GOV.UK uses cookies to make the site simpler. Find out more about cookies

               GOV.UK

            Search

  <form id="search" class="site-search" action="/search" method="get" role="search">

      Search
      <input type="search" name="q" id="site-search-text" title="Search" class="js-search-focus"><input class="submit" type="submit" value="Search">

  </form>

    Menu

Departments

Worldwide

How government works

Get involved

Policies

Publications

Consultations

Statistics

Announcements

Government initiative

The Work Programme

From:

Department for Work and Pensions

Topics:

Employment and Welfare

Policy areas:

Employment

Background

Latest

Contents

Evaluation, 2013

Scheme rollout, 2011

Consultation, 2011

White paper, 2010

Evaluation, 2013

Lorem ipsum dolor sit amet, cu sea everti recusabo, consul everti graecis vix et. No ocurreret argumentum usu, ea cum posse regione. Eripuit veritus eu ius, eu mediocrem expetenda definiebas sit, his cu cibo possit intellegat. Vix oportere scriptorem et, ei cibo tollit mediocritatem vel. Hinc vituperata his ea. No meis clita usu.

Scheme rollout, 2011

Lorem ipsum dolor sit amet, cu sea everti recusabo, consul everti graecis vix et. No ocurreret argumentum usu, ea cum posse regione. Eripuit veritus eu ius, eu mediocrem expetenda definiebas sit, his cu cibo possit intellegat. Vix oportere scriptorem et, ei cibo tollit mediocritatem vel. Hinc vituperata his ea. No meis clita usu.

Consultation, 2011

Lorem ipsum dolor sit amet, cu sea everti recusabo, consul everti graecis vix et. No ocurreret argumentum usu, ea cum posse regione. Eripuit veritus eu ius, eu mediocrem expetenda definiebas sit, his cu cibo possit intellegat. Vix oportere scriptorem et, ei cibo tollit mediocritatem vel. Hinc vituperata his ea. No meis clita usu.

White Paper, 2010

Lorem ipsum dolor sit amet, cu sea everti recusabo, consul everti graecis vix et. No ocurreret argumentum usu, ea cum posse regione. Eripuit veritus eu ius, eu mediocrem expetenda definiebas sit, his cu cibo possit intellegat. Vix oportere scriptorem et, ei cibo tollit mediocritatem vel. Hinc vituperata his ea. No meis clita usu.

Published:

16 April 2013

Updated:

10 October 2014

+ full page history

10 October 2014  9:27am

Updated the information about Fit for Work, previously known as the Health and Work Service, on the Co-ordinating the Health, Work and Wellbeing initiative detail page.

 6 August 2014 12:01am

Removed references to the Wage Incentive.

29 July 2014  2:42pm

Added link to announcement about the supplier of the Health and Work Service.

17 July 2014  7:00am

Added information about the Wage Incentive being withdrawn from 6 August 2014.
.

13 June 2014  9:30am

Published 'Fuller Working Lives: a framework for action' that sets out new actions we will take to help people have fuller working lives.

18 March 2014  9:43am

Updated to reflect further details of Tax-Free Childcare following consultation - the scheme to be increased up to £2,000 per child and extended to all children under 12 within the first year.

12 March 2014 12:16pm

Added information about how the Ethnic Minority Employment Stakeholder Group support this policy.

17 February 2014 10:23am

Published more information about the new Health and Work Service, including a link to the invitation to tender.

12 December 2013  9:47am

Health and Work Service - added information about tax exemption for occupational health treatments following the Autumn Statement 2013.

 8 August 2013  9:29am

Welfare reform communications toolkit link added.

15 July 2013 10:07am

Added "Co-ordinating the health, work and wellbeing initiative"

15 July 2013 10:07am

Detail added: Co-ordinating the Health, Work and Wellbeing initiative

16 April 2013 10:00am

First published.

16 April 2013 10:00am

Detail added: Helping older people who want to find or stay in work

16 April 2013 10:00am

Detail added: Introducing a tax-free childcare scheme

From:

Department for Work and Pensions

Help us improve GOV.UK

      <form accept-charset="UTF-8" action="/contact/govuk/problem_reports" method="post">

<input name="utf8" type="hidden" value="✓">

        <input id="url" name="url" type="hidden" value="https://www.gov.uk/government/policies/helping-people-to-find-and-stay-in-work"><input id="source" name="source" type="hidden" value="inside_government"><input id="page_owner" name="page_owner" type="hidden" value="dwp">
Please don't include any personal or financial information,
          for example your National Insurance or credit card numbers.

        What you were doing
        <input id="what_doing" name="what_doing" type="text">What went wrong
        <input id="what_wrong" name="what_wrong" type="text">

          <button name="commit" type="submit" class="button">Send</button>

      </form>

Services and information

Benefits

Births, deaths, marriages and care

Business and self-employed

Citizenship and living in the UK

Crime, justice and the law

Disabled people

Driving and transport

Education and learning

Employing people

Environment and countryside

Housing and local services

Money and tax

Passports, travel and living abroad

Visas and immigration

Working, jobs and pensions

Departments and policy

How government works

Departments

Worldwide

Policies

Publications

Announcements

Support links

Help

Cookies

Contact

Cymraeg

Built by the Government Digital Service

Open Government Licence

All content is available under the Open Government Licence v3.0, except where otherwise stated

            © Crown copyright


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 224 (1934)

#### Original name
Sclerotinia cylindrica Velen.

### Remarks
null


text:
PATH=/bin:/usr/bin:./tools
boot_dir := boot

iso: system.img keepod.iso

system.img:
	tools/mkuserimg.sh system system.img ext4 system 0 file_contexts
	mksquashfs system.img boot/system.sfs -noappend
	rm keepod.iso

keepod.iso: $(boot_dir)
	genisoimage -vJURT -b isolinux/isolinux.bin -c isolinux/boot.cat \
                -no-emul-boot -boot-load-size 4 -boot-info-table \
                -input-charset utf-8 -V "Android-x86 LiveCD" -o $@ $^


text:
#include <XEngine/Animation/Nodes/MathMinusNode.h>
#include <XEngine/Animation/Port.h>
using namespace XE;

MathMinusNode::MathMinusNode()
: Node()
, m_aPort( NULL )
, m_bPort( NULL )
{
	m_aPort = createPort(6);// "in0" );
	m_bPort = createPort(7);// "in1" );
}

MathMinusNode::~MathMinusNode()
{
}

Port* MathMinusNode::getAPort()
{
	return m_aPort;
}

const Port* MathMinusNode::getAPort() const
{
	return m_aPort;
}

Port* MathMinusNode::getBPort()
{
	return m_bPort;
}

const Port* MathMinusNode::getBPort() const
{
	return m_bPort;
}

float MathMinusNode::evaluateValue(double deltaTime)
{
	float valueA = getAPort()->evaluateValue(deltaTime);
	float valueB = getBPort()->evaluateValue(deltaTime);

	return valueA - valueB;
}


text:
layout: default
---

{{ page.title }}

        {{ content }}


text:
class EnvironmentEntity < Grape::Entity
  include RequestAwareEntity

  expose :id
  expose :name
  expose :state
  expose :external_url
  expose :environment_type
  expose :last_deployment, using: DeploymentEntity
  expose :stop_action?

  expose :metrics_path, if: -> (environment, _) { environment.has_metrics? } do |environment|
    metrics_namespace_project_environment_path(
      environment.project.namespace,
      environment.project,
      environment)
  end

  expose :environment_path do |environment|
    namespace_project_environment_path(
      environment.project.namespace,
      environment.project,
      environment)
  end

  expose :stop_path do |environment|
    stop_namespace_project_environment_path(
      environment.project.namespace,
      environment.project,
      environment)
  end

  expose :terminal_path, if: ->(environment, _) { environment.has_terminals? } do |environment|
    can?(request.current_user, :admin_environment, environment.project) &&
      terminal_namespace_project_environment_path(
        environment.project.namespace,
        environment.project,
        environment)
  end

  expose :created_at, :updated_at
end


text:
package com.grsu.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Специальность
 */
@Entity
@Table(name = "speciality")
public class Speciality implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Long id;

    /**
     * Название
     */
    @Column
    private String name;

    /**
     * Код специальности
     */
    @Column
    private String code;

    /**
     * Цена специальности
     */
    @Column
    private Double price;

    /**
     * Возможность бесплатного обучения
     */
    @Column(name = "free_education")
    private Boolean freeEducation;

    /**
     * Факультет
     */
    @ManyToOne
    @JoinColumn(name = "faculty_id")
    @JsonIgnore
    private Faculty faculty;

    /**
     * Продолжительность обучения
     */
    @Column
    private Integer duration;

    /**
     * Формы обучения
     */
    @ManyToMany
    @JoinTable(name = "speciality_form_of_education",
            joinColumns = @JoinColumn(name = "speciality_id"),
            inverseJoinColumns = @JoinColumn(name = "form_of_education_id"))
    private List<FormOfEducation> formsOfEducation = new ArrayList<>();

    /**
     * Языки обучения
     */
    @ManyToMany
    @JoinTable(name = "speciality_language_learning",
            joinColumns = @JoinColumn(name = "speciality_id"),
            inverseJoinColumns = @JoinColumn(name = "language_learning_id"))
    private List<LanguageLearning> languagesLearning = new ArrayList<>();

    /**
     * Уровень образования
     */
    @ManyToMany
    @JoinTable(name = "speciality_level_of_education",
            joinColumns = @JoinColumn(name = "speciality_id"),
            inverseJoinColumns = @JoinColumn(name = "level_of_education_id"))
    private List<LevelOfEducation> levelsOfEducation = new ArrayList<>();

    /**
     * Направления
     */
    @ManyToMany
    @JoinTable(name = "speciality_direction",
            joinColumns = @JoinColumn(name = "speciality_id"),
            inverseJoinColumns = @JoinColumn(name = "direction_id"))
    private List<Direction> directions = new ArrayList<>();

    public Speciality() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Boolean getFreeEducation() {
        return freeEducation;
    }

    public void setFreeEducation(Boolean freeEducation) {
        this.freeEducation = freeEducation;
    }

    public List<FormOfEducation> getFormsOfEducation() {
        return formsOfEducation;
    }

    public void setFormsOfEducation(List<FormOfEducation> formsOfEducation) {
        this.formsOfEducation = formsOfEducation;
    }

    public List<LanguageLearning> getLanguagesLearning() {
        return languagesLearning;
    }

    public void setLanguagesLearning(List<LanguageLearning> languagesLearning) {
        this.languagesLearning = languagesLearning;
    }

    public Faculty getFaculty() {
        return faculty;
    }

    public void setFaculty(Faculty faculty) {
        this.faculty = faculty;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public List<LevelOfEducation> getLevelsOfEducation() {
        return levelsOfEducation;
    }

    public void setLevelsOfEducation(List<LevelOfEducation> levelsOfEducation) {
        this.levelsOfEducation = levelsOfEducation;
    }

    public List<Direction> getDirections() {
        return directions;
    }

    public void setDirections(List<Direction> directions) {
        this.directions = directions;
    }
}


text:
import argparse
import collections
import os
import re
import shutil
import sys
import tempfile
import zipfile

import devil_chromium
from devil.android.sdk import dexdump
from pylib.constants import host_paths

sys.path.append(os.path.join(host_paths.DIR_SOURCE_ROOT, 'build', 'util', 'lib',
                             'common'))
import perf_tests_results_helper # pylint: disable=import-error

# Example dexdump output:
# DEX file header:
# magic               : 'dex\n035\0'
# checksum            : b664fc68
# signature           : ae73...87f1
# file_size           : 4579656
# header_size         : 112
# link_size           : 0
# link_off            : 0 (0x000000)
# string_ids_size     : 46148
# string_ids_off      : 112 (0x000070)
# type_ids_size       : 5730
# type_ids_off        : 184704 (0x02d180)
# proto_ids_size      : 8289
# proto_ids_off       : 207624 (0x032b08)
# field_ids_size      : 17854
# field_ids_off       : 307092 (0x04af94)
# method_ids_size     : 33699
# method_ids_off      : 449924 (0x06dd84)
# class_defs_size     : 2616
# class_defs_off      : 719516 (0x0afa9c)
# data_size           : 3776428
# data_off            : 803228 (0x0c419c)

# For what these mean, refer to:
# https://source.android.com/devices/tech/dalvik/dex-format.html

_CONTRIBUTORS_TO_DEX_CACHE = {'type_ids_size': 'types',
                              'string_ids_size': 'strings',
                              'method_ids_size': 'methods',
                              'field_ids_size': 'fields'}

def _ExtractSizesFromDexFile(dex_path):
  counts = {}
  for line in dexdump.DexDump(dex_path, file_summary=True):
    if not line.strip():
      # Each method, type, field, and string contributes 4 bytes (1 reference)
      # to our DexCache size.
      counts['dex_cache_size'] = (
          sum(counts[x] for x in _CONTRIBUTORS_TO_DEX_CACHE)) * 4
      return counts
    m = re.match(r'([a-z_]+_size) *: (\d+)', line)
    if m:
      counts[m.group(1)] = int(m.group(2))
  raise Exception('Unexpected end of output.')

def _ExtractSizesFromZip(path):
  tmpdir = tempfile.mkdtemp(suffix='_dex_extract')
  try:
    counts = collections.defaultdict(int)
    with zipfile.ZipFile(path, 'r') as z:
      for subpath in z.namelist():
        if not subpath.endswith('.dex'):
          continue
        extracted_path = z.extract(subpath, tmpdir)
        cur_counts = _ExtractSizesFromDexFile(extracted_path)
        for k in cur_counts:
          counts[k] += cur_counts[k]
    return dict(counts)
  finally:
    shutil.rmtree(tmpdir)

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--apk-name', help='Name of the APK to which the dexfile corresponds.')
  parser.add_argument('dexfile')

  args = parser.parse_args()

  devil_chromium.Initialize()

  if not args.apk_name:
    dirname, basename = os.path.split(args.dexfile)
    while basename:
      if 'apk' in basename:
        args.apk_name = basename
        break
      dirname, basename = os.path.split(dirname)
    else:
      parser.error(
          'Unable to determine apk name from %s, '
          'and --apk-name was not provided.' % args.dexfile)

  if os.path.splitext(args.dexfile)[1] in ('.zip', '.apk', '.jar'):
    sizes = _ExtractSizesFromZip(args.dexfile)
  else:
    sizes = _ExtractSizesFromDexFile(args.dexfile)

  def print_result(name, value_key, description=None):
    perf_tests_results_helper.PrintPerfResult(
        '%s_%s' % (args.apk_name, name), 'total', [sizes[value_key]],
        description or name)

  for dex_header_name, readable_name in _CONTRIBUTORS_TO_DEX_CACHE.iteritems():
    print_result(readable_name, dex_header_name)
  print_result(
      'DexCache_size', 'dex_cache_size', 'bytes of permanent dirty memory')
  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Services.Journal
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;

    using DotNetNuke.Services.Tokens;

    public class JournalEntity : IPropertyAccess
    {
        public JournalEntity()
        {
        }

        public JournalEntity(string entityXML)
        {
            if (!string.IsNullOrEmpty(entityXML))
            {
                XmlDocument xDoc = new XmlDocument { XmlResolver = null };
                xDoc.LoadXml(entityXML);
                if (xDoc != null)
                {
                    XmlNode xRoot = xDoc.DocumentElement;
                    XmlNode xNode = null;
                    xNode = xRoot.SelectSingleNode("//entity");
                    if (xNode != null)
                    {
                        this.Id = int.Parse(xNode["id"].InnerText);
                        this.Name = xNode["name"].InnerText.ToString();
                        if (xNode["vanity"] != null)
                        {
                            this.Vanity = xNode["vanity"].InnerText.ToString();
                        }
                    }
                }
            }
        }

        public CacheLevel Cacheability
        {
            get { return CacheLevel.fullyCacheable; }
        }

        public int Id { get; set; }

        public string Name { get; set; }

        public string Vanity { get; set; }

        public string Avatar { get; set; }

        public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound)
        {
            string OutputFormat = string.Empty;
            if (format == string.Empty)
            {
                OutputFormat = "g";
            }
            else
            {
                OutputFormat = format;
            }

            propertyName = propertyName.ToLowerInvariant();
            switch (propertyName)
            {
                case "id":
                    return PropertyAccess.FormatString(this.Id.ToString(), format);
                case "name":
                    return PropertyAccess.FormatString(this.Name.ToString(), format);
                case "vanity":
                    return PropertyAccess.FormatString(this.Vanity.ToString(), format);
                case "avatar":
                    return PropertyAccess.FormatString(this.Avatar.ToString(), format);
            }

            propertyNotFound = true;
            return string.Empty;
        }
    }
}


text:
<?php

namespace Calor\ApiBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Calor\ApiBundle\Entity\User;

/**
 * MealRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MealRepository extends EntityRepository
{
    public function getList($filter, $page, $perPage){
        $qb = $this->createQueryBuilder('m');
        if(isset($filter['user'])){
            $qb->where('m.user = :user')->setParameter('user', $filter['user']->getId());
        }

        if(isset($filter['date'])){
            $qb->andWhere('m.date >= :date0')->setParameter('date0', $filter['date'][0]);
            $qb->andWhere('m.date <= :date1')->setParameter('date1', $filter['date'][1]);
        }

        if(isset($filter['time'])){
            $qb->andWhere('m.time >= :time0')->setParameter('time0', $filter['time'][0]);
            $qb->andWhere('m.time <= :time1')->setParameter('time1', $filter['time'][1]);
        }

        if(isset($filter['name'])){
            $qb->andWhere('m.name LIKE :name')->setParameter('name', '%'.$filter['name'].'%');
        }
        $qb->addSelect('m.id');

        $totalQB = $qb->getQuery();

        $total = count($totalQB->getResult());

        $qb->setFirstResult(($page-1)*$perPage);
        $qb->setMaxResults($perPage);
        $list = $qb->getQuery()->getResult();

        return array('total'=>$total, 'page'=>$page, 'list'=>$list);
    }

    public function getReport($filter, $mode){

        $emConfig = $this->getEntityManager()->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
        $emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
        $emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
        $emConfig->addCustomDatetimeFunction('DATE_FORMAT', 'DoctrineExtensions\Query\Mysql\DateFormat');

        $qb = $this->createQueryBuilder('m');
        $qb->select('SUM(m.calories) as total');

        if(isset($filter['user'])){
            $qb->where('m.user = :user')->setParameter('user', $filter['user']->getId());
        }

        if(isset($filter['date'])){
            $qb->andWhere('m.date >= :date0')->setParameter('date0', $filter['date'][0]);
            $qb->andWhere('m.date <= :date1')->setParameter('date1', $filter['date'][1]);
        }

        if(isset($filter['time'])){
            $qb->andWhere('m.time >= :time0')->setParameter('time0', $filter['time'][0]);
            $qb->andWhere('m.time <= :time1')->setParameter('time1', $filter['time'][1]);
        }

        if($mode == 'daily'){
            $qb->groupBy('m.date');
            $qb->addSelect("DATE_FORMAT(m.date, '%Y-%m-%d') as day");
            $qb->addSelect('YEAR(m.date) as year');
            $qb->addSelect('MONTH(m.date) as month');
        }

        if($mode == 'monthly'){
            $qb->addSelect('YEAR(m.date) as year');
            $qb->addSelect('MONTH(m.date) as month');
            $qb->groupBy('year')->addGroupBy('month');
        }

        if($mode == 'yearly'){
            $qb->addSelect('YEAR(m.date) as year');
            $qb->groupBy('year');
        }

        $report = $qb->getQuery()->getResult();
        return $report;

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fossil Spores and Pollen of China (Beijing) 1: 23 + pl. 12, fig. 2 (1999)

#### Original name
Multicellaesporites spindlus Z.C. Song, Qian & Y.H. Zheng

### Remarks
null


text:
ca-burlington-transit-bus-parser
================================

Parser for Burlington Transit Bus data


text:
import os
import shutil
import time
import sys
from .Utilities import is_chip_pro

DEBUG = False

OVERLAYINSTALLPATH = "/lib/firmware/nextthingco/chip"
OVERLAYCONFIGPATH  = "/sys/kernel/config/device-tree/overlays"
CUSTOMOVERLAYFILEPATH = ""

PWMSYSFSPATH = "/sys/class/pwm/pwmchip0"
# USING THE BASE DIRECTORY FOR SPI AS THE DEVICE NUMBER CHANGES ON LOAD/UNLOAD
SPI2SYSFSPATH = "/sys/class/spi_master/"

# LOADED VARIABLES
# DO NOT MODIFY BY HAND WHEN USING
# AS IT COULD BREAK FUNCTIONALITY
_LOADED = {
  "SPI2" : False,
  "PWM0" : False,
  "CUST" : False
}

_OVERLAYS = {
  "SPI2" : "sample-spi.dtbo",
  "PWM0" : "sample-pwm.dtbo",
  "CUST" : ""
}

_FOLDERS = {
  "SPI2" : "chip-spi",
  "PWM0" : "chip-pwm",
  "CUST" : "chip-cust"
}

def toggle_debug():
    global DEBUG
    if DEBUG:
        DEBUG = False
        print("debug disabled")
    else:
        DEBUG = True
        print("debug enabled")

def get_spi_loaded():
    """
     get_spi_loaded - Returns True/False based upon if the spi2 Overlay is loaded
    """
    global _LOADED
    return _LOADED["SPI2"]

def get_pwm_loaded():
    """
     get_pwm_loaded - Returns True/False based upon if the pwm0 Overlay is loaded
    """
    global _LOADED
    return _LOADED["PWM0"]

def get_custom_loaded():
    """
     get_custom_loaded - Returns True/False based upon if a Custom Overlay is loaded
    """
    global _LOADED
    return _LOADED["CUST"]

def _set_overlay_verify(name, overlay_path, config_path):
    """
     _set_overlay_verify - Function to load the overlay and verify it was setup properly
    """
    global DEBUG
    # VERIFY PATH IS NOT THERE
    if os.path.exists(config_path):
        print("Config path already exists! Not moving forward")
        print("config_path: {0}".format(config_path))
        return -1

    # MAKE THE CONFIGURATION PATH
    os.makedirs(config_path)

    # CAT THE OVERLAY INTO THE CONFIG FILESYSTEM
    with open(config_path + "/dtbo", 'wb') as outfile:
        with open(overlay_path, 'rb') as infile:
            shutil.copyfileobj(infile, outfile)

    # SLEEP TO ENABLE THE KERNEL TO DO ITS JOB
    time.sleep(0.2)

    # VERIFY
    if name == "CUST":
        # BLINDLY ACCEPT THAT IT LOADED
        return 0
    elif name == "PWM0":
        if os.path.exists(PWMSYSFSPATH):
            if DEBUG:
                print("PWM IS LOADED!")
            return 0
        else:
            if DEBUG:
                print("ERROR LOAIDNG PWM0")
            return 1
    elif name == "SPI2":
        if os.listdir(SPI2SYSFSPATH) != "":
            if DEBUG:
                print("SPI2 IS LOADED!")
            return 0
        else:
            if DEBUG:
                print("ERROR LOADING SPI2")
            return 0

def load(overlay, path=""):
    """
     load - Load a DTB Overlay

     Inputs:
      overlay - Overlay Key: SPI2, PWM0, CUST
      path    - Full Path to where the custom overlay is stored

     Returns:
      0 - Successful Load
      1 - Unsuccessful Load
      2 - Overlay was previously set
    """
    global DEBUG
    global _LOADED
    if DEBUG:
        print("LOAD OVERLAY: {0} @ {1}".format(overlay,path))
    # SEE IF OUR OVERLAY NAME IS IN THE KEYS
    if overlay.upper() in _OVERLAYS.keys():
        cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]
        if DEBUG:
            print("VALID OVERLAY")
            print("CONFIG PATH:  {0}".format(cpath))
        # CHECK TO SEE IF WE HAVE A PATH FOR CUSTOM OVERLAY
        if overlay.upper() == "CUST" and path == "":
            raise ValueError("Path must be specified for Custom Overlay Choice")
        elif overlay.upper() == "CUST" and _LOADED[overlay.upper()]:
            print("Custom Overlay already loaded")
            return 2
        elif overlay.upper() == "CUST" and not os.path.exists(path):
            print("Custom Overlay path does not exist")
            return 1

        # DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO LOAD PWM0
        if is_chip_pro() and overlay.upper() == "PWM0":
            print("CHIP Pro supports PWM0 in base DTB, exiting")
            return 1

        # SET UP THE OVERLAY PATH FOR OUR USE
        if overlay.upper() != "CUST":
            opath = OVERLAYINSTALLPATH
            opath += "/" + _OVERLAYS[overlay.upper()]
        else:
            opath = path
        if DEBUG:
            print("OVERLAY PATH: {0}".format(opath))

        if overlay.upper() == "PWM0" and _LOADED[overlay.upper()]:
            print("PWM0 Overlay already loaded")
            return 2

        if overlay.upper() == "SPI2" and _LOADED[overlay.upper()]:
            print("SPI2 Overlay already loaded")
            return 2

        # LOAD THE OVERLAY
        errc = _set_overlay_verify(overlay.upper(), opath, cpath)
        if DEBUG:
            print("_SET_OVERLAY_VERIFY ERRC: {0}".format(errc))
        if errc == 0:
            _LOADED[overlay.upper()] = True

    else:
        raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST")

def unload(overlay):
    global DEBUG
    global _LOADED
    if DEBUG:
        print("UNLOAD OVERLAY: {0}".format(overlay))

    # DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO UNLOAD PWM0
    if is_chip_pro() and overlay.upper() == "PWM0":
        print("CHIP Pro supports PWM0 in base DTB, exiting")
        return

    # SEE IF OUR OVERLAY NAME IS IN THE KEYS
    if overlay.upper() in _OVERLAYS.keys():
        # BRUTE FORCE REMOVE AS THE DIRECTORY CONTAINS FILES
        os.system('rmdir \"{}\"'.format(OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]))
        _LOADED[overlay.upper()] = False
    else:
        raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST")


text:
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = require('./_export')
    , toIObject = require('./_to-iobject')
    , arrayJoin = [].join;

// fallback for not array-like strings
$export($export.P + $export.F * (require('./_iobject') != Object || !require('./_strict-method')(arrayJoin)), 'Array', {
    join: function join(separator) {
        return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
    }
});


text:
class TestPolicy < ApplicationPolicy

  def rails_admin?(action)
    case action
      when :destroy, :new
        false
      else
        super
    end
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json;

namespace DebuggerTesting.OpenDebug.Commands.Responses
{
    public sealed class ThreadsResponseValue : CommandResponseValue
    {
        public sealed class Body
        {
            public sealed class Thread
            {
                [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
                public int? id;

                [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
                public string name;
            }

            public Thread[] threads;
        }

        public Body body = new Body();
    }
}


text:
Most if not all projects at one point or another will have to provide multilingual support.

Adding i18n support in aurelia is as easy as adding the [aurelia-i18n](https://github.com/aurelia/i18n) plugin and [configuring it](http://aurelia.io/hub.html#/doc/article/aurelia/i18n/latest/i18n-with-aurelia).

But as a project becomes larger, centralizing your logic into reusable components is the way to go.

This article describes a way of combining aurelia's value-converters with i18n, to allow reusing them in your locales.

A live preview can be found [here](https://peterver.github.io/aurelia-i18n-value-converters/).

###0. Getting Started

Create a new aurelia project by running `au new` (assuming you are using the [aurelia-cli](http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/the-aurelia-cli/1)).

After this has completed, follow the steps at the [i18n-with-aurelia hub section](http://aurelia.io/hub.html#/doc/article/aurelia/i18n/latest/i18n-with-aurelia/1) to configure your aurelia project for internationalization.

###1. Adjust the i18n configuration to allow for value-converter support

Aurelia-i18n is a wrapper that does two things, and it does it well.

- It acts as a proxy around [i18next](https://www.i18next.com) to allow you to configure an aurelia application for i18next support.
- It provides some syntactic sugar to allow for easier translations

The fact that it acts as a proxy, allows us to still hook into the **i18next instance** without too much hassle.

i18next provides [interpolation](http://i18next.com/translate/interpolation/) support, this is a way of defining how the specific key-value pairs in your locale file should be processed.

Aurelia provides thin wrappers such as the *df (dateFormat)* value converter for hooking into this. But what if we wanted to add our own custom value converters into the mix?

A very interesting configuration option for i18next's interpolation feature is the [format](http://i18next.com/translate/formatting/) property. This provides us with a hook into the processing pipeline of i18next. Go ahead and extend your i18n configuration like so:

```javascript
return instance.setup({
	// ...
	interpolation : {
		format : function (value, format, lng) {
			const parts = format.split(':');

			//  Check if the value converter is registered as a resource
			const vc = aurelia.resources.valueConverters[parts.shift()];

			return vc ? vc.toView(value, ...parts) : value;
		}
	}
	// ...
});
```

There's a couple of things going on here, let's use an example to explain this step by step.

###2. Using value converters in your locales, an example

Let's consider a value converter called `formatDate`, all this value converter does is receive a date and a format, and return a string representation of that date in the provided format. To make that easier, we're using the date manipulation library [Moment.js](https://momentjs.com/)

```javascript
import moment from 'moment';

export class FormatDateValueConverter {
  toView (value, format) {
    return moment(value, 'YYYY-MM-DD').format(format);
  }
}

```

To use this in your view you could have a setup like so:

```html
<span t="a" t-params.bind="{date: '2017-02-20}"></span>
```

And your locale file could look like this:

```json
{
  "a" : "Today's date is : {{date, formatDate:MMMM D YYYY}}"
}
```

When executed, i18next will recognize that the key you're trying to translate contains a section that needs to be interpolated (because of the default prefix and suffix `{{ ... }}` in your locale file).

> Make sure to visit the i18next [docs section](http://i18next.com/docs/options/#interpolation-options) targeting the interpolation options for further info

As such it will execute the *interpolation.format* function that we configured in the previous step. This function will receive a value, format and an optional lng parameter

- Value : The date that we passed, in this case it will be `2017-02-20`
- Format : Our locale file will define this as being `formatDate:MMMM D YYYY`

Our interpolation function will split the format on the `:` character to become `['formatDate', 'MMMM D YYYY']` where the first part (*formatDate*) would be the name of the value converter we want to use, and the second part (*MMMM D YYYY*) would be the format parameter our value converter requires. Our format function will then look for the value converter in aurelia's registered resources, and will execute the `toView` function with the provided parameters.

And behold, the eventual result would be : ```Today's date is : February 20 2017```

### Take note

- If no value converter was registered under the name that you're trying to format, it will simply render the value of the variable you passed to it.
- This approach will only work if the value converter that you are trying to use is registered as a global resource.
- Using this approach, you could easily pass in additional parameters to your value converter by doing the following : ```valueConverterName:param1:param2:param3```

### Conclusion
Extending aurelia-i18n is extremely easy, and i'd definitely encourage anyone to try this for him/herself.

For example try writing any of the following and see for yourselves

- A value converter to render out currency values using something like [numeral](http://numeraljs.com/)!
- A value converter to automatically render out a person's fullname, when provided with an object containing personal details
- Automatically prefix the correct title (Miss/Mr./...) based on the locale
- ... Anything you can imagine :)

But most of all, have fun and be creative!


text:
<TITLE>Review for My Favorite Martian (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

My Favorite Martian (1999)

reviewed by
David Wilcock

My Favourite Martian

Starring Jeff Daniels, Christopher Lloyd, Elizabeth Hurley and Darryl Hannah
Directed By Donald Petrie
Running Time: 1 hour 33 minutes

(Walt Disney Pictures)

I love movies. I really do. Every time I watch great movies like Goodfellas
(1990) or Raiders of the Lost Ark (1981), a tear comes to my eye due to the
awesome talent, skill and entertainment that is on display. Even lower grade
films such as The Naked Gun 33 1/3 (1994) or Ghostbusters II (1988) while
not exactly brilliantly well made, are certainly not a waste of celluloid
and present entertainment value. Then there's My Favourite Martian, the
exact opposite of what a movie should be: a hurried, poorly written and
acted movie with one goal, to make money. Disney, ever since The Lion King
(1994) have lost their magic touch, but this dross just shows how far Disney
have sunk.

Christopher Lloyd plays a Martian who crash lands in front of T.V reporter's
Tim O'Hara car (Daniels), and soon Tim finds the Martian in his home, trying
to recover and fix his spaceship. Along with his 'Zoot' spacesuit, voiced by
Wayne Knight, must fix his spaceship before it explodes, and also try to
stop his identity being revealed to the public, firstly by O'Hara, but later
by rival T.V presenter Brace Channing (Hurley), by calling himself Tim's
'Uncle Martin.' 'Laughter' is supposed to arise from the 'comical' events,
but never does.

Many bad films have good intentions, but My Favourite Martian doesn't appear
to try to provide any entertainment. Filled to the brim with wham bang
special effects,  My Favourite Martian offers little more than some nice eye
candy. Christopher Lloyd mugs his way through the entire movie, I've never
seen a man pull a face for 93 minutes until now. Jeff Daniels plays 'staple
nice guy' and his role is useless. His performance is incredibly lazy,
although his paperthin character doesn't deserve more than the performance
he gives. Darryl Hannah looks as pretty as ever, but her role is somewhat,
erm, limited. Hurley mistakes 'acting' for 'shouting and looking like a
twit' and wins the David Wilcock award for 'Most Irritating, Godawful
Performance in a Moving Picture.' Way to go Liz! For the supporting cast,
Disney manage to assemble every character actor out there, during the film I
was going 'he was the guy in...ah..er...' before finally giving up and
switching off.

Another major setback is the staple 'comedy sidekick.' Unfortunately, the
writers (Sherri Stoner and Deanna Oliver, if anyone cares) forget that a
comedy sidekick needs to be 'funny.' Instead, they deliver Zoot, the
Martians deeply unfunny sidekick. Although meant to be a manic character no
doubt, every line that comes out of his 'neck' is a dud. A real dud. Citizen
Kane delivers more laughs a minute than his hell spawn piece of polyester.
Even the kids in the audience were insulted by this character: not one child
even bothered to smirk. It's a nice special effect, though.

Another problems with this comedy are the gags themselves. Or rather, the
lack of them. My Favourite Martian reaches a new level of toilet humour: it
goes past the bowl, down the pipe and into the sewer. Now, toilet humour can
be funny, as Dumb and Dumber (1994) humorously showed. But here, characters
farting, belching and almost getting crapped on (literally) is not
'amusing.' It's insulting. There's one good gag right before the credits,
but it appears the guy who wrote that gag tragically died and his unfunny
twin continued. Either that, or they were hoping that easy to please six
year olds wouldn't mind the fact that his movie is beaten by Men At Work in
the funny stakes. Yes, Men At Work. Yowza!

The fact that a lot of money was pumped into this film, and that they
actually got people to agree to be in this film just depresses me even more.
There are thousands of brilliant films out there that can't get
distribution, yet trash like this gets released nation-wide with ease.
Thankfully, as soon as it makes it's money, it will never be seen again, and
My Favourite Martian will end up where the two lead characters do near the
end of the movie: down the toilet.

RATING=* OUT OF *****

A David Wilcock Review ©1999

DAVID WILCOCK
david.wilcock@btinternet.com
Visit the Wilcock Movie Page for U.K film reviews!
http://www.wilcock54.freeserve.co.uk

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php
class Core
{
	protected function error($msg)
	{
		exit($msg);
	}
}