text:
"""
Test cases for twisted.reflect module.
"""

import weakref, os
from ihooks import ModuleImporter

try:
    from collections import deque
except ImportError:
    deque = None

from twisted.trial import unittest
from twisted.python import reflect, util
from twisted.python.versions import Version

class SettableTest(unittest.TestCase):
    def setUp(self):
        self.setter = reflect.Settable()

    def tearDown(self):
        del self.setter

    def testSet(self):
        self.setter(a=1, b=2)
        self.assertEqual(self.setter.a, 1)
        self.assertEqual(self.setter.b, 2)

class AccessorTester(reflect.Accessor):

    def set_x(self, x):
        self.y = x
        self.reallySet('x', x)

    def get_z(self):
        self.q = 1
        return 1

    def del_z(self):
        self.reallyDel("q")

class PropertyAccessorTester(reflect.PropertyAccessor):
    """
    Test class to check L{reflect.PropertyAccessor} functionalities.
    """
    r = 0

    def set_r(self, r):
        self.s = r

    def set_x(self, x):
        self.y = x
        self.reallySet('x', x)

    def get_z(self):
        self.q = 1
        return 1

    def del_z(self):
        self.reallyDel("q")

class AccessorTest(unittest.TestCase):
    def setUp(self):
        self.tester = AccessorTester()

    def testSet(self):
        self.tester.x = 1
        self.assertEqual(self.tester.x, 1)
        self.assertEqual(self.tester.y, 1)

    def testGet(self):
        self.assertEqual(self.tester.z, 1)
        self.assertEqual(self.tester.q, 1)

    def testDel(self):
        self.tester.z
        self.assertEqual(self.tester.q, 1)
        del self.tester.z
        self.assertEqual(hasattr(self.tester, "q"), 0)
        self.tester.x = 1
        del self.tester.x
        self.assertEqual(hasattr(self.tester, "x"), 0)

class PropertyAccessorTest(AccessorTest):
    """
    Tests for L{reflect.PropertyAccessor}, using L{PropertyAccessorTester}.
    """

    def setUp(self):
        self.tester = PropertyAccessorTester()

    def test_setWithDefaultValue(self):
        """
        If an attribute is present in the class, it can be retrieved by
        default.
        """
        self.assertEqual(self.tester.r, 0)
        self.tester.r = 1
        self.assertEqual(self.tester.r, 0)
        self.assertEqual(self.tester.s, 1)

    def test_getValueInDict(self):
        """
        The attribute value can be overriden by directly modifying the value in
        C{__dict__}.
        """
        self.tester.__dict__["r"] = 10
        self.assertEqual(self.tester.r, 10)

    def test_notYetInDict(self):
        """
        If a getter is defined on an attribute but without any default value,
        it raises C{AttributeError} when trying to access it.
        """
        self.assertRaises(AttributeError, getattr, self.tester, "x")

class LookupsTestCase(unittest.TestCase):
    """
    Tests for L{namedClass}, L{namedModule}, and L{namedAny}.
    """

    def test_namedClassLookup(self):
        """
        L{namedClass} should return the class object for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedClass("twisted.python.reflect.Summer"),
            reflect.Summer)

    def test_namedModuleLookup(self):
        """
        L{namedModule} should return the module object for the name it is
        passed.
        """
        self.assertIdentical(
            reflect.namedModule("twisted.python.reflect"), reflect)

    def test_namedAnyPackageLookup(self):
        """
        L{namedAny} should return the package object for the name it is passed.
        """
        import twisted.python
        self.assertIdentical(
            reflect.namedAny("twisted.python"), twisted.python)

    def test_namedAnyModuleLookup(self):
        """
        L{namedAny} should return the module object for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedAny("twisted.python.reflect"), reflect)

    def test_namedAnyClassLookup(self):
        """
        L{namedAny} should return the class object for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedAny("twisted.python.reflect.Summer"), reflect.Summer)

    def test_namedAnyAttributeLookup(self):
        """
        L{namedAny} should return the object an attribute of a non-module,
        non-package object is bound to for the name it is passed.
        """
        # Note - not assertEqual because unbound method lookup creates a new
        # object every time.  This is a foolishness of Python's object
        # implementation, not a bug in Twisted.
        self.assertEqual(
            reflect.namedAny("twisted.python.reflect.Summer.reallySet"),
            reflect.Summer.reallySet)

    def test_namedAnySecondAttributeLookup(self):
        """
        L{namedAny} should return the object an attribute of an object which
        itself was an attribute of a non-module, non-package object is bound to
        for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedAny(
                "twisted.python.reflect.Summer.reallySet.__doc__"),
            reflect.Summer.reallySet.__doc__)

    def test_importExceptions(self):
        """
        Exceptions raised by modules which L{namedAny} causes to be imported
        should pass through L{namedAny} to the caller.
        """
        self.assertRaises(
            ZeroDivisionError,
            reflect.namedAny, "twisted.test.reflect_helper_ZDE")
        # Make sure that this behavior is *consistent* for 2.3, where there is
        # no post-failed-import cleanup
        self.assertRaises(
            ZeroDivisionError,
            reflect.namedAny, "twisted.test.reflect_helper_ZDE")
        self.assertRaises(
            ValueError,
            reflect.namedAny, "twisted.test.reflect_helper_VE")
        # Modules which themselves raise ImportError when imported should result in an ImportError
        self.assertRaises(
            ImportError,
            reflect.namedAny, "twisted.test.reflect_helper_IE")

    def test_attributeExceptions(self):
        """
        If segments on the end of a fully-qualified Python name represents
        attributes which aren't actually present on the object represented by
        the earlier segments, L{namedAny} should raise an L{AttributeError}.
        """
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuchmoduleintheworld")
        # ImportError behaves somewhat differently between "import
        # extant.nonextant" and "import extant.nonextant.nonextant", so test
        # the latter as well.
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuch.modulein.theworld")
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.python.reflect.Summer.nosuchattributeintheworld")

    def test_invalidNames(self):
        """
        Passing a name which isn't a fully-qualified Python name to L{namedAny}
        should result in one of the following exceptions:
        - L{InvalidName}: the name is not a dot-separated list of Python objects
        - L{ObjectNotFound}: the object doesn't exist
        - L{ModuleNotFound}: the object doesn't exist and there is only one
          component in the name
        """
        err = self.assertRaises(reflect.ModuleNotFound, reflect.namedAny,
                                'nosuchmoduleintheworld')
        self.assertEqual(str(err), "No module named 'nosuchmoduleintheworld'")

        # This is a dot-separated list, but it isn't valid!
        err = self.assertRaises(reflect.ObjectNotFound, reflect.namedAny,
                                "@#$@(#.!@(#!@#")
        self.assertEqual(str(err), "'@#$@(#.!@(#!@#' does not name an object")

        err = self.assertRaises(reflect.ObjectNotFound, reflect.namedAny,
                                "tcelfer.nohtyp.detsiwt")
        self.assertEqual(
            str(err),
            "'tcelfer.nohtyp.detsiwt' does not name an object")

        err = self.assertRaises(reflect.InvalidName, reflect.namedAny, '')
        self.assertEqual(str(err), 'Empty module name')

        for invalidName in ['.twisted', 'twisted.', 'twisted..python']:
            err = self.assertRaises(
                reflect.InvalidName, reflect.namedAny, invalidName)
            self.assertEqual(
                str(err),
                "name must be a string giving a '.'-separated list of Python "
                "identifiers, not %r" % (invalidName,))

