text:
'''
Copyright (c) Members of the EGEE Collaboration. 2004.
http://www.eu-egee.org

File: unittest.py

Authors: Marc-Elian Begin <Marc-Elian.Begin@cern.ch>

Version info: $Id: unittest.py,v 1.5 2004/10/20 21:22:08 mbegin Exp $
Release: $Name:  $

Revision history:
$Log: unittest.py,v $
Revision 1.5  2004/10/20 21:22:08  mbegin
Attempted to create a generic set of Python tasks, and refactored accordingly

Revision 1.4  2004/10/19 17:56:46  mbegin
Refactoring and fixed bug on total testsuite test time

Revision 1.3  2004/10/19 16:40:54  mbegin
Removed requirement for Python 2.3. Now works with 2.2

Revision 1.2  2004/09/10 12:45:38  mbegin
Upgraded unittest.py such that the new 'writeParameter' method writes xml
elements in the system-out element of the test report.  The new util.py file
provides a function to print the name/value pair for a given test report.

Revision 1.1.1.1  2004/07/22 13:07:25  leanne
Initial import of unit testing tools

Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.

This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the results
(TextTestRunner).

Simple usage:

    import unittest

    class IntegerArithmenticTestCase(unittest.TestCase):
        def testAdd(self):  ## test method names begin 'test*'
            self.assertEquals((1 + 2), 3)
            self.assertEquals(0 + 1, 1)
        def testMultiply(self);
            self.assertEquals((0 * 10), 0)
            self.assertEquals((5 * 8), 40)

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

Further information is available in the bundled documentation, and from

  http://pyunit.sourceforge.net/

Copyright (c) 1999, 2000, 2001 Steve Purcell
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.

IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
'''

__author__ = "Steve Purcell"
__email__ = "stephen_purcell at yahoo dot com"
__version__ = "$Revision: 1.5 $"[11:-2]

import time
import sys
import traceback
import string
import os
import types

##############################################################################
# Test framework core
##############################################################################

class TestResult:
    """Holder for test result information.

    Test results are automatically managed by the TestCase and TestSuite
    classes, and do not need to be explicitly manipulated by writers of tests.

    Each instance holds the total number of tests run, and collections of
    failures and errors that occurred among those test runs. The collections
    contain tuples of (testcase, exceptioninfo), where exceptioninfo is a
    tuple of values as returned by sys.exc_info().
    """
    def __init__(self):
        self.failures = []
        self.errors = []
        self.testsRun = 0
        self.shouldStop = 0
        self.params = ""

    def startTest(self, test):
        "Called when the given test is about to be run"
        self.testsRun = self.testsRun + 1

    def stopTest(self, test):
        "Called when the given test has been run"
        pass

    def addError(self, test, err):
        "Called when an error has occurred"
        self.errors.append((test, err))

    def addFailure(self, test, err):
        "Called when a failure has occurred"
        self.failures.append((test, err))

    def addSuccess(self, test):
        "Called when a test has completed successfully"
        pass

    def wasSuccessful(self):
        "Tells whether or not this result was a success"
        return len(self.failures) == len(self.errors) == 0

    def stop(self):
        "Indicates that the tests should be aborted"
        self.shouldStop = 1

    def __repr__(self):
        return "<%s run=%i errors=%i failures=%i>" % \
               (self.__class__, self.testsRun, len(self.errors),
                len(self.failures))

class TestCase:
    """A class whose instances are single test cases.

    By default, the test code itself should be placed in a method named
    'runTest'.

    If the fixture may be used for many test cases, create as
    many test methods as are needed. When instantiating such a TestCase
    subclass, specify in the constructor arguments the name of the test method
    that the instance is to execute.

    Test authors should subclass TestCase for their own tests. Construction
    and deconstruction of the test's environment ('fixture') can be
    implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    If it is necessary to override the __init__ method, the base class
    __init__ method must always be called. It is important that subclasses
    should not change the signature of their __init__ method, since instances
    of the classes are instantiated automatically by parts of the framework
    in order to be run.
    """

    # This attribute determines which exception will be raised when
    # the instance's assertion methods fail; test methods raising this
    # exception will be deemed to have 'failed' rather than 'errored'

    failureException = AssertionError

    def __init__(self, methodName='runTest'):
        """Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.
        """
        self.result = TestResult()
        try:
            self.__testMethodName = methodName
            testMethod = getattr(self, methodName)
            self.__testMethodDoc = testMethod.__doc__
        except AttributeError:
            raise ValueError, "no such test method in %s: %s" % \
                  (self.__class__, methodName)

    def setUp(self):
        "Hook method for setting up the test fixture before exercising it."
        pass

    def tearDown(self):
        "Hook method for deconstructing the test fixture after testing it."
        pass

    def countTestCases(self):
        return 1

#    def defaultTestResult(self):
#        return TestResult()

    def shortDescription(self):
        """Returns a one-line description of the test, or None if no
        description has been provided.

        The default implementation of this method returns the first line of
        the specified test method's docstring.
        """
        doc = self.__testMethodDoc
        return doc and string.strip(string.split(doc, "\n")[0]) or None

    def id(self):
        return "%s.%s" % (self.__class__, self.__testMethodName)

    def __str__(self):
        return "%s (%s)" % (self.__testMethodName, self.__class__)

    def __repr__(self):
        return "<%s testMethod=%s>" % \
               (self.__class__, self.__testMethodName)

    def run(self, result=None):
        if result is not None: self.result = result
        return self(result)

    def __call__(self, result=None):
        if result is not None: self.result = result
        result.startTest(self)
        testMethod = getattr(self, self.__testMethodName)
        try:
            try:
                self.setUp()
            except:
                result.addError(self,self.__exc_info())
                return

            ok = 0
            try:
                testMethod()
                ok = 1
            except self.failureException, e:
                result.addFailure(self,self.__exc_info())
            except:
                result.addError(self,self.__exc_info())

            try:
                self.tearDown()
            except:
                result.addError(self,self.__exc_info())
                ok = 0
            if ok: result.addSuccess(self)
        finally:
            result.stopTest(self)

    def debug(self):
        """Run the test without collecting errors in a TestResult"""
        self.setUp()
        getattr(self, self.__testMethodName)()
        self.tearDown()

    def __exc_info(self):
        """Return a version of sys.exc_info() with the traceback frame
           minimised; usually the top level of the traceback frame is not
           needed.
        """
        exctype, excvalue, tb = sys.exc_info()
        if sys.platform[:4] == 'java': ## tracebacks look different in Jython
            return (exctype, excvalue, tb)
        newtb = tb.tb_next
        if newtb is None:
            return (exctype, excvalue, tb)
        return (exctype, excvalue, newtb)

    def fail(self, msg=None):
        """Fail immediately, with the given message."""
        raise self.failureException, msg

    def failIf(self, expr, msg=None):
        "Fail the test if the expression is true."
        if expr: raise self.failureException, msg

    def failUnless(self, expr, msg=None):
        """Fail the test unless the expression is true."""
        if not expr: raise self.failureException, msg

    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        """Fail unless an exception of class excClass is thrown
           by callableObj when invoked with arguments args and keyword
           arguments kwargs. If a different type of exception is
           thrown, it will not be caught, and the test case will be
           deemed to have suffered an error, exactly as for an
           unexpected exception.
        """
        try:
            apply(callableObj, args, kwargs)
        except excClass:
            return
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
            raise self.failureException, excName

    def failUnlessEqual(self, first, second, msg=None):
        """Fail if the two objects are unequal as determined by the '!='
           operator.
        """
        if first != second:
            raise self.failureException, (msg or '%s != %s' % (first, second))

    def failIfEqual(self, first, second, msg=None):
        """Fail if the two objects are equal as determined by the '=='
           operator.
        """
        if first == second:
            raise self.failureException, (msg or '%s == %s' % (first, second))

    assertEqual = assertEquals = failUnlessEqual

    assertNotEqual = assertNotEquals = failIfEqual

    assertRaises = failUnlessRaises

    assert_ = failUnless

    def writeParameter(self, paramName, paramValue):
        testcase = self.__class__
        testmethod = self.id().split('.')[-1]
        self.result.params += "<parameter name='%s' value='%s' testcase='%s' testmethod='%s' /> " % (paramName, paramValue, testcase, testmethod)

class TestSuite:
    """A test suite is a composite test consisting of a number of TestCases.

    For use, create an instance of TestSuite, then add test case instances.
    When all tests have been added, the suite can be passed to a test
    runner, such as TextTestRunner. It will run the individual test cases
    in the order in which they were added, aggregating the results. When
    subclassing, do not forget to call the base class constructor.
    """
    def __init__(self, tests=()):
        self._tests = []
        self.addTests(tests)

    def __repr__(self):
        return "<%s tests=%s>" % (self.__class__, self._tests)

    __str__ = __repr__

    def countTestCases(self):
        cases = 0
        for test in self._tests:
            cases = cases + test.countTestCases()
        return cases

    def addTest(self, test):
        self._tests.append(test)

    def addTests(self, tests):
        for test in tests:
            self.addTest(test)

    def run(self, result):
        return self(result)

    def __call__(self, result):
        for test in self._tests:
            if result.shouldStop:
                break
            test(result)
        return result

    def debug(self):
        """Run the tests without collecting errors in a TestResult"""
        for test in self._tests: test.debug()

class FunctionTestCase(TestCase):
    """A test case that wraps a test function.

    This is useful for slipping pre-existing test functions into the
    PyUnit framework. Optionally, set-up and tidy-up functions can be
    supplied. As with TestCase, the tidy-up ('tearDown') function will
    always be called if the set-up ('setUp') function ran successfully.
    """

    def __init__(self, testFunc, setUp=None, tearDown=None,
                 description=None):
        TestCase.__init__(self)
        self.__setUpFunc = setUp
        self.__tearDownFunc = tearDown
        self.__testFunc = testFunc
        self.__description = description

    def setUp(self):
        if self.__setUpFunc is not None:
            self.__setUpFunc()

    def tearDown(self):
        if self.__tearDownFunc is not None:
            self.__tearDownFunc()

    def runTest(self):
        self.__testFunc()

    def id(self):
        return self.__testFunc.__name__

    def __str__(self):
        return "%s (%s)" % (self.__class__, self.__testFunc.__name__)

    def __repr__(self):
        return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)

    def shortDescription(self):
        if self.__description is not None: return self.__description
        doc = self.__testFunc.__doc__
        return doc and string.strip(string.split(doc, "\n")[0]) or None

##############################################################################
# Locating and loading tests
##############################################################################

class TestLoader:
    """This class is responsible for loading tests according to various
    criteria and returning them wrapped in a Test
    """
    testMethodPrefix = 'test'
    sortTestMethodsUsing = cmp
    suiteClass = TestSuite

    def loadTestsFromTestCase(self, testCaseClass):
        """Return a suite of all tests cases contained in testCaseClass"""
        return self.suiteClass(map(testCaseClass,
                                   self.getTestCaseNames(testCaseClass)))

    def loadTestsFromModule(self, module):
        """Return a suite of all tests cases contained in the given module"""
        tests = []
        for name in dir(module):
            obj = getattr(module, name)
            if type(obj) == types.ClassType and issubclass(obj, TestCase):
                tests.append(self.loadTestsFromTestCase(obj))
        return self.suiteClass(tests)

    def loadTestsFromName(self, name, module=None):
        """Return a suite of all tests cases given a string specifier.

        The name may resolve either to a module, a test case class, a
        test method within a test case class, or a callable object which
        returns a TestCase or TestSuite instance.

        The method optionally resolves the names relative to a given module.
        """
        parts = string.split(name, '.')
        if module is None:
            if not parts:
                raise ValueError, "incomplete test name: %s" % name
            else:
                parts_copy = parts[:]
                while parts_copy:
                    try:
                        module = __import__(string.join(parts_copy,'.'))
                        break
                    except ImportError:
                        del parts_copy[-1]
                        if not parts_copy: raise
                parts = parts[1:]
        obj = module
        for part in parts:
            obj = getattr(obj, part)

        import unittest
        if type(obj) == types.ModuleType:
            return self.loadTestsFromModule(obj)
        elif type(obj) == types.ClassType and issubclass(obj, unittest.TestCase):
            return self.loadTestsFromTestCase(obj)
        elif type(obj) == types.UnboundMethodType:
            return obj.im_class(obj.__name__)
        elif callable(obj):
            test = obj()
            if not isinstance(test, unittest.TestCase) and \
               not isinstance(test, unittest.TestSuite):
                raise ValueError, \
                      "calling %s returned %s, not a test" % (obj,test)
            return test
        else:
            raise ValueError, "don't know how to make test from: %s" % obj

    def loadTestsFromNames(self, names, module=None):
        """Return a suite of all tests cases found using the given sequence
        of string specifiers. See 'loadTestsFromName()'.
        """
        suites = []
        for name in names:
            suites.append(self.loadTestsFromName(name, module))
        return self.suiteClass(suites)

    def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
                             dir(testCaseClass))
        for baseclass in testCaseClass.__bases__:
            for testFnName in self.getTestCaseNames(baseclass):
                if testFnName not in testFnNames:  # handle overridden methods
                    testFnNames.append(testFnName)
        if self.sortTestMethodsUsing:
            testFnNames.sort(self.sortTestMethodsUsing)
        return testFnNames

defaultTestLoader = TestLoader()

##############################################################################
# Patches for old functions: these functions should be considered obsolete
##############################################################################

def _makeLoader(prefix, sortUsing, suiteClass=None):
    loader = TestLoader()
    loader.sortTestMethodsUsing = sortUsing
    loader.testMethodPrefix = prefix
    if suiteClass: loader.suiteClass = suiteClass
    return loader

def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
    return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)

def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)

def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)

##############################################################################
# Text UI
##############################################################################

class _WritelnDecorator:
    """Used to decorate file-like objects with a handy 'writeln' method"""
    def __init__(self,stream):
        self.stream = stream

    def __getattr__(self, attr):
        return getattr(self.stream,attr)

    def writeln(self, *args):
        if args: apply(self.write, args)
        self.write('\n') # text-mode streams translate to \r\n if needed

class _XmlTextTestResult(TestResult):
    """A test result class that can print xml formatted text results to a stream.

    Used by XmlTextTestRunner.
    """
    def __init__(self, stream, descriptions, verbosity):
        TestResult.__init__(self)
        self.stream = _WritelnDecorator(stream)
        self.showAll = verbosity > 1
        self.descriptions = descriptions
        self._lastWas = 'success'
        self._errorsAndFailures = ""
        self._startTime = 0.0

    def getDescription(self, test):
        if self.descriptions:
            return test.shortDescription() or str(test)
        else:
            return str(test)

    def startTest(self, test):
        self._startTime = time.time()
        TestResult.startTest(self, test)
        self.stream.write('<testcase classname="%s' % test.__class__ + '" name="%s' % test.id().split('.')[-1] + '"')

    def stopTest(self, test):
        stopTime = time.time()
        deltaTime = stopTime - self._startTime
        TestResult.stopTest(self, test)
        self.stream.write(' time="%.3f"' % deltaTime)
        if self._lastWas == 'success':
            self.stream.write('/>')
        else:
            self.stream.write('>')
            if self._lastWas == 'error':
                self.stream.write(self._errorsAndFailures)
            elif self._lastWas == 'failure':
                self.stream.write(self._errorsAndFailures)
            else:
                assert(false)
            self.stream.write('</testcase>')
        self._errorsAndFailures = ""

    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
        self._lastWas = 'success'

    def addError(self, test, err):
        TestResult.addError(self, test, err)
        if err[0] is KeyboardInterrupt:
            self.shouldStop = 1
        self._lastWas = 'error'
        self._errorsAndFailures += '<error type="%s">' % err[0]
        for line in apply(traceback.format_exception, err):
           for l in string.split(line,"\n")[:-1]:
              self._errorsAndFailures += "%s" % l
        self._errorsAndFailures += "</error>"

    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)
        if err[0] is KeyboardInterrupt:
            self.shouldStop = 1
        self._lastWas = 'failure'
        self._errorsAndFailures += '<failure type="%s">' % err[0]
        for line in apply(traceback.format_exception, err):
           for l in string.split(line,"\n")[:-1]:
              self._errorsAndFailures += "%s" % l
        self._errorsAndFailures += "</failure>"

    def printErrors(self):
        assert false

    def printErrorList(self, flavour, errors):
        assert false

class _TextTestResult(TestResult):
    """A test result class that can print formatted text results to a stream.

    Used by TextTestRunner.
    """
    separator1 = '=' * 70
    separator2 = '-' * 70

    def __init__(self, stream, descriptions, verbosity):
        TestResult.__init__(self)
        self.stream = stream
        self.showAll = verbosity > 1
        self.dots = verbosity == 1
        self.descriptions = descriptions

    def getDescription(self, test):
        if self.descriptions:
            return test.shortDescription() or str(test)
        else:
            return str(test)

    def startTest(self, test):
        TestResult.startTest(self, test)
        if self.showAll:
            self.stream.write(self.getDescription(test))
            self.stream.write(" ... ")

    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
        if self.showAll:
            self.stream.writeln("ok")
        elif self.dots:
            self.stream.write('.')

    def addError(self, test, err):
        TestResult.addError(self, test, err)
        if self.showAll:
            self.stream.writeln("ERROR")
        elif self.dots:
            self.stream.write('E')
        if err[0] is KeyboardInterrupt:
            self.shouldStop = 1

    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)
        if self.showAll:
            self.stream.writeln("FAIL")
        elif self.dots:
            self.stream.write('F')

    def printErrors(self):
        if self.dots or self.showAll:
            self.stream.writeln()
        self.printErrorList('ERROR', self.errors)
        self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavour, errors):
        for test, err in errors:
            self.stream.writeln(self.separator1)
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
            self.stream.writeln(self.separator2)
            for line in apply(traceback.format_exception, err):
                for l in string.split(line,"\n")[:-1]:
                    self.stream.writeln("%s" % l)

class TextTestRunner:
    """A test runner class that displays results in textual form.

    It prints out the names of tests as they are run, errors as they
    occur, and a summary of the results at the end of the test run.
    """
    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
        self.stream = _WritelnDecorator(stream)
        self.descriptions = descriptions
        self.verbosity = verbosity

    def _makeResult(self):
        return _TextTestResult(self.stream, self.descriptions, self.verbosity)

    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        startTime = time.time()
        test(result)
        stopTime = time.time()
        timeTaken = float(stopTime - startTime)
        result.printErrors()
        self.stream.writeln(result.separator2)
        run = result.testsRun
        self.stream.writeln("Ran %d test%s in %.3fs" %
                            (run, run == 1 and "" or "s", timeTaken))
        self.stream.writeln()
        if not result.wasSuccessful():
            self.stream.write("FAILED (")
            failed, errored = map(len, (result.failures, result.errors))
            if failed:
                self.stream.write("failures=%d" % failed)
            if errored:
                if failed: self.stream.write(", ")
                self.stream.write("errors=%d" % errored)
            self.stream.writeln(")")
        else:
            self.stream.writeln("OK")
        return result