class ImportHooksLookupTests(LookupsTestCase):
    """
    Tests for lookup methods in the presence of L{ihooks}-style import hooks.
    Runs all of the tests from L{LookupsTestCase} after installing a custom
    import hook.
    """
    def setUp(self):
        """
        Perturb the normal import behavior subtly by installing an import
        hook.  No custom behavior is provided, but this adds some extra
        frames to the call stack, which L{namedAny} must be able to account
        for.
        """
        self.importer = ModuleImporter()
        self.importer.install()

    def tearDown(self):
        """
        Uninstall the custom import hook.
        """
        self.importer.uninstall()

class ObjectGrep(unittest.TestCase):
    def test_dictionary(self):
        """
        Test references search through a dictionnary, as a key or as a value.
        """
        o = object()
        d1 = {None: o}
        d2 = {o: None}

        self.assertIn("[None]", reflect.objgrep(d1, o, reflect.isSame))
        self.assertIn("{None}", reflect.objgrep(d2, o, reflect.isSame))

    def test_list(self):
        """
        Test references search through a list.
        """
        o = object()
        L = [None, o]

        self.assertIn("[1]", reflect.objgrep(L, o, reflect.isSame))

    def test_tuple(self):
        """
        Test references search through a tuple.
        """
        o = object()
        T = (o, None)

        self.assertIn("[0]", reflect.objgrep(T, o, reflect.isSame))

    def test_instance(self):
        """
        Test references search through an object attribute.
        """
        class Dummy:
            pass
        o = object()
        d = Dummy()
        d.o = o

        self.assertIn(".o", reflect.objgrep(d, o, reflect.isSame))

    def test_weakref(self):
        """
        Test references search through a weakref object.
        """
        class Dummy:
            pass
        o = Dummy()
        w1 = weakref.ref(o)

        self.assertIn("()", reflect.objgrep(w1, o, reflect.isSame))

    def test_boundMethod(self):
        """
        Test references search through method special attributes.
        """
        class Dummy:
            def dummy(self):
                pass
        o = Dummy()
        m = o.dummy

        self.assertIn(".im_self", reflect.objgrep(m, m.im_self, reflect.isSame))
        self.assertIn(".im_class", reflect.objgrep(m, m.im_class, reflect.isSame))
        self.assertIn(".im_func", reflect.objgrep(m, m.im_func, reflect.isSame))

    def test_everything(self):
        """
        Test references search using complex set of objects.
        """
        class Dummy:
            def method(self):
                pass

        o = Dummy()
        D1 = {(): "baz", None: "Quux", o: "Foosh"}
        L = [None, (), D1, 3]
        T = (L, {}, Dummy())
        D2 = {0: "foo", 1: "bar", 2: T}
        i = Dummy()
        i.attr = D2
        m = i.method
        w = weakref.ref(m)

        self.assertIn("().im_self.attr[2][0][2]{'Foosh'}", reflect.objgrep(w, o, reflect.isSame))

    def test_depthLimit(self):
        """
        Test the depth of references search.
        """
        a = []
        b = [a]
        c = [a, b]
        d = [a, c]

        self.assertEqual(['[0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=1))
        self.assertEqual(['[0]', '[1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=2))
        self.assertEqual(['[0]', '[1][0]', '[1][1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=3))

    def test_deque(self):
        """
        Test references search through a deque object. Only for Python > 2.3.
        """
        o = object()
        D = deque()
        D.append(None)
        D.append(o)

        self.assertIn("[1]", reflect.objgrep(D, o, reflect.isSame))

    if deque is None:
        test_deque.skip = "Deque not available"

class GetClass(unittest.TestCase):
    def testOld(self):
        class OldClass:
            pass
        old = OldClass()
        self.assertIn(reflect.getClass(OldClass).__name__, ('class', 'classobj'))
        self.assertEqual(reflect.getClass(old).__name__, 'OldClass')

    def testNew(self):
        class NewClass(object):
            pass
        new = NewClass()
        self.assertEqual(reflect.getClass(NewClass).__name__, 'type')
        self.assertEqual(reflect.getClass(new).__name__, 'NewClass')

class Breakable(object):

    breakRepr = False
    breakStr = False

    def __str__(self):
        if self.breakStr:
            raise RuntimeError("str!")
        else:
            return '<Breakable>'

    def __repr__(self):
        if self.breakRepr:
            raise RuntimeError("repr!")
        else:
            return 'Breakable()'

class BrokenType(Breakable, type):
    breakName = False

    def get___name__(self):
        if self.breakName:
            raise RuntimeError("no name")
        return 'BrokenType'
    __name__ = property(get___name__)

class BTBase(Breakable):
    __metaclass__ = BrokenType
    breakRepr = True
    breakStr = True

class NoClassAttr(Breakable):
    __class__ = property(lambda x: x.not_class)

class SafeRepr(unittest.TestCase):
    """
    Tests for L{reflect.safe_repr} function.
    """

    def test_workingRepr(self):
        """
        L{reflect.safe_repr} produces the same output as C{repr} on a working
        object.
        """
        x = [1, 2, 3]
        self.assertEqual(reflect.safe_repr(x), repr(x))

    def test_brokenRepr(self):
        """
        L{reflect.safe_repr} returns a string with class name, address, and
        traceback when the repr call failed.
        """
        b = Breakable()
        b.breakRepr = True
        bRepr = reflect.safe_repr(b)
        self.assertIn("Breakable instance at 0x", bRepr)
        # Check that the file is in the repr, but without the extension as it
        # can be .py/.pyc
        self.assertIn(os.path.splitext(__file__)[0], bRepr)
        self.assertIn("RuntimeError: repr!", bRepr)

    def test_brokenStr(self):
        """
        L{reflect.safe_repr} isn't affected by a broken C{__str__} method.
        """
        b = Breakable()
        b.breakStr = True
        self.assertEqual(reflect.safe_repr(b), repr(b))

    def test_brokenClassRepr(self):
        class X(BTBase):
            breakRepr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X())

    def test_unsignedID(self):
        """
        L{unsignedID} is used to print ID of the object in case of error, not
        standard ID value which can be negative.
        """
        class X(BTBase):
            breakRepr = True

        ids = {X: 100}
        def fakeID(obj):
            try:
                return ids[obj]
            except (TypeError, KeyError):
                return id(obj)
        self.addCleanup(util.setIDFunction, util.setIDFunction(fakeID))

        xRepr = reflect.safe_repr(X)
        self.assertIn("0x64", xRepr)

    def test_brokenClassStr(self):
        class X(BTBase):
            breakStr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X())

    def test_brokenClassAttribute(self):
        """
        If an object raises an exception when accessing its C{__class__}
        attribute, L{reflect.safe_repr} uses C{type} to retrieve the class
        object.
        """
        b = NoClassAttr()
        b.breakRepr = True
        bRepr = reflect.safe_repr(b)
        self.assertIn("NoClassAttr instance at 0x", bRepr)
        self.assertIn(os.path.splitext(__file__)[0], bRepr)
        self.assertIn("RuntimeError: repr!", bRepr)

    def test_brokenClassNameAttribute(self):
        """
        If a class raises an exception when accessing its C{__name__} attribute
        B{and} when calling its C{__str__} implementation, L{reflect.safe_repr}
        returns 'BROKEN CLASS' instead of the class name.
        """
        class X(BTBase):
            breakName = True
        xRepr = reflect.safe_repr(X())
        self.assertIn("<BROKEN CLASS AT 0x", xRepr)
        self.assertIn(os.path.splitext(__file__)[0], xRepr)
        self.assertIn("RuntimeError: repr!", xRepr)

class SafeStr(unittest.TestCase):
    """
    Tests for L{reflect.safe_str} function.
    """

    def test_workingStr(self):
        x = [1, 2, 3]
        self.assertEqual(reflect.safe_str(x), str(x))

    def test_brokenStr(self):
        b = Breakable()
        b.breakStr = True
        reflect.safe_str(b)

    def test_brokenRepr(self):
        b = Breakable()
        b.breakRepr = True
        reflect.safe_str(b)

    def test_brokenClassStr(self):
        class X(BTBase):
            breakStr = True
        reflect.safe_str(X)
        reflect.safe_str(X())

    def test_brokenClassRepr(self):
        class X(BTBase):
            breakRepr = True
        reflect.safe_str(X)
        reflect.safe_str(X())

    def test_brokenClassAttribute(self):
        """
        If an object raises an exception when accessing its C{__class__}
        attribute, L{reflect.safe_str} uses C{type} to retrieve the class
        object.
        """
        b = NoClassAttr()
        b.breakStr = True
        bStr = reflect.safe_str(b)
        self.assertIn("NoClassAttr instance at 0x", bStr)
        self.assertIn(os.path.splitext(__file__)[0], bStr)
        self.assertIn("RuntimeError: str!", bStr)

    def test_brokenClassNameAttribute(self):
        """
        If a class raises an exception when accessing its C{__name__} attribute
        B{and} when calling its C{__str__} implementation, L{reflect.safe_str}
        returns 'BROKEN CLASS' instead of the class name.
        """
        class X(BTBase):
            breakName = True
        xStr = reflect.safe_str(X())
        self.assertIn("<BROKEN CLASS AT 0x", xStr)
        self.assertIn(os.path.splitext(__file__)[0], xStr)
        self.assertIn("RuntimeError: str!", xStr)

class FilenameToModule(unittest.TestCase):
    """
    Test L{reflect.filenameToModuleName} detection.
    """
    def test_directory(self):
        """
        Tests it finds good name for directories/packages.
        """
        module = reflect.filenameToModuleName(os.path.join('twisted', 'test'))
        self.assertEqual(module, 'test')
        module = reflect.filenameToModuleName(os.path.join('twisted', 'test')
                                              + os.path.sep)
        self.assertEqual(module, 'test')

    def test_file(self):
        """
        Test it finds good name for files.
        """
        module = reflect.filenameToModuleName(
            os.path.join('twisted', 'test', 'test_reflect.py'))
        self.assertEqual(module, 'test_reflect')

class FullyQualifiedNameTests(unittest.TestCase):
    """
    Test for L{reflect.fullyQualifiedName}.
    """

    def _checkFullyQualifiedName(self, obj, expected):
        """
        Helper to check that fully qualified name of C{obj} results to
        C{expected}.
        """
        self.assertEqual(
            reflect.fullyQualifiedName(obj), expected)

    def test_package(self):
        """
        L{reflect.fullyQualifiedName} returns the full name of a package and
        a subpackage.
        """
        import twisted
        self._checkFullyQualifiedName(twisted, 'twisted')
        import twisted.python
        self._checkFullyQualifiedName(twisted.python, 'twisted.python')

    def test_module(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a module inside a a
        package.
        """
        self._checkFullyQualifiedName(reflect, 'twisted.python.reflect')
        import twisted.trial.unittest
        self._checkFullyQualifiedName(twisted.trial.unittest,
                                      'twisted.trial.unittest')

    def test_class(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a class and its
        module.
        """
        self._checkFullyQualifiedName(reflect.Settable,
                                      'twisted.python.reflect.Settable')

    def test_function(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a function inside its
        module.
        """
        self._checkFullyQualifiedName(reflect.fullyQualifiedName,
            "twisted.python.reflect.fullyQualifiedName")

    def test_boundMethod(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a bound method inside
        its class and its module.
        """
        self._checkFullyQualifiedName(
            reflect.PropertyAccessor().reallyDel,
            "twisted.python.reflect.PropertyAccessor.reallyDel")

    def test_unboundMethod(self):
        """
        L{reflect.fullyQualifiedName} returns the name of an unbound method
        inside its class and its module.
        """
        self._checkFullyQualifiedName(
            reflect.PropertyAccessor.reallyDel,
            "twisted.python.reflect.PropertyAccessor.reallyDel")

class DeprecationTestCase(unittest.TestCase):
    """
    Test deprecations in twisted.python.reflect
    """

    def test_allYourBase(self):
        """
        Test deprecation of L{reflect.allYourBase}. See #5481 for removal.
        """
        self.callDeprecated(
            (Version("Twisted", 11, 0, 0), "inspect.getmro"),
            reflect.allYourBase, DeprecationTestCase)

    def test_accumulateBases(self):
        """
        Test deprecation of L{reflect.accumulateBases}. See #5481 for removal.
        """
        l = []
        self.callDeprecated(
            (Version("Twisted", 11, 0, 0), "inspect.getmro"),
            reflect.accumulateBases, DeprecationTestCase, l, None)

    def lookForDeprecationWarning(self, testMethod, attributeName, warningMsg):
        """
        Test deprecation of attribute 'reflect.attributeName' by calling
        'reflect.testMethod' and verifying the warning message
        'reflect.warningMsg'

        @param testMethod: Name of the offending function to be used with
            flushWarnings
        @type testmethod: C{str}

        @param attributeName: Name of attribute to be checked for deprecation
        @type attributeName: C{str}

        @param warningMsg: Deprecation warning message
        @type warningMsg: C{str}
        """
        warningsShown = self.flushWarnings([testMethod])
        self.assertEqual(len(warningsShown), 1)
        self.assertIdentical(warningsShown[0]['category'], DeprecationWarning)
        self.assertEqual(
            warningsShown[0]['message'],
            "twisted.python.reflect." + attributeName + " "
            "was deprecated in Twisted 12.1.0: " + warningMsg + ".")

    def test_settable(self):
        """
        Test deprecation of L{reflect.Settable}.
        """
        reflect.Settable()
        self.lookForDeprecationWarning(
            self.test_settable, "Settable",
            "Settable is old and untested. Please write your own version of this "
            "functionality if you need it")

    def test_accessorType(self):
        """
        Test deprecation of L{reflect.AccessorType}.
        """
        reflect.AccessorType(' ', ( ), { })
        self.lookForDeprecationWarning(
            self.test_accessorType, "AccessorType",
            "AccessorType is old and untested. Please write your own version of "
            "this functionality if you need it")

    def test_propertyAccessor(self):
        """
        Test deprecation of L{reflect.PropertyAccessor}.
        """
        reflect.PropertyAccessor()
        self.lookForDeprecationWarning(
            self.test_propertyAccessor, "PropertyAccessor",
            "PropertyAccessor is old and untested. Please write your own "
            "version of this functionality if you need it")

    def test_accessor(self):
        """
        Test deprecation of L{reflect.Accessor}.
        """
        reflect.Accessor()
        self.lookForDeprecationWarning(
            self.test_accessor, "Accessor",
            "Accessor is an implementation for Python 2.1 which is no longer "
            "supported by Twisted")

    def test_originalAccessor(self):
        """
        Test deprecation of L{reflect.OriginalAccessor}.
        """
        reflect.OriginalAccessor()
        self.lookForDeprecationWarning(
            self.test_originalAccessor, "OriginalAccessor",
            "OriginalAccessor is a reference to class "
            "twisted.python.reflect.Accessor which is deprecated")

    def test_summer(self):
        """
        Test deprecation of L{reflect.Summer}.
        """
        reflect.Summer()
        self.lookForDeprecationWarning(
            self.test_summer, "Summer",
            "Summer is a child class of twisted.python.reflect.Accessor which "
            "is deprecated")


text:
import EventEmitter from 'events';
import Promise from 'bluebird';

// Error helper
function ExtendableError(message){
  Error.apply(this, arguments);
  if (typeof Error.captureStackTrace === 'function') {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = (new Error(message)).stack;
  }
}

ExtendableError.prototype = Object.create(Error.prototype);

Object.setPrototypeOf(ExtendableError, Error);

// Errors
export class EtcdClientRequiredError extends ExtendableError {
  constructor () {
    super('etcd client parameter is required');
  }
}

export class KeyRequiredError extends ExtendableError {
  constructor () {
    super('key parameter of type String is required');
  }
}

export class NodeIdRequiredError extends ExtendableError {
  constructor () {
    super('node_id parameter of type String is required')
  }
}

export class InvalidTtlError extends ExtendableError {
  constructor () {
    super('ttl parameter must be of type Number');
  }
}

export class AlreadyLockedError extends ExtendableError {
  constructor (key) {
    super(`Lock "${key}" is already locked`);
  }
}

export class LockNotOwnedError extends ExtendableError {
  constructor (key, node_id) {
    super(`Lock "${key}" is not owned by node "${node_id}"`);
  }
}

// Events
export const events = {
  locked: 'locked',
  unlocked: 'unlocked',
  error: 'error'
};

//Microlock
export default class Microlock extends EventEmitter {
  constructor (etcd, key, node_id, ttl = 1) {

    if (!etcd) throw new EtcdClientRequiredError();
    if (typeof key !== 'string') throw new KeyRequiredError();
    if (typeof node_id !== 'string') throw new NodeIdRequiredError();
    if (isNaN(ttl)) throw new InvalidTtlError();

    super();

    this.__etcd = etcd;
    this.__key = key;
    this.__node_id = node_id;
    this.__ttl = ttl < 1 ? 1 : ttl; //Require at least one second for ttl for stability of lock/unlock

    this.__watcher = this.__etcd.watcher(key);

    this.__watcher.on('compareAndDelete', () => this.emit(events.unlocked));
    this.__watcher.on('change', (v) => {
      if (v.node && v.node.ttl) this.emit(events.locked);
    });
  }

  // Private methods
  __throwAlreadyLocked () {
    const e = new AlreadyLockedError(this.__key);
    this.emit(events.error, e)
    throw e;
  }
  __throwLockNotOwned () {
    const e = new LockNotOwnedError(this.__key, this.__node_id);
    this.emit(events.error, e);
    throw e;
  }

  // Public methods
  destroy () {
    this.__watcher.stop();
    this.removeAllListeners();
  }

  lock () {
    return new Promise((resolve, reject) => {
      return this.__etcd.set(this.__key, this.__node_id, {
        ttl: this.__ttl,
        prevExist: false
      }, (err, val) => {
        if (err) return reject(err);
        return resolve(val)
      });
    })
    .catch((e) => {
      // Key already exists
      if (e.errorCode === 105) {
        this.__throwAlreadyLocked();
      }
      throw e;
    });
  }

  unlock () {
    return new Promise((resolve, reject) => {
      return this.__etcd.compareAndDelete(this.__key, this.__node_id, (err, res) => {
        if (err) return reject(err);
        return resolve(res);
      });
    })
    .catch((e) => {
      // KeyNotFound or CompareFailed
      if (e.errorCode === 100 || e.errorCode === 101) {
        this.__throwLockNotOwned();
      }
      throw e;
    });
  }

  renew () {
    return new Promise((resolve, reject) => {
      return this.__etcd.set(this.__key, null, {
        prevValue: this.__node_id,
        refresh: true,
        ttl: this.__ttl
      }, (err, val) => {
        if (err) return reject(err);
        return resolve(val);
      })
    })
    .catch((e) => {
      // KeyNotFound or CompareFailed
      if (e.errorCode === 100 || e.errorCode === 101) {
        this.__throwLockNotOwned();
      }
      throw e;
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

describe('Hexo', function(){
  require('./scripts/box');
  require('./scripts/console');
  require('./scripts/extend');
  require('./scripts/filters');
  require('./scripts/generators');
  require('./scripts/helpers');
  require('./scripts/hexo');
  require('./scripts/models');
  require('./scripts/processors');
  require('./scripts/renderers');
  require('./scripts/tags');
  require('./scripts/theme');
  require('./scripts/theme_processors');
});


text:
#pragma once

#include "../group/pile.hpp"

namespace morda{

/**
 * @brief container to be used for intercepting keyboard key events.
 * From GUI scripts it can be instantiated as "key_proxy".
 */
class key_proxy : public pile{
public:
	key_proxy(std::shared_ptr<morda::context> c, const treeml::forest& desc) :
			widget(std::move(c), desc),
			pile(this->context, desc)
	{}

	key_proxy(const key_proxy&) = delete;
	key_proxy& operator=(const key_proxy&) = delete;

	/**
	 * @brief Keyboard key signal.
	 * Emitted when a keyboard key event reaches this widget.
	 */
	std::function<bool(key_proxy& w, bool is_down, morda::key key_code)> key_handler;

	virtual bool on_key(bool is_down, morda::key key_code)override;
};

}


text:
/**
 *
 */
package com.netflix.conductor.tests.utils;

import com.google.common.util.concurrent.Uninterruptibles;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.Task.Status;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.core.execution.WorkflowExecutor;
import com.netflix.conductor.core.execution.tasks.WorkflowSystemTask;

import java.util.concurrent.TimeUnit;

/**
 * @author Viren
 *
 */
public class UserTask extends WorkflowSystemTask {

	private static final String NAME = "USER_TASK";

	public UserTask() {
		super(NAME);
	}

	@Override
	public void start(Workflow workflow, Task task, WorkflowExecutor executor) {
		Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
		task.setStatus(Status.COMPLETED);
	}

	@Override
	public boolean isAsync() {
		return true;
	}
}


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

namespace GuildedRose.Service.Service
{
    public interface IInventory
    {

        /// <summary>
        /// List all the Items in the Inventory
        /// </summary>
        /// <returns>List of ItemDTOs</returns>
        IEnumerable<ItemDTO> List();

        /// <summary>
        /// Find 1 specific Item base on the Name
        /// </summary>
        /// <param name="name"></param>
        /// <returns>ItemDTO</returns>
        ItemDTO GetItemByName(string name);

        /// <summary>
        /// Find 1 specific Item base on the Id
        /// </summary>
        /// <param name="name"></param>
        /// <returns>ItemDTO</returns>
        ItemDTO GetItemById(string id);

    }
}


text:
<?php

namespace istranger\rSmartLoad;

use istranger\rSmartLoad\base;
use yii\helpers\ArrayHelper;

/**
 * Yii2 class for read properties of current request (method, http headers, cookie...)
 *
 * @author  G.Azamat <m@fx4web.com>
 * @link    http://fx4.ru/
 * @link    https://github.com/IStranger/yii2-resource-smart-load
 * @since   2.0.2
 */
class RequestReader extends base\RequestReader
{
    /**
     * @inheritdoc
     */
    public function getIsAjax()
    {
        return $this->_req()->isAjax;
    }

    /**
     * @inheritdoc
     */
    public function getMethod()
    {
        return $this->_req()->method;
    }

    /**
     * @inheritdoc
     */
    public function getCurrentURL()
    {
        return $this->_req()->absoluteUrl;
    }

    /**
     * @inheritdoc
     */
    public function getReferrer()
    {
        return $this->_req()->referrer;
    }

    /**
     * @inheritdoc
     */
    public function getHttpHeader($name, $webserverPrefix = 'HTTP_')
    {
        $name = str_replace(array('-', ' '), '_', $name);
        return ArrayHelper::getValue($_SERVER, mb_strtoupper($webserverPrefix . $name));
    }

    /**
     * @inheritdoc
     */
    public function getCookieValue($cookieName, $default = null, $attribute = 'value')
    {
        $this->_req()->enableCookieValidation = false;
        $cookieObj = $this->_req()->cookies->get($cookieName);
        $this->_req()->enableCookieValidation = true;

        return ArrayHelper::getValue($cookieObj, $attribute, $default);
    }

    private function _req()
    {
        return \Yii::$app->request;
    }
}


text:
layout: post
title: "Boob"
tags: [citat]
---

> His hand reached for her boob over her shirt and pawed at it, his palm still
> while his fingers moved around. I woundered if that felt good. Didn't seem
> like it would, but I decided to forgive Isaac on the grounds that he was going
> blind. The senses must feast while there is yet hunger and wathever.

Från "The Fault in our Stars" av John Geen


text:
package org.optaplanner.osgi.common.app;

import java.net.URL;

import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.core.config.solver.termination.TerminationConfig;
import org.optaplanner.core.impl.score.director.InnerScoreDirectorFactory;
import org.optaplanner.osgi.common.persistence.SolutionDao;
import org.osgi.framework.BundleContext;

@SuppressWarnings("rawtypes")
public abstract class SolverPerformanceTest extends LoggingMain {

	protected SolutionDao solutionDao;
	private BundleContext bundleContext;

	public void setUp() {
		solutionDao = createSolutionDao();
		OSGiSolverFactory.setContext(bundleContext);
	}

	protected abstract String createSolverConfigResource();

	protected abstract SolutionDao createSolutionDao();

	protected abstract void solveAll();

	protected void runSpeedTest(URL unsolvedDataFile,
			String bestScoreLimitString) {
		runSpeedTest(unsolvedDataFile, bestScoreLimitString,
				EnvironmentMode.REPRODUCIBLE);
	}

	protected void runSpeedTest(URL unsolvedDataFile,
			String bestScoreLimitString, EnvironmentMode environmentMode) {
		OSGiSolverFactory solverFactory = buildSolverFactory(
				bestScoreLimitString, environmentMode);
		Solver solver = solve(solverFactory, unsolvedDataFile);
		assertBestSolution(solver, bestScoreLimitString);
	}

	protected OSGiSolverFactory buildSolverFactory(String bestScoreLimitString,
			EnvironmentMode environmentMode) {
		OSGiSolverFactory solverFactory = OSGiSolverFactory
				.createFromXmlResource(createSolverConfigResource());
		solverFactory.getSolverConfig().setEnvironmentMode(environmentMode);
		TerminationConfig terminationConfig = new TerminationConfig();
		terminationConfig.setBestScoreLimit(bestScoreLimitString);
		solverFactory.getSolverConfig().setTerminationConfig(terminationConfig);
		return solverFactory;
	}

	private Solver solve(OSGiSolverFactory solverFactory, URL unsolvedDataFile) {
		Solution planningProblem = solutionDao.readSolution(unsolvedDataFile);
		Solver solver = solverFactory.buildSolver();
		solver.solve(planningProblem);
		return solver;
	}

	private void assertBestSolution(Solver solver, String bestScoreLimitString) {
		Solution bestSolution = solver.getBestSolution();
		// assertNotNull(bestSolution);
		Score bestScore = bestSolution.getScore();
		InnerScoreDirectorFactory scoreDirectorFactory = (InnerScoreDirectorFactory) solver
				.getScoreDirectorFactory();
		Score bestScoreLimit = scoreDirectorFactory.getScoreDefinition()
				.parseScore(bestScoreLimitString);
		logger.info("The bestScore (" + bestScore
				+ ") must be at least bestScoreLimit (" + bestScoreLimit);
		// assertTrue(
		// "The bestScore (" + bestScore
		// + ") must be at least bestScoreLimit ("
		// + bestScoreLimit + ").",
		// bestScore.compareTo(bestScoreLimit) >= 0);
	}

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

}


text:
package me.cybulski.public_transport.model;

/**
 * A representation of a vehicle type.
 *
 * @author Michał Cybulski
 */
public enum VehicleType {
    TRAM
}


text: console.log('HELLO USER SCRIPT FROM SUB FOLDER')


text:
Client side web app to calculate live totals from user-entered Cambridge English Exam Scores and convert the totals to grades using the Cambridge English Scale.

Checkout the live site here: http://thepeted.github.io/cambridge-exam-calculator/

This project is not affiliated with Cambridge English.

## Project Status

This build is for testing purposes.

## Technical info

- Its a single page app built with Angular JS and Bootstrap.
- Data for assessment categories and associated data used for validation as a local JSON file.
- As user adds scores, they are added to the client side model and calculated totals are displayed live to the user.

##License

This project is Copyright Peter Daily December 2015 and licensed under the terms of the MIT license.


text:
package nl.fontys.epic.util;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test case for {@see SimpleObserver}
 *
 * @author Miguel Gonzalez <miguel-gonzalez@gmx.de>
 * @since 1.0
 * @version 1.0
 */
public class SimpleObserverTest {

    SimpleObserver<String> observer;

    String first = "Hello";
    String second = "World";
    String third = "!";

    @Before
    public void setUp() {
        observer = new SimpleObserver();
        observer.addListener(first);
        observer.addListener(second);
        observer.addListener(third);
    }

    @Test
    public void testAddListener() {
        int size = observer.getListeners().size();
        assertTrue("Observer size has to be 3 instead of " + size, size == 3);
    }

    @Test
    public void testRemoveListener() {
        observer.removeListener(first);
        int size = observer.getListeners().size();
        assertTrue("Observer size has to be 2 instead of " + size, size == 2);
        observer.removeListener(third);
        size = observer.getListeners().size();
        assertTrue("Observer size has to be 1 instead of " + size, size == 1);
         observer.removeListener(second);
        size = observer.getListeners().size();
        assertTrue("Observer size has to be 0 instead of " + size, size == 0);
    }

    @Test
    public void testHasListener() {
        assertTrue("Listener " + first + " has to be exist", observer.hasListener(first));
        assertTrue("Listener " + second + " has to be exist", observer.hasListener(second));
        assertTrue("Listener " + third + " has to be exist", observer.hasListener(third));
    }

}


text:
package jenkins.model;

import com.google.common.collect.ImmutableList;
import hudson.model.InvisibleAction;
import hudson.model.Run;
import java.util.Collection;
import java.util.List;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;

/**
 * Action added to {@link Run} to record the cause of interruption.
 *
 * @author Kohsuke Kawaguchi
 * @since 1.425
 */
@ExportedBean
public class InterruptedBuildAction extends InvisibleAction {
    private final List<CauseOfInterruption> causes;

    public InterruptedBuildAction(Collection<? extends CauseOfInterruption> causes) {
        this.causes = ImmutableList.<CauseOfInterruption>copyOf(causes);
    }

    @Exported
    public List<CauseOfInterruption> getCauses() {
        return causes;
    }
}


text:
var request = require('request')
    puppies = require('../puppies')

module.exports = {
  canHandle: function(url) {
    var result = (url.lastIndexOf('https://www.reddit.com/', 0) === 0
        || url.lastIndexOf('http://www.reddit.com/', 0) === 0
        || url.lastIndexOf('http://redd.it/', 0) === 0
        || url.lastIndexOf('https://redd.it/', 0) === 0 );

    console.log(result);
    return result;
  },
  handle: function(id, url, callback) {
    request(url + ".json?limit=1", function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var json = JSON.parse(body),
            entry = json[0]['data']['children'][0]['data'],
            permalink = "https://np.reddit.com" + entry['permalink'],
            image = entry['url'],
            title = entry['title'];

        if(image.lastIndexOf('http://imgur.com/', 0) === 0) {
          image = image.replace('http://imgur.com/', 'http://i.imgur.com/') + '.png';
        }
        if(image.lastIndexOf('https://imgur.com/', 0) === 0) {
          image = image.replace('https://imgur.com/', 'https://i.imgur.com/') + '.png';
        }

        puppies.update(id, permalink, image, title);
        callback(permalink, image, title);
      }
    });
  }
}


text:
require 'singleton'

module Serverspec
  module Backend
    class Exec < Base

      def run_command(cmd, opts={})
        cmd = build_command(cmd)
        cmd = add_pre_command(cmd)
        stdout = `#{build_command(cmd)} 2>&1`
        # In ruby 1.9, it is possible to use Open3.capture3, but not in 1.8
        #stdout, stderr, status = Open3.capture3(cmd)

        if @example
          @example.metadata[:command] = cmd
          @example.metadata[:stdout]  = stdout
        end

        { :stdout => stdout, :stderr => nil,
          :exit_status => $?.exitstatus, :exit_signal => nil }
      end

      def build_command(cmd)
        path = Serverspec.configuration.path || RSpec.configuration.path
        if path
          cmd = "env PATH=#{path}:$PATH #{cmd}"
          cmd.gsub!(/(\&\&\s*!?\(?\s*)/, "\\1env PATH=#{path}:$PATH ")
          cmd.gsub!(/(\|\|\s*!?\(?\s*)/, "\\1env PATH=#{path}:$PATH ")
        end
        cmd
      end

      def add_pre_command(cmd)
        path = Serverspec.configuration.path || RSpec.configuration.path
        if Serverspec.configuration.pre_command
          cmd = "#{Serverspec.configuration.pre_command} && #{cmd}"
          cmd = "env PATH=#{path}:$PATH #{cmd}" if path
        end
        cmd
      end

      def check_running(process)
        ret = run_command(commands.check_running(process))
        if ret[:exit_status] == 1 || ret[:stdout] =~ /stopped/
          ret = run_command(commands.check_process(process))
        end
        ret[:exit_status] == 0
      end

      def check_monitored_by_monit(process)
        ret = run_command(commands.check_monitored_by_monit(process))
        return false unless ret[:stdout] != nil && ret[:exit_status] == 0

        retlines = ret[:stdout].split(/[\r\n]+/).map(&:strip)
        proc_index = retlines.index("Process '#{process}'")
        return false unless proc_index

        retlines[proc_index+2].match(/\Amonitoring status\s+monitored\Z/) != nil
      end

      def check_readable(file, by_whom)
        mode = sprintf('%04s',run_command(commands.get_mode(file))[:stdout].strip)
        mode = mode.split('')
        mode_octal = mode[0].to_i * 512 + mode[1].to_i * 64 + mode[2].to_i * 8 + mode[3].to_i * 1
        case by_whom
        when nil
          mode_octal & 0444 != 0
        when 'owner'
          mode_octal & 0400 != 0
        when 'group'
          mode_octal & 0040 != 0
        when 'others'
          mode_octal & 0004 != 0
        end
      end

      def check_writable(file, by_whom)
        mode = sprintf('%04s',run_command(commands.get_mode(file))[:stdout].strip)
        mode = mode.split('')
        mode_octal = mode[0].to_i * 512 + mode[1].to_i * 64 + mode[2].to_i * 8 + mode[3].to_i * 1
        case by_whom
        when nil
          mode_octal & 0222 != 0
        when 'owner'
          mode_octal & 0200 != 0
        when 'group'
          mode_octal & 0020 != 0
        when 'others'
          mode_octal & 0002 != 0
        end
      end

      def check_executable(file, by_whom)
        mode = sprintf('%04s',run_command(commands.get_mode(file))[:stdout].strip)
        mode = mode.split('')
        mode_octal = mode[0].to_i * 512 + mode[1].to_i * 64 + mode[2].to_i * 8 + mode[3].to_i * 1
        case by_whom
        when nil
          mode_octal & 0111 != 0
        when 'owner'
          mode_octal & 0100 != 0
        when 'group'
          mode_octal & 0010 != 0
        when 'others'
          mode_octal & 0001 != 0
        end
      end

      def check_mounted(path, expected_attr, only_with)
        ret = run_command(commands.check_mounted(path))
        if expected_attr.nil? || ret[:exit_status] != 0
          return ret[:exit_status] == 0
        end

        mount = ret[:stdout].scan(/\S+/)
        actual_attr    = { :device => mount[0], :type => mount[4] }
        mount[5].gsub(/\(|\)/, '').split(',').each do |option|
          name, val = option.split('=')
          if val.nil?
            actual_attr[name.to_sym] = true
          else
            val = val.to_i if val.match(/^\d+$/)
            actual_attr[name.to_sym] = val
          end
        end

        if ! expected_attr[:options].nil?
          expected_attr.merge!(expected_attr[:options])
          expected_attr.delete(:options)
        end

        if only_with
          actual_attr == expected_attr
        else
          expected_attr.each do |key, val|
            return false if actual_attr[key] != val
          end
          true
        end
      end

      def check_routing_table(expected_attr)
        return false if ! expected_attr[:destination]
        ret = run_command(commands.check_routing_table(expected_attr[:destination]))
        return false if ret[:exit_status] != 0

        ret[:stdout] =~ /^(\S+)(?: via (\S+))? dev (\S+).+\r\n(?:default via (\S+))?/
        actual_attr = {
          :destination => $1,
          :gateway     => $2 ? $2 : $4,
          :interface   => expected_attr[:interface] ? $3 : nil
        }

        expected_attr.each do |key, val|
          return false if actual_attr[key] != val
        end
        true
      end

      def check_os
        return RSpec.configuration.os if RSpec.configuration.os
        if run_command('ls /etc/redhat-release')[:exit_status] == 0
          'RedHat'
        elsif run_command('ls /etc/system-release')[:exit_status] == 0
          'RedHat' # Amazon Linux
        elsif run_command('ls /etc/debian_version')[:exit_status] == 0
          'Debian'
        elsif run_command('ls /etc/gentoo-release')[:exit_status] == 0
          'Gentoo'
        elsif run_command('uname -s')[:stdout] =~ /AIX/i
           'AIX'
        elsif (os = run_command('uname -sr')[:stdout]) && os =~ /SunOS/i
          if os =~ /5.10/
            'Solaris10'
          elsif run_command('grep -q "Oracle Solaris 11" /etc/release')[:exit_status] == 0
            'Solaris11'
          elsif run_command('grep -q SmartOS /etc/release')[:exit_status] == 0
            'SmartOS'
          else
            'Solaris'
          end
        elsif run_command('uname -s')[:stdout] =~ /Darwin/i
          'Darwin'
        elsif run_command('uname -s')[:stdout] =~ /FreeBSD/i
          'FreeBSD'
        else
          'Base'
        end
      end
    end
  end
end


text:
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
    //var tasksTitle = {todoText:$scope.todoInput, done:false};
    $scope.todoList = [];

    $scope.todoAdd = function() {
        $scope.todoList.push({todoText:$scope.todoInput, done:false});
        $scope.todoInput = "";
    };

    $scope.delete = function() {
        var oldList = $scope.todoList;
        $scope.todoList = [];
        angular.forEach(oldList, function(x) {
            if (!x.done) $scope.todoList.push(x);
        });
    };

});

// angular.module('todoApp', [])
//     .controller('todoController', function($scope) {
//         $scope.tasks = [];
//         $scope.add = function() {
//             $scope.tasks.push($scope.title);
//         }
//         $scope.delete = function() {
//             $scope.tasks.splice(this.$index, 1);
//         }
//     })


text:
<!doctype html>

    <meta charset="UTF-8"/>
    <meta name="viewport"
          content="width=device-width,
           user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}"/>
    <title>Add Car</title>

        <form method="post" th:action="@{/sales/add}" th:object="${sale}">

                Customer:
                <select id="customers" th:field="*{customerName}">
                    <option th:each="customer : ${customers}"
                            th:value="${customer.name}"
                            th:text="${customer.name}"></option>
                </select>

                Car:
                <select id="cars" th:field="*{car}">
                    <option th:each="car : ${cars}"
                            th:value="${car.make} + ' ' + ${car.model}"
                            th:text="${car.make} + ' ' + ${car.model}"></option>
                </select>

                Discount:
                <input id="discount"type="number" th:field="*{discount}">

            <input type="submit" class="btn btn-primary" value="Create">

        </form>


text:
package com.tom_roush.pdfbox.pdmodel.interactive.form;

import android.content.Context;

import androidx.test.platform.app.InstrumentationRegistry;

import java.io.File;
import java.io.IOException;

import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.rendering.TestRendering;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class AcroFormsRotationTest
{

    private static File OUT_DIR;
    private static final String IN_DIR = "pdfbox/com/tom_roush/pdfbox/pdmodel/interactive/form";
    private static final String NAME_OF_PDF = "AcroFormsRotation.pdf";
    private static final String TEST_VALUE = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr,"
        + " sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.";

    private PDDocument document;
    private PDAcroForm acroForm;

    Context testContext;

    @Before
    public void setUp() throws IOException
    {
        testContext = InstrumentationRegistry.getInstrumentation().getContext();
        PDFBoxResourceLoader.init(testContext);

        document = PDDocument.load(testContext.getAssets().open(IN_DIR + "/" + NAME_OF_PDF));
        acroForm = document.getDocumentCatalog().getAcroForm();
        OUT_DIR = new File(testContext.getCacheDir(), "pdfbox-test-output");
        OUT_DIR.mkdirs();
    }

    @Test
    public void fillFields() throws IOException
    {

        // portrait page
        // single line fields
        PDField field = acroForm.getField("pdfbox.portrait.single.rotation0");
        field.setValue(field.getFullyQualifiedName());
        field = acroForm.getField("pdfbox.portrait.single.rotation90");
        field.setValue(field.getFullyQualifiedName());
        field = acroForm.getField("pdfbox.portrait.single.rotation180");
        field.setValue(field.getFullyQualifiedName());
        field = acroForm.getField("pdfbox.portrait.single.rotation270");
        field.setValue(field.getFullyQualifiedName());

        // multiline fields
        field = acroForm.getField("pdfbox.portrait.multi.rotation0");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.portrait.multi.rotation90");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.portrait.multi.rotation180");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.portrait.multi.rotation270");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);

        // 90 degrees rotated page
        // single line fields
        field = acroForm.getField("pdfbox.page90.single.rotation0");
        field.setValue("pdfbox.page90.single.rotation0");
        field = acroForm.getField("pdfbox.page90.single.rotation90");
        field.setValue("pdfbox.page90.single.rotation90");
        field = acroForm.getField("pdfbox.page90.single.rotation180");
        field.setValue("pdfbox.page90.single.rotation180");
        field = acroForm.getField("pdfbox.page90.single.rotation270");
        field.setValue("pdfbox.page90.single.rotation270");

        // multiline fields
        field = acroForm.getField("pdfbox.page90.multi.rotation0");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.page90.multi.rotation90");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.page90.multi.rotation180");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);
        field = acroForm.getField("pdfbox.page90.multi.rotation270");
        field.setValue(field.getFullyQualifiedName() + "\n" + TEST_VALUE);

        // compare rendering
        File file = new File(OUT_DIR, NAME_OF_PDF);
        document.save(file);
        TestRendering testRendering = new TestRendering();
        testRendering.setUp();
        testRendering.render(file);
    }

    @After
    public void tearDown() throws IOException
    {
        document.close();
    }

}


text:
<?php
namespace G4\Tasker;

use G4\Tasker\Model\Domain\Recurring;
use G4\Tasker\Model\Domain\Task as TaskDomain;
use G4\Tasker\Model\Repository\RecurringRepositoryInterface;
use G4\Tasker\Model\Repository\TaskRepositoryInterface;
use G4\Cron\CronExpression;
use G4\ValueObject\Uuid;

class Injector
{

    /**
     * @var array|Recurring[]
     */
    private $data;

    /**
     * @var Identifier
     */
    private $identifier;

    /**
     * @var RecurringRepositoryInterface
     */
    private $recurringRepository;

    /**
     * @var TaskRepositoryInterface
     */
    private $taskRepository;

    /**
     * @param TaskRepositoryInterface $taskRepository
     * @param RecurringRepositoryInterface $recurringRepository
     */
    public function __construct(TaskRepositoryInterface $taskRepository, RecurringRepositoryInterface $recurringRepository)
    {
        $this->taskRepository  = $taskRepository;
        $this->recurringRepository = $recurringRepository;
    }

    public function run()
    {
        if (!$this->isPrimaryHost()) {
            return;
        }

        $this->fetchRecurringTasks();

        if($this->hasData()) {
            $this->saveTasks();
        }
    }

    /**
     * @param string|array $hostname
     * @return Injector
     */
    public function setHostname($hostname)
    {
        $this->identifier = new Identifier($hostname);
        return $this;
    }

    public function isPrimaryHost()
    {
        return gethostname() === $this->identifier->getPrimary();
    }

    private function fetchRecurringTasks()
    {
        $this->data = $this->recurringRepository->getNextTasks();
    }

    private function hasData()
    {
        return count($this->data) > 0;
    }

    private function saveOneTask(Recurring $item)
    {
        $expression = CronExpression::factory($item->getFrequency());
        $ts = strtotime($expression->getNextRunDate()->format('Y-m-d H:i:s'));

        $domain = new TaskDomain(
            $this->identifier->getOne(),
            $item->getTask(),
            $item->getData(),
            $item->getPriority(),
            $ts
        );

        $domain
            ->setRecurringId($item->getRecuId())
            ->setRequestUuid((string) Uuid::generate());

        $this->taskRepository->add($domain);
    }

    private function saveTasks()
    {
        foreach ($this->data as $item) {
            $this->saveOneTask($item);
        }
    }
}


text:
using System;
using System.Linq;
using zserv;
using System.Collections.Generic;

namespace zserv.filesytem
{
	/// <summary>
	/// Class to hold all directives.
	/// </summary>
	public class DirectiveList
	{
		private List<Directive> directives = new List<Directive>();
		private char? prefix = null;

		public DirectiveList (params Directive[] directives)
		{
			foreach (Directive d in directives)
				Add (d);

		}

		public DirectiveList(DirectiveParser presets, string path)
		{
			throw new NotImplementedException ();
		}

		public void Add(Directive d)
		{
			if(IsDirectiveSet(d.name))
				throw new DirectiveAlreadySetException (d.name);

			directives.Add (d);
		}

		public bool IsDirectiveSet(string name)
		{
			return (from dir in directives
					where name == dir.name && dir.enabled
				select dir).Count() > 0;
		}

		public bool IsDirectiveNotSet(string name)
		{
			return !IsDirectiveSet (name);
		}

		/// <summary>
		/// Merges two directory lists (i.e. a parsed one and one of a parent directory).
		/// </summary>
		/// <returns>The merged directory directives.</returns>
		/// <param name="parent">The parent directory.</param>
		/// <param name="child">The subdirectory.</param>
		public static DirectiveList MergeLists(DirectiveList parent, DirectiveList child)
		{
			var merged = new DirectiveList ();

			// take over all child directives
			merged.directives = child.directives;

			// take over all recursive directives from the parent
			(from direc in parent.directives where direc.recursive select direc)
				.each(d => {
					var parentdirec = (from x in child.directives
						where d == x select x).First();

					// if the directive is already set only take it over if it's enforced
					if(parentdirec != null && parentdirec.enforced)
					{
						// remove the directive from the child (remember: == is overridden)
						merged.directives.Remove(parentdirec);

						// and add the parent one
						merged.directives.Add(parentdirec);
					}
					else // if not, just take it over
						merged.Add(d);
				});

			// yey, done :)
			return merged;
		}
	}
}


text:
//
//  PathOverlayRenderer.m
//  Pigeon
//
//  Created by James Bucanek on 12/23/13.
//  Copyright (c) 2013 James Bucanek. See LICENSE.txt.
//

#import "PathOverlayRenderer.h"

#define NO_TEST_LOG
#import "Pigeon.h"
#import "PigeonMath.h"
#import "PathOverlay.h"

@implementation PathOverlayRenderer

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
	// Draw the accuracy area around the return location and a line from the user's current location.

	// Note: This method only uses Core Graphics drawing functions. Use of UIKit is possible,
	//	but there are a number of restrictions, so I just avoid them.

	PathOverlay* overlay = self.overlay;
	if (!MKMapRectIntersectsRect(mapRect,overlay.boundingMapRect))
		return;

	CGPoint linePoints[2];
	linePoints[0] = [self pointForMapPoint:overlay.userMapPoint];
	linePoints[1] = [self pointForMapPoint:overlay.returnMapPoint];
#define fromPoint linePoints[0]
#define toPoint linePoints[1]

	// Create a rectangle the encompasses both points (at opposite corners)
	CGRect boundRect = CGRectStandardize(CGRectMake(fromPoint.x,
													fromPoint.y,
													toPoint.x-fromPoint.x,
													toPoint.y-fromPoint.y));
	CGFloat shortEdge = boundRect.size.height;
	CGFloat longEdge = boundRect.size.width;
	if (shortEdge>longEdge)
		{
		shortEdge = longEdge;
		longEdge = boundRect.size.height;
		}
	if (longEdge<2.0)
		// Nothing to draw, and avoids the edge condition where longEdge==0
		return;
	// Calculate how square the rectangle is, with 0.0 being completely flat
	//	and 1.0 being perfectly square.
	CGFloat squareness = shortEdge/longEdge;
	TESTLog(@"squareness = %f",squareness);
	CGMutablePathRef curveRef = NULL;
	if (squareness>0.125)
		{
		// Calculate the angle from the starting point to the ending point
		double angle = CGATan2(toPoint.y-fromPoint.y,toPoint.x-fromPoint.x);
		// Calculate the midpoint between the starting point and the ending point
		CGPoint midPoint = CenterOfRect(boundRect);
#ifndef NO_TEST_LOG
		// Debugging: draw the center point on the map (green)
		CGRect ctlPoint = CGRectMake(midPoint.x,midPoint.y,100.0,100.0);
		CGContextSetRGBFillColor(context,0.0,1.0,0.0,1.0);
		CGContextFillRect(context,ctlPoint);
#endif
		// Calculate a point, offset from center, perpendicular from the direct line,
		//	the distance relative to the shortest side times the "squareness".
		angle += M_PI_2;		// Rotate left, 90°
		CGFloat offset = shortEdge*squareness*0.667;
		midPoint.x += CGCos(angle)*offset;
		midPoint.y += CGSin(angle)*offset;
#ifndef NO_TEST_LOG
		// Debugging: draw the quadraic control point on the map (purple)
		ctlPoint = CGRectMake(midPoint.x,midPoint.y,100.0,100.0);
		CGContextSetRGBFillColor(context,1.0,0.0,1.0,1.0);
		CGContextFillRect(context,ctlPoint);
#endif
		curveRef = CGPathCreateMutable();
		CGPathMoveToPoint(curveRef,NULL,fromPoint.x,fromPoint.y);
		CGPathAddQuadCurveToPoint(curveRef,NULL,midPoint.x,midPoint.y,toPoint.x,toPoint.y);
		}

	// Draw the line
	CGFloat roadWidth = MKRoadWidthAtZoomScale(zoomScale);
	TESTLog(@"roadWidth=%f",roadWidth);
	CGContextSetLineWidth(context,roadWidth);
	CGContextSetLineCap(context,/*kCGLineCapSquare*/kCGLineCapRound);
	if (_lightPath)
		{
		// Draw a light path (used for satellite views)
		// Fill with a black, 60% transparent, underlay
		CGContextSetRGBStrokeColor(context,0.0,0.0,0.0,0.6);
		if (curveRef!=NULL)
			{
			CGContextAddPath(context,curveRef);
			CGContextStrokePath(context);
			}
		else
			{
			CGContextStrokeLineSegments(context,linePoints,2);
			}
		// Overwrite with a white line
		CGContextSetRGBStrokeColor(context,1.0,1.0,1.0,1.0);
		}
	else
		{
		// Draw a dark path (used for standard map view)
		CGContextSetRGBStrokeColor(context,0.0,0.0,0.0,1.0);
		}
	CGFloat dashes[2] = { roadWidth*2.5, roadWidth*1.5 };
	CGContextSetLineDash(context,0,dashes,2);
	if (curveRef!=NULL)
		{
		CGContextAddPath(context,curveRef);
		CGContextStrokePath(context);
		}
	else
		{
		CGContextStrokeLineSegments(context,linePoints,2);
		}
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?><res:ErrorResponse xmlns:res='http://www.dhl.com' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation= 'http://www.dhl.com err-res.xsd'>
    <Response>
        <ServiceHeader>
            <MessageTime>2013-10-10T03:55:46+01:00</MessageTime>
        </ServiceHeader>
        <Status>
            <ActionStatus>Error</ActionStatus>
            <Condition>
                <ConditionCode>111</ConditionCode>
                <ConditionData>Error in parsing request XML:The element
                    type "req:BookPURequest" must be
                    terminated by the matching end-tag "</req:BookPURequest>".</ConditionData>
            </Condition>
        </Status>
    </Response></res:ErrorResponse>