class XmlTextTestRunner:
    """A test runner class that displays results in xml form.

    The format is compatible with the Ant junit task xml format.
    """

    class _StdOut:
        def __init__(self,std):
            self.reset()
            self._std = std
            return

        def write(self, string):
            self._string += string
            self._std.write(string)
            return

        def read(self):
            return self._string

        def reset(self):
            self._string = ""

    class _StringStream:
        def __init__(self):
            self.reset()
            return

        def write(self, string):
            self._string += string
            return

        def read(self):
            return self._string

        def reset(self):
            self._string = ""

    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
        self.descriptions = descriptions
        self.verbosity = verbosity
        self.stdout = self._StdOut(sys.stdout)
        sys.stdout = self.stdout
        self.stderr = self._StdOut(sys.stderr)
        sys.stderr = self.stderr
        self.testResults = self._StringStream()
        self.totalTime = 0.0
        self.output = None

    def _openOutputFile(self, fileName):

        if not os.path.isdir(os.path.join("temp", "xml")): os.makedirs(os.path.join("temp", "xml"))

        self.outputFileName = 'temp/xml/test_output.xml'
        self.output = open(self.outputFileName,'w')

    def _makeResult(self):
        return _XmlTextTestResult(self.testResults, self.descriptions, self.verbosity)

    def _resetBuffers(self):
        self.testResults.reset()

    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        for t in test._tests:
            # get the name of the unit test file name (!!!)
            size = len(sys.argv[0])
            if sys.argv[0].endswith('.py'):
                (filePath,fileName) = os.path.split(sys.argv[0])
                fileName = fileName.split('.')[0]
            else:
                fileName = "%s" % string.split("%s" % t._tests[0]._tests[0].__class__,'.')[0]
            self._openOutputFile(fileName)
            startTime = time.time()
            t(result)
            stopTime = time.time()
            timeTaken = float(stopTime - startTime)
            self.totalTime += timeTaken
        self._writeReport(result,self.totalTime)
        # ??? this line
        run = result.testsRun
        return result

    def _writeReport(self, result, timeTaken):
        if self.output != None:
            self.output.write('<testsuite ')
            self.output.write('errors="%i" ' % len(result.errors))
            self.output.write('failures="%i" ' % len(result.failures))
            self.output.write('name="%s" ' % "")
            self.output.write('tests="%i" ' % result.testsRun)
            self.output.write('time="%.3f" ' % timeTaken)
            self.output.write(' >')
            self.output.write(self.testResults.read())
            self.output.write('<system-out>')
            self.output.write(result.params)
            self.output.write('<![CDATA[')
            self.output.write(self.stdout.read())
            self.output.write(']]></system-out>')
            self.output.write('<system-err><![CDATA[')
            self.output.write(self.stderr.read())
            self.output.write(']]></system-err>')
            self.output.write('</testsuite>')
            self.output.close()
            self._resetBuffers()
            # Write console report
            print '======================================================================'
            print 'Ran %d test%s in %.3fs' % (result.testsRun, result.testsRun == 1 and '' or 's', timeTaken)
            print '----------------------------------------------------------------------'
            print 'See generated report:', self.outputFileName,'\n'
            msg = ''
            if not result.wasSuccessful():
                msg += "FAILED ("
                failed, errored = map(len, (result.failures, result.errors))
                if failed:
                    msg += "failures=%d" % failed
                if errored:
                    if failed: msg += ", "
                    msg += "errors=%d" % errored
                msg += ")"
            else:
                msg += "OK"
            print msg
        else:
            print '======================================================================'
            print 'No tests to run'
            print '----------------------------------------------------------------------'
        return

##############################################################################
# Facilities for running tests from the command line
##############################################################################

class TestProgram:
    """A command-line program that runs a set of tests; this is primarily
       for making test modules conveniently executable.
    """
    USAGE = """\
Usage: %(progName)s [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -t, --text       Text output (classic output) - default
  -x, --xml        XML output (same format as JUnit)

Examples:
  %(progName)s                               - run default set of tests
  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'
  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething
  %(progName)s MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase
"""
    def __init__(self, module='__main__', defaultTest=None,
                 argv=None, testRunner=None, testLoader=defaultTestLoader):
        if type(module) == type(''):
            self.module = __import__(module)
            for part in string.split(module,'.')[1:]:
                self.module = getattr(self.module, part)
        else:
            self.module = module
        if argv is None:
            argv = sys.argv
        self.verbosity = 2
        self.xmlReport = False
        self.defaultTest = defaultTest
        self.testRunner = testRunner
        self.testLoader = testLoader
        self.progName = os.path.basename(argv[0])
        self.parseArgs(argv)
        self.runTests()

    def usageExit(self, msg=None):
        if msg: print msg
        print self.USAGE % self.__dict__
        sys.exit(2)

    def parseArgs(self, argv):
        import getopt
        try:
            options, args = getopt.getopt(argv[1:], 'hHvqxt',
                                          ['help','verbose','quiet','xml','text'])
        except getopt.error, msg:
            self.usageExit(msg)
        for opt, value in options:
            if opt in ('-h','-H','--help'):
                self.usageExit()
            if opt in ('-q','--quiet'):
                self.verbosity = 0
            if opt in ('-v','--verbose'):
                self.verbosity = 2
            if opt in ('-x','--xml'):
                self.xmlReport = True
            if opt in ('-t','--text'):
                self.xmlReport = False
        if os.getenv('PYUNITXMLOUTPUT'):
            self.xmlReport = True
        if len(args) == 0 and self.defaultTest is None:
            self.test = self.testLoader.loadTestsFromModule(self.module)
            return
        if len(args) > 0:
            self.testNames = args
        else:
            print 'Running default test:%s' % self.defaultTest
            self.testNames = (self.defaultTest,)
        self.createTests()

    def createTests(self):
        self.test = self.testLoader.loadTestsFromNames(self.testNames,
                                                       self.module)

    def runTests(self):
        if self.testRunner is None:
            if self.xmlReport == True:
                self.testRunner = XmlTextTestRunner(verbosity=self.verbosity)
            else:
                self.testRunner = TextTestRunner(verbosity=self.verbosity)
        result = self.testRunner.run(self.test)
        sys.exit(not result.wasSuccessful())

main = TestProgram

##############################################################################
# Executing this module from the command line
##############################################################################

if __name__ == "__main__":
    main(module=None)


text:
package net.ghostrealms.util;

/**
 * Created by jamesraynor on 7/31/15.
 */
public enum SerializeStatus {
    TO_LARGE,
    NOT_SET,
    DIFFERENT_WORLDS,
    SUCCESSFUL,
    ALREADY_SET
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}

{% from 'forms.html' import field %}

{% block content %}

Add route

<form method="post">

	{{ field(form.container) }}
	{{ field(form.routing_key) }}
	{{ field(form.weight) }}

	<button type="submit" class="btn btn-primary btn-large">Add</button>

</form>

{% endblock %}


text:
/**
 * Created by Islam on 23.04.2017.
 */

/**
 * Add vinget effect to canvas
 * @param {HTMLCanvasElement} canvas
 * @param {Object} [params]
 * @param {String} [params.color]
 * @param {String} [params.color2]
 * @param {Number} [params.alpha]
 */
export default function(canvas, params={}){
	let ctx = canvas.getContext('2d'),
		x = canvas.width/2,
		y = canvas.height/2,
		g = ctx.createRadialGradient(x, y, Math.max(canvas.width, canvas.height)/2, x, y, 0);

	ctx.save();

	g.addColorStop(0, params.color || 'black');
	g.addColorStop(0.5, params.color2 || 'transparent');
	ctx.fillStyle = g;
	ctx.globalAlpha = params.alpha || 1;
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	ctx.restore();
};


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

namespace XMLTool.Errors
{
    /// <summary>
    /// XML的XPath异常
    /// </summary>
    public class XMLNodeError : Exception
    {
        public string XPath { get; set; }

        public XMLNodeError(string xPath)
            : base("原XML的XPath没有读取到数据")
        {
            this.XPath = xPath;
        }

        public XMLNodeError(string xPath, Exception innerException)
            : base("原XML的XPath没有读取到数据", innerException)
        {
            this.XPath = xPath;
        }
    }
}


text:
'use strict';

const assert = require('assert');

const test = require('../lib/test');
const {Browser, By} = require('..');

test.suite(function(env) {
  var driver;

  before(async function() { driver = await env.builder().build(); });
  after(function() { return driver.quit(); });

  beforeEach(function() {
    return driver.switchTo().defaultContent();
  });

  it('can switch to a frame and back to the parent frame', async function() {
    await driver.get(test.Pages.iframePage);

    let frame = await driver.findElement(By.name('iframe1-name'));
    await driver.switchTo().frame(frame);
    assert.equal(await driver.executeScript('return document.title'), 'We Leave From Here');
    await driver.switchTo().parentFrame();
    assert.equal(await driver.executeScript('return document.title'), 'This page has iframes');
  });
});


text:
using SharpDX;
using SharpDX.Direct3D11;
using System.Collections.Generic;

#if NETFX_CORE
namespace HelixToolkit.UWP.Render
#else
namespace HelixToolkit.Wpf.SharpDX.Render
#endif
{
    using Core;
    using Model.Scene;
    using Model.Scene2D;
    /// <summary>
    ///
    /// </summary>
    public struct RenderParameter
    {
        /// <summary>
        /// The render target view
        /// </summary>
        public RenderTargetView RenderTargetView;
        /// <summary>
        /// The depth stencil view
        /// </summary>
        public DepthStencilView DepthStencilView;
        /// <summary>
        /// The viewport region
        /// </summary>
        public ViewportF ViewportRegion;
        /// <summary>
        /// The scissor region
        /// </summary>
        public Rectangle ScissorRegion;
        /// <summary>
        ///
        /// </summary>
        public bool RenderLight;
        /// <summary>
        ///
        /// </summary>
        public bool UpdatePerFrameData;
    }

    /// <summary>
    ///
    /// </summary>
    public struct RenderParameter2D
    {
        public global::SharpDX.Direct2D1.Bitmap1 RenderTarget;
    }

    /// <summary>
    ///
    /// </summary>
    public interface IRenderer
    {
        /// <summary>
        /// Default ImmediateContext. Same as Device.ImmediateContext.
        /// <para>Used for update global variables</para>
        /// </summary>
        DeviceContextProxy ImmediateContext { get; }
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        void Attach(IRenderHost host);
        /// <summary>
        ///
        /// </summary>
        void Detach();
        /// <summary>
        /// Update scene graph, return the renderables which will be rendered in this frame
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="results"></param>
        /// <returns></returns>
        void UpdateSceneGraph(RenderContext context, List<SceneNode> renderables, List<KeyValuePair<int, SceneNode>> results);

        /// <summary>
        /// Update scene graph, return the 2D renderables which will be rendered in this frame
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <returns></returns>
        void UpdateSceneGraph2D(RenderContext2D context, List<SceneNode2D> renderables);
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="parameter"></param>
        void UpdateGlobalVariables(RenderContext context, List<SceneNode> renderables, ref RenderParameter parameter);

        /// <summary>
        ///
        /// </summary>
        /// <param name="parameter"></param>
        void SetRenderTargets(ref RenderParameter parameter);

        /// <summary>
        /// Render pre processings, such as Shadow pass etc.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="parameter"></param>
        void RenderPreProc(RenderContext context, List<SceneNode> renderables, ref RenderParameter parameter);

        /// <summary>
        /// Render post processing, such as bloom effects etc.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="parameter"></param>
        void RenderPostProc(RenderContext context, List<SceneNode> renderables, ref RenderParameter parameter);

        /// <summary>
        /// Run actual rendering for render cores.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="parameter"></param>
        /// <returns>Number of node has been rendered</returns>
        int RenderOpaque(RenderContext context, List<SceneNode> renderables, ref RenderParameter parameter);

        /// <summary>
        /// Renders the transparent.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="renderables">The renderables.</param>
        /// <param name="parameter">The parameter.</param>
        /// <returns></returns>
        int RenderTransparent(RenderContext context, List<SceneNode> renderables, ref RenderParameter parameter);
        /// <summary>
        /// Renders to back buffer.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="parameter">The parameter.</param>
        void RenderToBackBuffer(RenderContext context, ref RenderParameter parameter);
        /// <summary>
        /// Update scene graph not related to rendering. Can be run parallel with the <see cref="RenderOpaque(RenderContext, List{SceneNode}, ref RenderParameter)"/>
        /// <para>Warning: Dependency properties are thread affinity. Do not get/set any dependency property in this function.</para>
        /// </summary>
        /// <param name="renderables"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        void UpdateNotRenderParallel(RenderContext context, List<KeyValuePair<int, SceneNode>> renderables);
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="renderables"></param>
        /// <param name="parameter"></param>
        void RenderScene2D(RenderContext2D context, List<SceneNode2D> renderables, ref RenderParameter2D parameter);
    }
}


text:
@interface FlxAlert () <UIAlertViewDelegate>

@end

@implementation FlxAlert{
    id _lock;
    UIAlertView *_alert;
}
#pragma mark - Init Methods
+ (void) displayYesNoAlertWithTitle:(NSString *)title message:(NSString *)message completion:(YesNoBlock)completion{
    FlxAlert *alert = [FlxAlert alertWithTitle:title message:message completion:!completion ? nil : ^(NSUInteger uInteger) {
        if (uInteger == 0){
            completion(YES);
        } else {
            completion(NO);
        }
    }];
    alert.cancelButton = nil;
    alert.buttons = Array(@"Yes", @"No");
    [alert display];
}
+ (void) displayAlertTitle:(NSString *)title message:(NSString *)message buttons:(NSArray *)buttons completion:(AlertBlock)completion{
    FlxAlert *alert = [FlxAlert alertWithTitle:title message:message completion:completion];
    alert.cancelButton = buttons.firstObject ? : @"OK";
    if (buttons.count > 1){
        alert.buttons = ({
            NSMutableArray *otherButtons = [NSMutableArray new];
            for (int i = 1; i < buttons.count; i++){
                [otherButtons addObject:buttons[i]];
            }
            otherButtons;
        });
    }
    [alert display];
}
+ (void) displayAlertWithTitle:(NSString *)title message:(NSString *)message completion:(AlertBlock)completion{
    [[FlxAlert alertWithTitle:title message:message completion:completion] display];
}
+ (void) displayAlertWithTitle:(NSString *)title message:(NSString *)message{
    [[FlxAlert alertWithTitle:title message:message completion:nil] display];
}
+ (FlxAlert *) alertWithTitle:(NSString *)title message:(NSString *)message completion:(AlertBlock)completion{
    FlxAlert *alert = [FlxAlert new];
    alert.title = title;
    alert.message = message;
    alert.cancelButton = @"OK";
    alert.completionBlock = completion;
    return alert;
}
#pragma mark - Private Methods

#pragma mark - Properties

#pragma mark - Standard Methods
- (void) display{
    if (!_alert){
        MainBlock(^{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_title message:_message delegate:_completionBlock ? self : nil cancelButtonTitle:_cancelButton otherButtonTitles:nil];
            for (NSString *string in _buttons){
                [alert addButtonWithTitle:string];
            }
            if (_completionBlock){
                _alert = alert;
                _lock = Array(self);
            }
            [alert show];
        })
    }
}
#pragma mark - Protocol Methods
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (_completionBlock){
        _completionBlock(buttonIndex);
    }
    _completionBlock = nil;
    _alert = nil;
    _lock = nil;
}
#pragma mark - Overridden Methods
@end


text:
namespace Util
{
} //namespace Util

#endif // _RAST_UTILITY_


text:
<?php

class Subscriber extends PluginSubscriber
{
}


text:
from sahara import exceptions as ex
from sahara.plugins import base as plugins_base
from sahara.utils import resources

class ProvisioningPluginBase(plugins_base.PluginInterface):
    @plugins_base.required
    def get_versions(self):
        pass

    @plugins_base.required
    def get_configs(self, hadoop_version):
        pass

    @plugins_base.optional
    def get_hdfs_user(self):
        pass

    @plugins_base.required
    def get_node_processes(self, hadoop_version):
        pass

    @plugins_base.required_with_default
    def get_required_image_tags(self, hadoop_version):
        return [self.name, hadoop_version]

    @plugins_base.required_with_default
    def validate(self, cluster):
        pass

    @plugins_base.required_with_default
    def validate_scaling(self, cluster, existing, additional):
        pass

    @plugins_base.required_with_default
    def update_infra(self, cluster):
        pass

    @plugins_base.required
    def configure_cluster(self, cluster):
        pass

    @plugins_base.required
    def start_cluster(self, cluster):
        pass

    @plugins_base.optional
    def scale_cluster(self, cluster, instances):
        pass

    @plugins_base.optional
    def get_name_node_uri(self, cluster):
        pass

    @plugins_base.optional
    def get_oozie_server(self, cluster):
        pass

    @plugins_base.optional
    def get_oozie_server_uri(self, cluster):
        pass

    @plugins_base.optional
    def validate_edp(self, cluster):
        pass

    @plugins_base.optional
    def get_resource_manager_uri(self, cluster):
        pass

    @plugins_base.required_with_default
    def decommission_nodes(self, cluster, instances):
        pass

    @plugins_base.optional
    def convert(self, config, plugin_name, version, template_name,
                cluster_template_create):
        pass

    @plugins_base.required_with_default
    def on_terminate_cluster(self, cluster):
        pass

    def to_dict(self):
        res = super(ProvisioningPluginBase, self).to_dict()
        res['versions'] = self.get_versions()
        return res

    # Some helpers for plugins

    def _map_to_user_inputs(self, hadoop_version, configs):
        config_objs = self.get_configs(hadoop_version)

        # convert config objects to applicable_target -> config_name -> obj
        config_objs_map = {}
        for config_obj in config_objs:
            applicable_target = config_obj.applicable_target
            confs = config_objs_map.get(applicable_target, {})
            confs[config_obj.name] = config_obj
            config_objs_map[applicable_target] = confs

        # iterate over all configs and append UserInputs to result list
        result = []
        for applicable_target in configs:
            for config_name in configs[applicable_target]:
                confs = config_objs_map.get(applicable_target)
                if not confs:
                    raise ex.ConfigurationError(
                        "Can't find applicable target '%s' for '%s'"
                        % (applicable_target, config_name))
                conf = confs.get(config_name)
                if not conf:
                    raise ex.ConfigurationError(
                        "Can't find config '%s' in '%s'"
                        % (config_name, applicable_target))
                result.append(UserInput(
                    conf, configs[applicable_target][config_name]))

        return result

class Config(resources.BaseResource):
    """Describes a single config parameter.

    Config type - could be 'str', 'integer', 'boolean', 'enum'.
    If config type is 'enum' then list of valid values should be specified in
    config_values property.

    Priority - integer parameter which helps to differentiate all
    configurations in the UI. Priority decreases from the lower values to
    higher values.

    For example:

        "some_conf", "map_reduce", "node", is_optional=True
    """

    def __init__(self, name, applicable_target, scope, config_type="string",
                 config_values=None, default_value=None, is_optional=False,
                 description=None, priority=2):
        self.name = name
        self.description = description
        self.config_type = config_type
        self.config_values = config_values
        self.default_value = default_value
        self.applicable_target = applicable_target
        self.scope = scope
        self.is_optional = is_optional
        self.priority = priority

    def to_dict(self):
        res = super(Config, self).to_dict()
        # TODO(slukjanov): all custom fields from res
        return res

    def __repr__(self):
        return '<Config %s in %s>' % (self.name, self.applicable_target)

class UserInput(object):
    """Value provided by the user for a specific config entry."""

    def __init__(self, config, value):
        self.config = config
        self.value = value

    def __eq__(self, other):
        return self.config == other.config and self.value == other.value

    def __repr__(self):
        return '<UserInput %s = %s>' % (self.config.name, self.value)

class ValidationError(object):
    """Describes what is wrong with one of the values provided by user."""

    def __init__(self, config, message):
        self.config = config
        self.message = message

    def __repr__(self):
        return "<ValidationError %s>" % self.config.name


text:
walk(document.body);

var rpl = "butt";
function loadRpl() {
  var rpl = localStorage["rpl"];
  return rpl;
}

function walk(node)
{
	// I stole this function from here:
	// http://is.gd/mwZp7E

	var child, next;

	switch ( node.nodeType )
	{
		case 1:  // Element
		case 9:  // Document
		case 11: // Document fragment
			child = node.firstChild;
			while ( child )
			{
				next = child.nextSibling;
				walk(child);
				child = next;
			}
			break;

		case 3: // Text node
			handleText(node);
			break;
	}
}

function handleText(textNode)
{
	var v = textNode.nodeValue;

  rpl = loadRpl();
  // LocalStorage isn't working as I'd expect, so set a default.
  if ( rpl == undefined ) { rpl = "Butt"; }
	v = v.replace(/\bTrump\b/g, rpl);
	v = v.replace(/\bTrump's\b/g, rpl);

	textNode.nodeValue = v;
}


text:
/*!
 * \file
 * \brief Class factory::Interleaver.
 */
#ifndef FACTORY_INTERLEAVER_HPP
#define FACTORY_INTERLEAVER_HPP

#include <string>
#include <map>
#include <cli.hpp>

#include "Tools/Factory/Header.hpp"
#include "Tools/auto_cloned_unique_ptr.hpp"
#include "Tools/Interleaver/Interleaver_core.hpp"
#include "Module/Interleaver/Interleaver.hpp"
#include "Factory/Tools/Interleaver/Interleaver_core.hpp"
#include "Factory/Factory.hpp"

namespace aff3ct
{
namespace factory
{
extern const std::string Interleaver_name;
extern const std::string Interleaver_prefix;
class Interleaver : public Factory
{
public:
	// ----------------------------------------------------------------------------------------------------- PARAMETERS
	// depending parameters
	tools::auto_cloned_unique_ptr<factory::Interleaver_core> core;

	// -------------------------------------------------------------------------------------------------------- METHODS
	explicit Interleaver(const std::string &p = Interleaver_prefix);
	virtual ~Interleaver() = default;
	Interleaver* clone() const;

	// parameters construction
	void get_description(cli::Argument_map_info &args) const;
	void store          (const cli::Argument_map_value &vals);
	void get_headers    (std::map<std::string,tools::header_list>& headers, const bool full = true) const;

	// builder
	template <typename D = int32_t>
	static module::Interleaver<D>* build(tools::Interleaver_core<>& itl_core);
};
}
}

#endif /* FACTORY_INTERLEAVER_HPP */


text:
package org.jetbrains.kotlin.idea.test;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.LanguageLevelModuleExtension;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class KotlinWithJdkAndRuntimeLightProjectDescriptor extends KotlinJdkAndLibraryProjectDescriptor {
    protected KotlinWithJdkAndRuntimeLightProjectDescriptor() {
        super(Collections.singletonList(KotlinArtifacts.getKotlinStdlib()),
              Collections.singletonList(KotlinArtifacts.getKotlinStdlibSources()));
    }

    public KotlinWithJdkAndRuntimeLightProjectDescriptor(
            @NotNull List<? extends File> libraryFiles,
            @NotNull List<? extends File> librarySourceFiles
    ) {
        super(libraryFiles, librarySourceFiles);
    }

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            Arrays.asList(KotlinArtifacts.getKotlinStdlib()),
            Collections.singletonList(KotlinArtifacts.getKotlinStdlibSources())
    );

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_WITH_STDLIB_JDK8 = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            List.of(KotlinArtifacts.getKotlinStdlib(), KotlinArtifacts.getKotlinStdlibJdk8()),
            List.of(KotlinArtifacts.getKotlinStdlibSources(), KotlinArtifacts.getKotlinStdlibJdk8Sources())
    );

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_NO_SOURCES = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            INSTANCE.getLibraryFiles(), Collections.emptyList()
    );

    public static KotlinWithJdkAndRuntimeLightProjectDescriptor getInstance(LanguageLevel level) {
        return new KotlinWithJdkAndRuntimeLightProjectDescriptor() {
            @Override
            public void configureModule(
                    @NotNull Module module, @NotNull ModifiableRootModel model
            ) {
                super.configureModule(module, model);
                model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level);
            }
        };
    }

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_WITH_KOTLIN_TEST = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            Arrays.asList(KotlinArtifacts.getKotlinStdlib(),
                          KotlinArtifacts.getKotlinTest()),
            Collections.singletonList(KotlinArtifacts.getKotlinStdlibSources())
    );

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_WITH_SCRIPT_RUNTIME = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            Arrays.asList(KotlinArtifacts.getKotlinStdlib(),
                          KotlinArtifacts.getKotlinScriptRuntime()),
            Collections.singletonList(KotlinArtifacts.getKotlinStdlibSources())
    );

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_WITH_REFLECT = new KotlinWithJdkAndRuntimeLightProjectDescriptor(
            Arrays.asList(KotlinArtifacts.getKotlinStdlib(),
                          KotlinArtifacts.getKotlinReflect()),
            Collections.singletonList(KotlinArtifacts.getKotlinStdlibSources())
    );

    @NotNull
    public static final KotlinWithJdkAndRuntimeLightProjectDescriptor INSTANCE_FULL_JDK = new KotlinWithJdkAndRuntimeLightProjectDescriptor() {
        @Override
        public Sdk getSdk() {
            return PluginTestCaseBase.fullJdk();
        }
    };
}


text:
using System;
using System.Runtime.InteropServices;

namespace ManagedBass.Enc
{
    public static partial class BassEnc
    {
        /// <summary>
        /// ACM codec name to give priority for the formats it supports (e.g. 'l3codecp.acm').
        /// </summary>
        public static string ACMLoad
        {
            get => Marshal.PtrToStringAnsi(Bass.GetConfigPtr(Configuration.EncodeACMLoad));
            set
            {
                var ptr = Marshal.StringToHGlobalAnsi(value);

                Bass.Configure(Configuration.EncodeACMLoad, ptr);

                Marshal.FreeHGlobal(ptr);
            }
        }

        [DllImport(DllName, CharSet = CharSet.Unicode)]
        static extern int BASS_Encode_GetACMFormat(int handle, IntPtr form, int formlen, string title, int flags);

        /// <summary>
        /// Presents the user with a list of available ACM (Audio Compression Manager) codec output formats to choose from.
        /// </summary>
        /// <param name="Handle">The channel handle... a HSTREAM, HMUSIC, or HRECORD.</param>
        /// <param name="Format">Pointer to the format buffer.</param>
        /// <param name="FormatLength">Size of the format buffer. If this is 0, then a suggested format buffer length is returned (which is the maximum length of all installed codecs), without displaying the codec selector.</param>
        /// <param name="Title">Window title for the selector... <see langword="null" /> = "Choose the output format".</param>
        /// <param name="Flags">A combination of <see cref="ACMFormatFlags"/>.</param>
        /// <param name="Encoding">Can be used to restrict the choice to a particular format tag. This is required with <see cref="ACMFormatFlags.Suggest"/>, and is optional otherwise.</param>
        /// <returns>
        /// If successful, the user-selected codec format details are put in the provided buffer and the length of the format details is returned, else 0 is returned.
        /// Use <see cref="Bass.LastError" /> to get the error code.
        /// If <paramref name="FormatLength"/> is 0, then the suggested format buffer size is returned.
        /// </returns>
        /// <remarks>
        /// This function presents the user with a list of available ACM codecs to choose from, given the sample format of the channel.
        /// The details of the chosen codec's output are returned in the Format buffer, which can then be used with <see cref="EncodeStartACM(int,IntPtr,EncodeFlags,EncodeProcedure,IntPtr)" /> or <see cref="EncodeStartACM(int,IntPtr,EncodeFlags,string)" /> to begin encoding.
        /// <para>
        /// The <paramref name="Format" /> buffer contents are actually a WAVEFORMATEX or ACMFORMAT structure.
        /// If writing the encoder output to a WAVE file, the Format buffer contents would be the format chunk ("fmt") of the file.
        /// </para>
        /// </remarks>
        /// <exception cref="Errors.Handle"><paramref name="Handle" /> is not valid.</exception>
        /// <exception cref="Errors.NotAvailable">There are no codecs available that will accept the channel's format.</exception>
        /// <exception cref="Errors.AcmCancel">The user pressed the "cancel" button.</exception>
        /// <exception cref="Errors.Unknown">Some other mystery problem!</exception>
        public static int GetACMFormat(int Handle,
                                       IntPtr Format = default(IntPtr),
                                       int FormatLength = 0,
                                       string Title = null,
                                       ACMFormatFlags Flags = ACMFormatFlags.Default,
                                       WaveFormatTag Encoding = WaveFormatTag.Unknown)
        {
            var acMflags = BitHelper.MakeLong((short)(Flags | ACMFormatFlags.Unicode), (short)Encoding);

            return BASS_Encode_GetACMFormat(Handle, Format, FormatLength, Title, acMflags);
        }

        /// <summary>
        /// Sets up an encoder on a channel, using an ACM codec and sending the output to a user defined function.
        /// </summary>
        /// <param name="Handle">The channel handle... a HSTREAM, HMUSIC, or HRECORD.</param>
        /// <param name="Format">ACM codec output format (as returned by <see cref="GetACMFormat" />).</param>
        /// <param name="Flags">A combination of <see cref="EncodeFlags"/>.</param>
        /// <param name="Procedure">Callback function to receive the encoded data.</param>
        /// <param name="User">User instance data to pass to the callback function.</param>
        /// <returns>The encoder handle is returned if the encoder is successfully started, else 0 is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns>
        /// <remarks>
        /// The ACM encoder allows installed ACM (Audio Compression Manager) codecs to be used for encoding.
        /// The codec used is determined by the contents of the Format parameter.
        /// The <see cref="GetACMFormat" /> function can be used to initialize that.
        /// <para>
        /// Internally, the sending of sample data to the encoder is implemented via a DSP callback on the channel.
        /// That means when you play the channel (or call <see cref="Bass.ChannelGetData(int,IntPtr,int)" /> if it's a decoding channel), the sample data will be sent to the encoder at the same time.
        /// The encoding is performed in the DSP callback.
        /// There isn't a separate process doing the encoding, as when using an external encoder via <see cref="EncodeStart(int,string,EncodeFlags,EncodeProcedure,IntPtr)" />.
        /// </para>
        /// <para>
        /// By default, the encoder DSP has a priority setting of -1000, which determines where in the DSP chain the encoding is performed.
        /// That can be changed using the <see cref="DSPPriority"/> config option.
        /// </para>
        /// <para>
        /// Besides the automatic DSP system, data can also be manually fed to the encoder via the <see cref="EncodeWrite(int,IntPtr,int)" /> function.
        /// Both methods can be used together, but in general, the "automatic" system ought be paused when using the "manual" system, by use of the <see cref="EncodeFlags.Pause"/> flag or the <see cref="EncodeSetPaused" /> function.
        /// </para>
        /// <para>
        /// When queued encoding is enabled via the <see cref="EncodeFlags.Queue"/> flag, the DSP system or <see cref="EncodeWrite(int,IntPtr,int)" /> call will just buffer the data, and the data will then be fed to the encoder by another thread.
        /// The buffer will grow as needed to hold the queued data, up to a limit specified by the <see cref="EncodeFlags.Queue"/> config option.
        /// If the limit is exceeded (or there is no free memory), data will be lost;
        /// <see cref="EncodeSetNotify" /> can be used to be notified of that occurrence.
        /// The amount of data that is currently queued, as well as the queue limit and how much data has been lost, is available from <see cref="EncodeGetCount" />.
        /// </para>
        /// <para>When done encoding, use <see cref="EncodeStop(int)" /> to close the encoder.</para>
        /// <para>
        /// Multiple encoders can be set on a channel.
        /// For simplicity, the encoder functions will accept either an encoder handle or a channel handle.
        /// When using a channel handle, the function is applied to all encoders that are set on that channel.
        /// </para>
        /// </remarks>
        /// <exception cref="Errors.Handle"><paramref name="Handle" /> is not valid.</exception>
        /// <exception cref="Errors.NotAvailable">The codec specified in <paramref name="Format" /> couldn't be initialized.</exception>
        /// <exception cref="Errors.Unknown">Some other mystery problem!</exception>
        [DllImport(DllName, EntryPoint = "BASS_Encode_StartACM")]
        public static extern int EncodeStartACM(int Handle, IntPtr Format, EncodeFlags Flags, EncodeProcedure Procedure, IntPtr User = default(IntPtr));

        [DllImport(DllName, CharSet = CharSet.Unicode)]
        static extern int BASS_Encode_StartACMFile(int handle, IntPtr form, EncodeFlags flags, string filename);

        /// <summary>
        /// Sets up an encoder on a channel, using an ACM codec and writing the output to a file.
        /// </summary>
        /// <param name="Handle">The channel handle... a HSTREAM, HMUSIC, or HRECORD.</param>
        /// <param name="Format">ACM codec output format (as returned by <see cref="GetACMFormat" />).</param>
        /// <param name="Flags">A combination of <see cref="EncodeFlags"/>.</param>
        /// <param name="FileName">The filename to write.</param>
        /// <returns>The encoder handle is returned if the encoder is successfully started, else 0 is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns>
        /// <remarks>
        /// The ACM encoder allows installed ACM (Audio Compression Manager) codecs to be used for encoding.
        /// The codec used is determined by the contents of the Format parameter.
        /// The <see cref="GetACMFormat" /> function can be used to initialize that.
        /// <para>
        /// Internally, the sending of sample data to the encoder is implemented via a DSP callback on the channel.
        /// That means when you play the channel (or call <see cref="Bass.ChannelGetData(int,IntPtr,int)" /> if it's a decoding channel), the sample data will be sent to the encoder at the same time.
        /// The encoding is performed in the DSP callback.
        /// There isn't a separate process doing the encoding, as when using an external encoder via <see cref="EncodeStart(int,string,EncodeFlags,EncodeProcedure,IntPtr)" />.
        /// </para>
        /// <para>
        /// By default, the encoder DSP has a priority setting of -1000, which determines where in the DSP chain the encoding is performed.
        /// That can be changed using the <see cref="DSPPriority"/> config option.
        /// </para>
        /// <para>
        /// Besides the automatic DSP system, data can also be manually fed to the encoder via the <see cref="EncodeWrite(int,IntPtr,int)" /> function.
        /// Both methods can be used together, but in general, the "automatic" system ought be paused when using the "manual" system, by use of the <see cref="EncodeFlags.Pause"/> flag or the <see cref="EncodeSetPaused" /> function.
        /// </para>
        /// <para>
        /// When queued encoding is enabled via the <see cref="EncodeFlags.Queue"/> flag, the DSP system or <see cref="EncodeWrite(int,IntPtr,int)" /> call will just buffer the data, and the data will then be fed to the encoder by another thread.
        /// The buffer will grow as needed to hold the queued data, up to a limit specified by the <see cref="EncodeFlags.Queue"/> config option.
        /// If the limit is exceeded (or there is no free memory), data will be lost;
        /// <see cref="EncodeSetNotify" /> can be used to be notified of that occurrence.
        /// The amount of data that is currently queued, as well as the queue limit and how much data has been lost, is available from <see cref="EncodeGetCount" />.
        /// </para>
        /// <para>When done encoding, use <see cref="EncodeStop(int)" /> to close the encoder.</para>
        /// <para>
        /// Multiple encoders can be set on a channel.
        /// For simplicity, the encoder functions will accept either an encoder handle or a channel handle.
        /// When using a channel handle, the function is applied to all encoders that are set on that channel.
        /// </para>
        /// </remarks>
        /// <exception cref="Errors.Handle"><paramref name="Handle" /> is not valid.</exception>
        /// <exception cref="Errors.NotAvailable">The codec specified in <paramref name="Format" /> couldn't be initialized.</exception>
        /// <exception cref="Errors.Create">The file couldn't be created.</exception>
        /// <exception cref="Errors.Unknown">Some other mystery problem!</exception>
        public static int EncodeStartACM(int Handle, IntPtr Format, EncodeFlags Flags, string FileName)
        {
            return BASS_Encode_StartACMFile(Handle, Format, Flags | EncodeFlags.Unicode, FileName);
        }
    }
}


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QDBUSPENDINGCALLWATCHERSLOTS_H
#define QDBUSPENDINGCALLWATCHERSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>

#include <QtDBus/QDBusPendingCallWatcher>

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

class QDBusPendingCallWatcherSlots: public QObject
{
  Q_OBJECT
  public:
  QDBusPendingCallWatcherSlots( QObject *parent = 0 );
  ~QDBusPendingCallWatcherSlots();
  public slots:
  void finished( QDBusPendingCallWatcher * self );
};

#endif /* QDBUSPENDINGCALLWATCHERSLOTS_H */


text:
import json
import shutil

from mock import Mock
import pytest

from hackerranksetup import Repository, Challenge
from tests import sample_config, sample_url, sample_assets

challenge_model = json.load(open(sample_assets('challenge_request.json')))[
    'model']

@pytest.fixture
def mock_challenge():
    mock = Mock(spec=Challenge)
    mock.json.return_value = {'test': 'success'}
    mock.from_repo.return_value = Challenge(sample_url, model=challenge_model,
                                            requests=Mock())
    return mock

@pytest.fixture
def repo(tmpdir, mock_challenge):
    mock_config = tmpdir.join('repository_config.json').strpath
    shutil.copyfile(sample_config, mock_config)

    repository = Repository(mock_config, mock_challenge)
    return repository

def test_config_file_patched_properly(repo, tmpdir):
    assert repo.config_file == tmpdir.join('repository_config.json').strpath
    assert repo.root == '/home/manu/code/HackerRankSetup/tests'

def test_root(repo):
    assert repo.root == '/home/manu/code/HackerRankSetup/tests'

def test_assets(repo):
    assert repo.assets == '/home/manu/code/HackerRankSetup/tests/assets'

def test_workspace(repo):
    assert repo.workspace == '/home/manu/code/HackerRankSetup/tests/workspace'

def test_get_current_challenge(repo):
    assert repo.current_challenge == json.load(open(sample_config))['Current']

def test_set_current_challenge(repo, mock_challenge):
    del repo.current_challenge
    assert repo.current_challenge is None

    repo.current_challenge = mock_challenge

    assert repo.current_challenge['test'] == 'success'

def test_delete_current_config(repo):
    del repo.current_challenge
    assert repo.current_challenge is None

def test_saves_on_set_current_challenge(repo, mock_challenge, tmpdir):
    del repo.current_challenge
    assert repo.current_challenge is None

    repo.current_challenge = mock_challenge

    assert repo.current_challenge['test'] == 'success'

    with tmpdir.join('repository_config.json').open() as f:
        tmp_repo_dict = json.load(f)

    assert tmp_repo_dict['Current']['test'] == 'success'

def test_saves_on_del_current_challenge(repo, tmpdir):
    del repo.current_challenge
    assert repo.current_challenge is None

    with tmpdir.join('repository_config.json').open() as f:
        tmp_repo_dict = json.load(f)

    assert tmp_repo_dict.get('Current') is None
    with pytest.raises(KeyError):
        assert tmp_repo_dict['Current']

def test_nested_archive(repo):
    repo.data = {}
    # assert repo.archive is None
    # assert repo.current_challenge is None

    mock = Mock()
    mock.track_main = "test track main"
    mock.track_sub = "test track sub"
    mock.name = "test name"
    mock.url = " test url"
    mock.path = "test path"
    mock.json.return_value = {'test': 'success'}

    repo.data['Current'] = mock
    repo.Challenge.from_repo.return_value = mock
    del repo.current_challenge

    expected_partial = {'path': 'test path', 'url': ' test url'}
    expected = {
        'test track main': {'test track sub': {'test name': expected_partial}}}
    assert repo.data['Archive'] == expected

def test_archive(repo):
    expected = {'test': 'success'}
    repo.data['Archive'] = expected
    assert repo.archive == expected


text:
package com.teedrei.rools.localize;

import java.util.Locale;

import com.teedrei.rools.rulesengine.Condition;
import com.teedrei.rools.rulesengine.Facts;

/**
 * Hello World Condition. This will check if a name exist in the data context.
 *
 * @author edward.biton@gmail.com
 */
public class LocalizeGreetingCondition implements Condition
{
	public static final String LOCALE_KEY = "LOCALE";

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.teedrei.simplerulesengine.rulesengine.rules.Condition#evaluate(com.teedrei.simplerulesengine.rulesengine.
	 * rules.Facts)
	 */
	@Override
	public boolean evaluate(Facts facts)
	{
		Locale locale = (Locale) facts.get(LOCALE_KEY);
		if (locale == null)
		{
			return false;
		}
		return true;
	}

}


text:
APPNAME="HXGame"

# options

buildexternalsfromsource=

usage(){
cat << EOF
usage: $0 [options]

Build C/C++ code for $APPNAME using Android NDK

OPTIONS:
-s  Build externals from source
-h  this help
EOF
}

while getopts "sh" OPTION; do
case "$OPTION" in
s)
buildexternalsfromsource=1
;;
h)
usage
exit 0
;;
esac
done

# paths

if [ -z "${NDK_ROOT+aaa}" ];then
echo "please define NDK_ROOT"
exit 1
fi

# For compatibility of android-ndk-r9, 4.7 was removed from r9
if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then
    export NDK_TOOLCHAIN_VERSION=4.7
    echo "The Selected NDK toolchain version was 4.7 !"
else
    if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then
        export NDK_TOOLCHAIN_VERSION=4.8
        echo "The Selected NDK toolchain version was 4.8 !"
    else
        echo "Couldn't find the gcc toolchain."
        exit 1
    fi
fi

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# ... use paths relative to current directory
COCOS2DX_ROOT="$DIR/../libs"
APP_ROOT="$DIR/.."
APP_ANDROID_ROOT="$DIR"

echo "NDK_ROOT = $NDK_ROOT"
echo "COCOS2DX_ROOT = $COCOS2DX_ROOT"
echo "APP_ROOT = $APP_ROOT"
echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT"

# make sure assets is exist
if [ -d "$APP_ANDROID_ROOT"/assets ]; then
    rm -rf "$APP_ANDROID_ROOT"/assets
fi

mkdir "$APP_ANDROID_ROOT"/assets

# copy resources
for file in "$APP_ROOT"/Resources/*
do
if [ -d "$file" ]; then
    cp -rf "$file" "$APP_ANDROID_ROOT"/assets
fi

if [ -f "$file" ]; then
    cp "$file" "$APP_ANDROID_ROOT"/assets
fi
done

# copy common luaScript
#for file in "$APP_ROOT"/../../scripting/lua/script/*
#do
#if [ -d "$file" ]; then
#    cp -rf "$file" "$APP_ANDROID_ROOT"/assets
#fi
#
#if [ -f "$file" ]; then
#    cp "$file" "$APP_ANDROID_ROOT"/assets
#fi
#done

# create luaScript.zip
#`mv "$APP_ANDROID_ROOT"/assets/luaScript luaScript`
#filelist=`find luaScript -name "*.lua"`
#echo "生成luac"
#for file in $filelist; do `luac -o $file $file`;echo "生成$file"; done;
#echo "生存luaScript.zip"
#if [ -f "APP_ANDROID_ROOT/assets/luaScript.zip" ];  then
#    `rm "$APP_ANDROID_ROOT"/assets/luaScript.zip`
#fi
#`zip "$APP_ANDROID_ROOT"/assets/luaScript.zip -r luaScript`
#`rm -rf luaScript`

if [[ "$buildexternalsfromsource" ]]; then
    echo "Building external dependencies from source"
    "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \
        "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source"
else
    echo "Using prebuilt externals"
    "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \
        "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt"
fi

## 打包apk
ant debug


text:
var message = require('./message');
var EventEmitter = require('events').EventEmitter;

/*

Handle socket events
----

*/

var handlers = {};

/*

Received a patch.

*/
handlers.patch = function (self, data) {
  //> We can only apply the patch if the sequence remains unbroken.
  //> if this happens we tell the server we need a fresh copy
  if (data.seq !== self.obj.seq + 1) {
    self.events.emit('error', 'SEQ BROKEN', data);
    self._send({
      cmd: 'refresh'
    });
    return;
  }

  //> update our copy of the state, and the sequence.
  self.applyPatch(self.obj.state, data.data);
  self.obj.seq = data.seq;

  self.events.emit('patch', data.data, data.seq);
};

/*

Received a refresh.

*/
handlers.refresh = function (self, data) {
  self.obj.state = data.state;
  self.obj.seq = data.seq;

  self.events.emit('refresh', self.obj.state, self.obj.seq);
};

function Client (ws, applyPatchFunc) {
  this.obj = {
    state: {},
    seq: 0
  };

  this.ws = ws;
  this.applyPatch = applyPatchFunc;
  this.events = new EventEmitter();

  this._setup();
}

Client.prototype.patch = function (data) {
  //> update the state (but not seq)
  this.applyPatch(this.obj.state, data);

  // TODO: need own copy
  handlers['patch-ack'] = function (self, data) {
    delete handlers['patch-ack'];

    self.events.emit('patch-ack', data);
  };

  //> send the patch cmd to the server along with the current seq
  this._send({
    cmd: 'patch',
    data: data,
    seq: this.obj.seq
  });
};

Client.prototype._send = function (data) {
  this.ws.send(message.encode(data));
};

Client.prototype._setup = function () {
  var self = this;
  this.ws.addEventListener('message', function (event) {
    var data = message.decode(event.data);
    if (!data) { return; }

    var handler = handlers[data.type];
    if (!handler) {
      return self.events.emit('error', 'UNKNOWN MSG TYPE', data);
    }

    handler(self, data);
  });
};

module.exports = Client;


text:
"""
Backup script for postgres DB.  This must be run as user postgres.
   type 'gunzip -c filename.gz | psql'
"""

# Don't change anything below this line
import os
import subprocess
import sys
import time

if len(sys.argv) != 2:
    print "args: backup_directory"
    sys.exit()

dir = sys.argv[1]

filename = "%d.sql.gz" % (time.time())
path = "%s/%s" % (dir, filename)
bk_command = "pg_dump -C -U qurkexp qurkexp | gzip > %s" % (path)

print "Backing up..."
os.system(bk_command)

print "Created %s" % (path)


text:
<?php
script('settings', 'certificates');
?>

<?php p($l->t('SSL Root Certificates')); ?>

	<table id="sslCertificate" class="grid" data-type="<?php p($_['type']); ?>">

				<?php p($l->t('Common Name')); ?>
				<?php p($l->t('Valid until')); ?>
				<?php p($l->t('Issued By')); ?>

		<?php foreach ($_['certs'] as $rootCert): /**@var \OCP\ICertificate $rootCert */ ?>
			<tr class="<?php echo ($rootCert->isExpired()) ? 'expired' : 'valid' ?>"
				data-name="<?php p($rootCert->getName()) ?>">
				<td class="rootCert"
					title="<?php p($rootCert->getOrganization()) ?>">
					<?php p($rootCert->getCommonName()) ?>

				<td title="<?php p($l->t('Valid until %s', $l->l('date', $rootCert->getExpireDate()))) ?>">
					<?php echo $l->l('date', $rootCert->getExpireDate()) ?>

				<td title="<?php p($rootCert->getIssuerOrganization()) ?>">
					<?php p($rootCert->getIssuerName()) ?>

				<td <?php if ($rootCert != ''): ?>class="remove"
					<?php else: ?>style="visibility:hidden;"
					<?php endif; ?>><img alt="<?php p($l->t('Delete')); ?>"
										 title="<?php p($l->t('Delete')); ?>"
										 class="action"
										 src="<?php print_unescaped(image_path('core', 'actions/delete.svg')); ?>"/>

		<?php endforeach; ?>

	<form class="uploadButton" method="post"
		  action="<?php p($_['urlGenerator']->linkToRoute($_['uploadRoute'])); ?>"
		  target="certUploadFrame">
		<?php p($l->t('Import root certificate')); ?>
		<input type="file" id="rootcert_import" name="rootcert_import"
			   class="hiddenuploadfield">
	</form>


text:
class chart(object):
    """Base class for a C3 chart object"""

    def __init__(self):
        """Constructor"""
        self.name = ""
        self.c3Name = ""
        self.stacked = False

    def getMinFields(self):
        """Minimum limit for the amount of fields in a viz"""
        return 1

    def getMaxFields(self):
        """Maximum limit for the amount of fields in a viz"""
        return 999 # Come on, you're using the wrong tech if you want to exceed this

    def getFieldErrMessage(self):
        """The error message given when the wrong amount of fields are selected"""
        return "requires at least one field in a data range"

    def getStackingScript(self, ranges):
        """Get the javascript for stacking the ranges on top of each other

        :param ranges: The names of the data ranges
        :type ranges: list

        :returns: The javascript required for the stacking to work in C3
        :rtype: string
        """

        # We want a string in the format
        # groups: [['data1', 'data2']]

        delimit = u""" "data{0}" """
        template = u"groups: [[{0}]],"
        temp = []

        if self.stacked == True:
            i = 1
            for r in ranges:
                temp.append(delimit.format(i))

                i += 1

            return template.format(u",".join(temp))

        else:
            return u""

    def getMinMaxRange(self, main, ranges):
        """Compare the min and max values for all attributes to retrieve the full range of data values

        :param main: The QgsVectorLayer with the data for the viz
        :type main: QgsVectorLayer

        :returns: The min and max values
        :rtype: int, int
        """
        lmin = []
        lmax = []

        rmin = 0
        rmax = 0

        for r in ranges:
            for f in r.getFields():
                index = main.layer.fieldNameIndex(f)
                lmin.append(main.layer.minimumValue(index))
                lmax.append(main.layer.maximumValue(index))

        if len(lmin) > 0:
            min(lmin)
        if len(lmax) > 0:
            if self.stacked == True:
                # stacked charts require the total of the values on the y axis
                rmax = sum(lmax)
            else:
                rmax = max(lmax)

        return rmin, rmax

    def getJavaScript(self, main, ranges, labels, width, height, ext):
        """Create the chart javascript"""

        value = ""

        '''Trying to return something along the lines of:

         function chart(obj) {
            var par = d3.select(".d3-tip #chart")
            var labels = ["x", 2004, 2007, 2010];
            var data0 = ["data0", obj["OVRK2004"], obj["OVRK2007"], obj["OVRK2010"]];
            var data1 = ["data1", obj["INCRK2004"], obj["INCRK2007"], obj["INCRK2010"]];

            var chart = c3.generate({
                bindto: par,
                data: {
                    x: "x",
                    type: "line",
                    columns: [
                      labels,
                      data0,
                      data1
                    ],
                    groups: [
                        ['data0', 'data1']
                    ]
                    names: {
                        data0: "Overall",
                        data1: "Income"
                    }
                },
                size: {
                    width: 240,
                    height: 240
                },
                axis: {
                    y: {
                        min: 0,
                        max: 32000
                    }
                }
            });
        }
        '''

        template = u"""    function chart(obj){{
      var par = d3.select("{par}")
      {labels}
      {vars}

      var chart = c3.generate({{
        bindto: par,
        data: {{
          {xaxis}
          type: "{chartName}",
          columns: [
            {labelvar}{data}
          ],
          {groups}
          names: {{ {names} }}
        }},
        size: {{
          width: {width},
          height: {height}
        }},
        axis: {{
          y: {{
            min: {min},
            max: {max}
          }}
        }}
      }});
    }}"""

        parentTemplate = u".d3-tip #chart"
        if ext == True:
            parentTemplate = "#extTip #chart"

        min, max = self.getMinMaxRange(main, ranges)

        # var labels = ["x", 2004, 2007, 2010];
        labelPart = u"""var labels = ["x", {0}];"""
        labelTemplate = labelPart.format(u",".join(labels))
        labelVarTemplate = u"labels,"

        # var data1 = ["data1", obj["OVRK2004"], obj["OVRK2007"], obj["OVRK2010"]];
        varPart = u"""var data{0} = ["data{0}", {1}];"""
        fieldPart = u"""obj["{0}"]"""
        varTemplate = u""
        varList = []
        # Need to check the length of all the labels
        # x: "x",
        xaxisTemplate = u"""x: "x","""
        for l in labels:
            if len(l) == 0:
                # not all labels specified, so don't need this
                xaxisTemplate = u""
                labelTemplate = u""
                labelVarTemplate = u""
            break

        # data1, data2, ...
        dataPart = u"""data{0}"""
        dataTemplate = u""
        dataList = []

        # data1: "Overall", data2: "Income", ...
        namesPart = u"""data{0}: "{1}" """
        namesTemplate = u""
        nameList = []

        i = 1
        for r in ranges:
            varList.append(varPart.format(str(i), r.getCsvFormattedFields(fieldPart)))
            dataList.append(dataPart.format(str(i)))
            nameList.append(namesPart.format(str(i), r.getName()))

            i += 1

        varTemplate = " ".join(varList)
        dataTemplate = ", ".join(dataList)
        namesTemplate = ",".join(nameList)

        value = template.format(
            par = parentTemplate,
            labels = labelTemplate,
            vars = varTemplate,
            xaxis = xaxisTemplate,
            chartName = self.c3Name,
            groups = self.getStackingScript(ranges),
            labelvar = labelVarTemplate,
            data = dataTemplate,
            names = namesTemplate,
            width = width,
            height = height,
            min = min,
            max = max
            )

        return value

class area(chart):
    """Area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Area Chart"
        self.c3Name = "area"

class bar(chart):
    """Bar chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Bar Chart"
        self.c3Name = "bar"

class donut(chart):
    """Donut chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Donut Chart"
        self.c3Name = "donut"

class gauge(chart):
    """Gauge chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Gauge Chart"
        self.c3Name = "gauge"

    def getMaxFields(self):
        """Limit for the amount of fields in a viz"""
        return 1

    def getFieldErrMessage(self):
        """The error message given when the wrong amount of fields are selected"""
        return "requires only one field to be in a data range"

class line(chart):
    """Line chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Line Chart"
        self.c3Name = "line"

class pie(chart):
    """Pie chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Pie Chart"
        self.c3Name = "pie"

class scatterplot(chart):
    """Stacked bar chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Scatterplot"
        self.c3Name = "scatter"

class spline(chart):
    """Spline chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Spline Chart"
        self.c3Name = "spline"

class splinearea(chart):
    """Spline area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Spline Area Chart"
        self.c3Name = "area-spline"

class step(chart):
    """Step chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Step Chart"
        self.c3Name = "step"

class steparea(chart):
    """Stepped area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Step Area Chart"
        self.c3Name = "area-step"

class stackedarea(chart):
    """Stacked area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Area Chart"
        self.c3Name = "area"
        self.stacked = True

class stackedbar(chart):
    """Stacked bar chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Bar Chart"
        self.c3Name = "bar"
        self.stacked = True

class stackedline(chart):
    """Stacked line chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Line Chart"
        self.c3Name = ""
        self.stacked = True

class stackedspline(chart):
    """Stacked spline chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Spline Chart"
        self.c3Name = "spline"
        self.stacked = True

class stackedsplinearea(chart):
    """Stacked splinee area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Spline Area Chart"
        self.c3Name = "area-spline"
        self.stacked = True

class stackedstep(chart):
    """Stacked step chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Step Chart"
        self.c3Name = "step"
        self.stacked = True

class stackedsteparea(chart):
    """Stacked step area chart"""

    def __init__(self):
        """Constructor"""
        chart.__init__(self)
        self.name = "Stacked Step Area Chart"
        self.c3Name = "area-step"
        self.stacked = True

class dataRanges(list):
    """Collection of dataRange objects"""

    def getRangeCount(self):
        """Retrieve the maximum count of objects within the data ranges"""
        maxLength = 0

        for r in self:
            length = r.getLength()
            if length > maxLength:
                maxLength = length

        return maxLength

    def getQtLabelMask(self):
        """Get the format mask for the data labels"""
        #Qt input mask.
        #Require ASCII numeric character followed by 9 optional ASCII numeric characters
        template = "9000000000"
        i = 0
        max = self.getRangeCount()
        temp = []

        while i < max:
           temp.append(template)
           i += 1

        return ",".join(temp)

class dataRange:
    """Collection of fields to be used in a range of data"""

    def __init__(self, name):
        """Create a new data range helper object"""
        self.__name = unicode(name)
        self.__formattedList = []
        self.__fieldList = []

        temp = u""
        if len(name) > 0:
            temp = name + ":"
            temp = temp.ljust(11)

        self.__displayPrompt = temp

    def appendField(self, item):
        """Append method to format the field name"""
        self.__formattedList.append(item.ljust(11))
        self.__fieldList.append(item)

    def getName(self):
        """Get the data range name"""
        return self.__name

    def getFields(self):
        """Get the field list in the range"""
        return self.__fieldList

    def getCsvFormattedFields(self, formatString):
        """Concatenate the fields together with custom string format"""
        # e.g. obj["{0}"]
        temp = []
        for f in self.__fieldList:
            temp.append(formatString.format(f))

        return u",".join(temp)

    def getLength(self):
        """Get the the amount of fields in the data range"""
        return len(self.__fieldList)

    def getDisplayString(self):
        """Display the list as a whitespace separated string for display in a field
        Each field is limited to 10 characters (shapefile field name length)
        Name displayed at the beginning of the string
        e.g. NAME:      ITEM1      ITEM2      ITEM3      """
        temp = ""

        if len(self.__displayPrompt) > 0:
            temp = self.__displayPrompt
        temp += u', '.join(self.__formattedList)

        return temp


text:
<?php

namespace FooNamespace;

abstract class FooClass
{

	public function allParametersWithNullableTypeHints(?string $string, ?int $int = 10, ?bool $bool, ?float $float = 0.0, ?callable $callable, ?array $array, ?\FooNamespace\FooClass $object = null)
	{

	}

	abstract public function someParametersWithNullableTypeHints(?string $string, int $int, ?bool $bool = true, float $float, ?callable $callable, array $array = [], ?\FooNamespace\FooClass $object);

	abstract public function parametersWithWeirdDefinition(?string$string,int$int,?bool$bool=true,float$float,?callable$callable,array$array=[],?\FooNamespace\FooClass$object);

}


text:
package myzipfs

/*
	myzipfs implements fs.FS and fs.ReadDirFS interface for a zip archive.

*/

import (
	"archive/zip"
	"bytes"
	"io"
	"io/fs"
)

type ZipFs struct {
	*zip.Reader
	index int
}

// Open a zip file for the fs. If the file can't provide a io.ReadAt, the file is
// completely read in a buffer acting as a io.ReadAt.
func Open(fsys fs.FS, name string) (*ZipFs, error) {
	f, err := fsys.Open(name)
	if err != nil {
		return nil, err
	}
	s, err := f.Stat()
	if err != nil {
		return nil, err
	}
	return Reader(f, s.Size())
}

// makeReaderAt returns a ReaderAt from an io.Reader using ReadAll when needed
func makeReaderAt(r io.Reader) (io.ReaderAt, error) {
	if ra, ok := r.(io.ReaderAt); ok {
		return ra, nil
	}
	b, err := io.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(b), nil
}

// Reader return a ZipFs
func Reader(r io.Reader, size int64) (*ZipFs, error) {
	var err error
	zfs := ZipFs{}
	ra, err := makeReaderAt(r)
	if err != nil {
		return nil, err
	}
	zfs.Reader, err = zip.NewReader(ra, size)
	if err != nil {
		return nil, err
	}
	return &zfs, nil
}

// ReadDir implements the ReadDir interface
func (zfs *ZipFs) ReadDir(name string) ([]fs.DirEntry, error) {
	ds := []fs.DirEntry{}
	for _, d := range zfs.File {
		ds = append(ds, &DirEntry{File: d})
	}
	return ds, nil
}

// DirEntry adds missing methods to implement fs.FileInfo
type DirEntry struct {
	*zip.File
}

func (de DirEntry) Info() (fs.FileInfo, error) {
	return de.FileInfo(), nil
}
func (de DirEntry) IsDir() bool {
	return de.Mode().IsDir()
}

func (de DirEntry) Name() string {
	return de.File.Name
}

func (de DirEntry) Type() fs.FileMode {
	return de.Mode()
}

func (zfs *ZipFs) Next() (fs.FS, string, error) {
	for ; zfs.index < len(zfs.Reader.File); zfs.index++ {
		f := zfs.Reader.File[zfs.index]
		zfs.index++
		if f.FileInfo().IsDir() {
			continue
		}

		return zfs, f.Name, nil
	}
	return nil, "", io.EOF
}


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.WebSites;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Instance of an app.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class SiteInstance : ProxyOnlyResource
    {
        /// <summary>
        /// Initializes a new instance of the SiteInstance class.
        /// </summary>
        public SiteInstance()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SiteInstance class.
        /// </summary>
        /// <param name="id">Resource Id.</param>
        /// <param name="name">Resource Name.</param>
        /// <param name="kind">Kind of resource.</param>
        /// <param name="type">Resource type.</param>
        /// <param name="siteInstanceName">Name of instance.</param>
        public SiteInstance(string id = default(string), string name = default(string), string kind = default(string), string type = default(string), string siteInstanceName = default(string))
            : base(id, name, kind, type)
        {
            SiteInstanceName = siteInstanceName;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets name of instance.
        /// </summary>
        [JsonProperty(PropertyName = "properties.name")]
        public string SiteInstanceName { get; private set; }

    }
}