text:
import unittest
from .support import CatchLogs

from openid.message import Message, OPENID2_NS, OPENID1_NS, OPENID_NS
from openid import association
from openid.consumer.consumer import GenericConsumer, ServerError
from openid.consumer.discover import OpenIDServiceEndpoint, OPENID_2_0_TYPE

class ErrorRaisingConsumer(GenericConsumer):
    """
    A consumer whose _requestAssocation will return predefined results
    instead of trying to actually perform association requests.
    """

    # The list of objects to be returned by successive calls to
    # _requestAssocation.  Each call will pop the first element from
    # this list and return it to _negotiateAssociation.  If the
    # element is a Message object, it will be wrapped in a ServerError
    # exception.  Otherwise it will be returned as-is.
    return_messages = []

    def _requestAssociation(self, endpoint, assoc_type, session_type):
        m = self.return_messages.pop(0)
        if isinstance(m, Message):
            raise ServerError.fromMessage(m)
        else:
            return m

class TestOpenID2SessionNegotiation(unittest.TestCase, CatchLogs):
    """
    Test the session type negotiation behavior of an OpenID 2
    consumer.
    """

    def setUp(self):
        CatchLogs.setUp(self)
        self.consumer = ErrorRaisingConsumer(store=None)

        self.endpoint = OpenIDServiceEndpoint()
        self.endpoint.type_uris = [OPENID_2_0_TYPE]
        self.endpoint.server_url = 'bogus'

    def testBadResponse(self):
        """
        Test the case where the response to an associate request is a
        server error or is otherwise undecipherable.
        """
        self.consumer.return_messages = [
            Message(self.endpoint.preferredNamespace())
        ]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)
        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testEmptyAssocType(self):
        """
        Test the case where the association type (assoc_type) returned
        in an unsupported-type response is absent.
        """
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        # not set: msg.delArg(OPENID_NS, 'assoc_type')
        msg.setArg(OPENID_NS, 'session_type', 'new-session-type')

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Unsupported association type',
            'Server responded with unsupported association ' +
            'session but did not supply a fallback.')

    def testEmptySessionType(self):
        """
        Test the case where the session type (session_type) returned
        in an unsupported-type response is absent.
        """
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'new-assoc-type')
        # not set: msg.setArg(OPENID_NS, 'session_type', None)

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Unsupported association type',
            'Server responded with unsupported association ' +
            'session but did not supply a fallback.')

    def testNotAllowed(self):
        """
        Test the case where an unsupported-type response specifies a
        preferred (assoc_type, session_type) combination that is not
        allowed by the consumer's SessionNegotiator.
        """
        allowed_types = []

        negotiator = association.SessionNegotiator(allowed_types)
        self.consumer.negotiator = negotiator

        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'not-allowed')
        msg.setArg(OPENID_NS, 'session_type', 'not-allowed')

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Unsupported association type',
            'Server sent unsupported session/association type:')

    def testUnsupportedWithRetry(self):
        """
        Test the case where an unsupported-type response triggers a
        retry to get an association with the new preferred type.
        """
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
        msg.setArg(OPENID_NS, 'session_type', 'DH-SHA1')

        assoc = association.Association('handle', 'secret', 'issued', 10000,
                                        'HMAC-SHA1')

        self.consumer.return_messages = [msg, assoc]
        self.assertTrue(
            self.consumer._negotiateAssociation(self.endpoint) is assoc)

        self.failUnlessLogMatches('Unsupported association type')

    def testUnsupportedWithRetryAndFail(self):
        """
        Test the case where an unsupported-typ response triggers a
        retry, but the retry fails and None is returned instead.
        """
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
        msg.setArg(OPENID_NS, 'session_type', 'DH-SHA1')

        self.consumer.return_messages = [
            msg, Message(self.endpoint.preferredNamespace())
        ]

        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches('Unsupported association type',
                                  'Server %s refused' %
                                  (self.endpoint.server_url))

    def testValid(self):
        """
        Test the valid case, wherein an association is returned on the
        first attempt to get one.
        """
        assoc = association.Association('handle', 'secret', 'issued', 10000,
                                        'HMAC-SHA1')

        self.consumer.return_messages = [assoc]
        self.assertTrue(
            self.consumer._negotiateAssociation(self.endpoint) is assoc)
        self.failUnlessLogEmpty()

class TestOpenID1SessionNegotiation(unittest.TestCase, CatchLogs):
    """
    Tests for the OpenID 1 consumer association session behavior.  See
    the docs for TestOpenID2SessionNegotiation.  Notice that this
    class is not a subclass of the OpenID 2 tests.  Instead, it uses
    many of the same inputs but inspects the log messages.
    See the calls to self.failUnlessLogMatches.  Some of
    these tests pass openid2-style messages to the openid 1
    association processing logic to be sure it ignores the extra data.
    """

    def setUp(self):
        CatchLogs.setUp(self)
        self.consumer = ErrorRaisingConsumer(store=None)

        self.endpoint = OpenIDServiceEndpoint()
        self.endpoint.type_uris = [OPENID1_NS]
        self.endpoint.server_url = 'bogus'

    def testBadResponse(self):
        self.consumer.return_messages = [
            Message(self.endpoint.preferredNamespace())
        ]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)
        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testEmptyAssocType(self):
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        # not set: msg.setArg(OPENID_NS, 'assoc_type', None)
        msg.setArg(OPENID_NS, 'session_type', 'new-session-type')

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testEmptySessionType(self):
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'new-assoc-type')
        # not set: msg.setArg(OPENID_NS, 'session_type', None)

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testNotAllowed(self):
        allowed_types = []

        negotiator = association.SessionNegotiator(allowed_types)
        self.consumer.negotiator = negotiator

        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'not-allowed')
        msg.setArg(OPENID_NS, 'session_type', 'not-allowed')

        self.consumer.return_messages = [msg]
        self.assertEqual(
            self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testUnsupportedWithRetry(self):
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
        msg.setArg(OPENID_NS, 'session_type', 'DH-SHA1')

        assoc = association.Association('handle', 'secret', 'issued', 10000,
                                        'HMAC-SHA1')

        self.consumer.return_messages = [msg, assoc]
        self.assertTrue(
            self.consumer._negotiateAssociation(self.endpoint) is None)

        self.failUnlessLogMatches(
            'Server error when requesting an association')

    def testValid(self):
        assoc = association.Association('handle', 'secret', 'issued', 10000,
                                        'HMAC-SHA1')

        self.consumer.return_messages = [assoc]
        self.assertTrue(
            self.consumer._negotiateAssociation(self.endpoint) is assoc)
        self.failUnlessLogEmpty()

class TestNegotiatorBehaviors(unittest.TestCase, CatchLogs):
    def setUp(self):
        self.allowed_types = [
            ('HMAC-SHA1', 'no-encryption'),
            ('HMAC-SHA256', 'no-encryption'),
        ]

        self.n = association.SessionNegotiator(self.allowed_types)

    def testAddAllowedTypeNoSessionTypes(self):
        self.assertRaises(ValueError, self.n.addAllowedType, 'invalid')

    def testAddAllowedTypeBadSessionType(self):
        self.assertRaises(ValueError, self.n.addAllowedType, 'assoc1',
                          'invalid')

    def testAddAllowedTypeContents(self):
        assoc_type = 'HMAC-SHA1'
        self.assertTrue(self.n.addAllowedType(assoc_type) is None)

        for typ in association.getSessionTypes(assoc_type):
            self.assertTrue((assoc_type, typ) in self.n.allowed_types)

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

redpajama_set_name: RedPajamaGithub


text:
require './linear_search'

describe "linear_search test" do
  it "empty array" do
    linear_search([], 1).should eq(-1)
  end

  it "Search for an element in array" do
    linear_search([1,3,4,10,32], 10).should eq(3)
  end
end


text:
"""
If you have more than one version of wxPython installed this module
allows your application to choose which version of wxPython will be
imported when it does 'import wx'.  The main function of this module
is `select` and you use it like this::

    import wxversion
    wxversion.select('2.4')
    import wx

Or additional build options can also be selected, although they will
not be required if they are not installed, like this::

    import wxversion
    wxversion.select('2.5.3-unicode')
    import wx

Or you can require an exact match on the build options like this::

    import wxversion
    wxversion.select('2.5.3-unicode', optionsRequired=True)
    import wx

Finally you can also specify a collection of versions that are allowed
by your application, like this::

    import wxversion
    wxversion.select(['2.5.4', '2.5.5', '2.6'])
    import wx

Of course the default wxPython version can also be controlled by
setting PYTHONPATH or by editing the wx.pth path configuration file,
but using wxversion will allow an application to manage the version
selection itself rather than depend on the user to setup the
environment correctly.

It works by searching the sys.path for directories matching wx-* and
then comparing them to what was passed to the select function.  If a
match is found then that path is inserted into sys.path.

NOTE: If you are making a 'bundle' of your application with a tool
like py2exe then you should *not* use the wxversion module since it
looks at the filesystem for the directories on sys.path, it will fail
in a bundled environment.  Instead you should simply ensure that the
version of wxPython that you want is found by default on the sys.path
when making the bundled version by setting PYTHONPATH.  Then that
version will be included in your bundle and your app will work as
expected.  Py2exe and the others usually have a way to tell at runtime
if they are running from a bundle or running raw, so you can check
that and only use wxversion if needed.  For example, for py2exe::

    if not hasattr(sys, 'frozen'):
        import wxversion
        wxversion.select('2.5')
    import wx

More documentation on wxversion and multi-version installs can be
found at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls

"""

import re, sys, os, glob, fnmatch

_selected = None
class VersionError(Exception):
    pass

class AlreadyImportedError(VersionError):
    pass

#----------------------------------------------------------------------

def select(versions, optionsRequired=False):
    """
    Search for a wxPython installation that matches version.  If one
    is found then sys.path is modified so that version will be
    imported with a 'import wx', otherwise a VersionError exception is
    raised.  This function should only be called once at the beginning
    of the application before wxPython is imported.

        :param versions: Specifies the version to look for, it can
            either be a string or a list of strings.  Each string is
            compared to the installed wxPythons and the best match is
            inserted into the sys.path, allowing an 'import wx' to
            find that version.

            The version string is composed of the dotted version
            number (at least 2 of the 4 components) optionally
            followed by hyphen ('-') separated options (wx port,
            unicode/ansi, flavour, etc.)  A match is determined by how
            much of the installed version matches what is given in the
            version parameter.  If the version number components don't
            match then the score is zero, otherwise the score is
            increased for every specified optional component that is
            specified and that matches.

            Please note, however, that it is possible for a match to
            be selected that doesn't exactly match the versions
            requested.  The only component that is required to be
            matched is the version number.  If you need to require a
            match on the other components as well, then please use the
            optional ``optionsRequired`` parameter described next.

        :param optionsRequired: Allows you to specify that the other
             components of the version string (such as the port name
             or character type) are also required to be present for an
             installed version to be considered a match.  Using this
             parameter allows you to change the selection from a soft,
             as close as possible match to a hard, exact match.

    """
    if type(versions) == str:
        versions = [versions]

    global _selected
    if _selected is not None:
        # A version was previously selected, ensure that it matches
        # this new request
        for ver in versions:
            if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0:
                return
        # otherwise, raise an exception
        raise VersionError("A previously selected wx version does not match the new request.")

    # If we get here then this is the first time wxversion is used,
    # ensure that wxPython hasn't been imported yet.
    if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
        raise AlreadyImportedError("wxversion.select() must be called before wxPython is imported")

    # Look for a matching version and manipulate the sys.path as
    # needed to allow it to be imported.
    installed = _find_installed(True)
    bestMatch = _get_best_match(installed, versions, optionsRequired)

    if bestMatch is None:
        raise VersionError("Requested version of wxPython not found")

    sys.path.insert(0, bestMatch.pathname)
    # q.v. Bug #1409256
    path64 = re.sub('/lib/','/lib64/',bestMatch.pathname)
    if os.path.isdir(path64):
        sys.path.insert(0, path64)
    _selected = bestMatch

#----------------------------------------------------------------------

UPDATE_URL = "http://wxPython.org/"
#UPDATE_URL = "http://sourceforge.net/project/showfiles.php?group_id=10718"

_EM_DEBUG=0

def ensureMinimal(minVersion, optionsRequired=False):
    """
    Checks to see if the default version of wxPython is greater-than
    or equal to `minVersion`.  If not then it will try to find an
    installed version that is >= minVersion.  If none are available
    then a message is displayed that will inform the user and will
    offer to open their web browser to the wxPython downloads page,
    and will then exit the application.
    """
    assert type(minVersion) == str

    # ensure that wxPython hasn't been imported yet.
    if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
        raise AlreadyImportedError("wxversion.ensureMinimal() must be called before wxPython is imported")

    bestMatch = None
    minv = _wxPackageInfo(minVersion)

    # check the default version first
    defaultPath = _find_default()
    if defaultPath:
        defv = _wxPackageInfo(defaultPath, True)
        if defv >= minv and minv.CheckOptions(defv, optionsRequired):
            bestMatch = defv

    # if still no match then check look at all installed versions
    if bestMatch is None:
        installed = _find_installed()
        # The list is in reverse sorted order, so find the first
        # one that is big enough and optionally matches the
        # options
        for inst in installed:
            if inst >= minv and minv.CheckOptions(inst, optionsRequired):
                bestMatch = inst
                break

    # if still no match then prompt the user
    if bestMatch is None:
        if _EM_DEBUG: # We'll do it this way just for the test code below
            raise VersionError("Requested version of wxPython not found")

        import wx, webbrowser
        versions = "\n".join(["      "+ver for ver in getInstalled()])
        app = wx.PySimpleApp()
        result = wx.MessageBox("This application requires a version of wxPython "
                               "greater than or equal to %s, but a matching version "
                               "was not found.\n\n"
                               "You currently have these version(s) installed:\n%s\n\n"
                               "Would you like to download a new version of wxPython?\n"
                               % (minVersion, versions),
                      "wxPython Upgrade Needed", style=wx.YES_NO)
        if result == wx.YES:
            webbrowser.open(UPDATE_URL)
        app.MainLoop()
        sys.exit()

    sys.path.insert(0, bestMatch.pathname)
    # q.v. Bug #1409256
    path64 = re.sub('/lib/','/lib64/',bestMatch.pathname)
    if os.path.isdir(path64):
        sys.path.insert(0, path64)
    global _selected
    _selected = bestMatch

#----------------------------------------------------------------------

def checkInstalled(versions, optionsRequired=False):
    """
    Check if there is a version of wxPython installed that matches one
    of the versions given.  Returns True if so, False if not.  This
    can be used to determine if calling `select` will succeed or not.

        :param versions: Same as in `select`, either a string or a list
            of strings specifying the version(s) to check for.

        :param optionsRequired: Same as in `select`.
    """

    if type(versions) == str:
        versions = [versions]
    installed = _find_installed()
    bestMatch = _get_best_match(installed, versions, optionsRequired)
    return bestMatch is not None

#----------------------------------------------------------------------

def getInstalled():
    """
    Returns a list of strings representing the installed wxPython
    versions that are found on the system.
    """
    installed = _find_installed()
    return [os.path.basename(p.pathname)[3:] for p in installed]

#----------------------------------------------------------------------
# private helpers...

def _get_best_match(installed, versions, optionsRequired):
    bestMatch = None
    bestScore = 0
    for pkg in installed:
        for ver in versions:
            score = pkg.Score(_wxPackageInfo(ver), optionsRequired)
            if score > bestScore:
                bestMatch = pkg
                bestScore = score
    return bestMatch

_pattern = "wx-[0-9].*"
def _find_installed(removeExisting=False):
    installed = []
    toRemove = []
    for pth in sys.path:

        # empty means to look in the current dir
        if not pth:
            pth = '.'

        # skip it if it's not a package dir
        if not os.path.isdir(pth):
            continue

        base = os.path.basename(pth)

        # if it's a wx path that's already in the sys.path then mark
        # it for removal and then skip it
        if fnmatch.fnmatchcase(base, _pattern):
            toRemove.append(pth)
            continue

        # now look in the dir for matching subdirs
        for name in glob.glob(os.path.join(pth, _pattern)):
            # make sure it's a directory
            if not os.path.isdir(name):
                continue
            # and has a wx subdir
            if not os.path.exists(os.path.join(name, 'wx')):
                continue
            installed.append(_wxPackageInfo(name, True))

    if removeExisting:
        for rem in toRemove:
            del sys.path[sys.path.index(rem)]

    installed.sort()
    installed.reverse()
    return installed

# Scan the sys.path looking for either a directory matching _pattern,
# or a wx.pth file
def _find_default():
    for pth in sys.path:
        # empty means to look in the current dir
        if not pth:
            pth = '.'

        # skip it if it's not a package dir
        if not os.path.isdir(pth):
            continue

        # does it match the pattern?
        base = os.path.basename(pth)
        if fnmatch.fnmatchcase(base, _pattern):
            return pth

    for pth in sys.path:
        if not pth:
            pth = '.'
        if not os.path.isdir(pth):
            continue
        if os.path.exists(os.path.join(pth, 'wx.pth')):
            base = open(os.path.join(pth, 'wx.pth')).read()
            return os.path.join(pth, base)

    return None

class _wxPackageInfo(object):
    def __init__(self, pathname, stripFirst=False):
        self.pathname = pathname
        base = os.path.basename(pathname)
        segments = base.split('-')
        if stripFirst:
            segments = segments[1:]
        self.version = tuple([int(x) for x in segments[0].split('.')])
        self.options = segments[1:]

    def Score(self, other, optionsRequired):
        score = 0

        # whatever number of version components given in other must
        # match exactly
        minlen = min(len(self.version), len(other.version))
        if self.version[:minlen] != other.version[:minlen]:
            return 0
        score += 1

        # check for matching options, if optionsRequired then the
        # options are not optional ;-)
        for opt in other.options:
            if opt in self.options:
                score += 1
            elif optionsRequired:
                return 0

        return score

    def CheckOptions(self, other, optionsRequired):
        # if options are not required then this always succeeds
        if not optionsRequired:
            return True
        # otherwise, if we have any option not present in other, then
        # the match fails.
        for opt in self.options:
            if opt not in other.options:
                return False
        return True

    def __lt__(self, other):
        return self.version < other.version or \
               (self.version == other.version and self.options < other.options)
    def __le__(self, other):
        return self.version <= other.version or \
               (self.version == other.version and self.options <= other.options)

    def __gt__(self, other):
        return self.version > other.version or \
               (self.version == other.version and self.options > other.options)
    def __ge__(self, other):
        return self.version >= other.version or \
               (self.version == other.version and self.options >= other.options)

    def __eq__(self, other):
        return self.version == other.version and self.options == other.options

#----------------------------------------------------------------------

if __name__ == '__main__':
    import pprint

    #ensureMinimal('2.5')
    #pprint.pprint(sys.path)
    #sys.exit()

    def test(version, optionsRequired=False):
        # setup
        savepath = sys.path[:]

        #test
        select(version, optionsRequired)
        print "Asked for %s, (%s):\t got: %s" % (version, optionsRequired, sys.path[0])

        # reset
        sys.path = savepath[:]
        global _selected
        _selected = None

    def testEM(version, optionsRequired=False):
        # setup
        savepath = sys.path[:]

        #test
        ensureMinimal(version, optionsRequired)
        print "EM: Asked for %s, (%s):\t got: %s" % (version, optionsRequired, sys.path[0])

        # reset
        sys.path = savepath[:]
        global _selected
        _selected = None

    # make some test dirs
    names = ['wx-2.4-gtk-ansi',
             'wx-2.5.2-gtk2-unicode',
             'wx-2.5.3-gtk-ansi',
             'wx-2.6-gtk2-unicode',
             'wx-2.6-gtk2-ansi',
             'wx-2.6-gtk-ansi',
             'wx-2.7.1-gtk2-ansi',
             ]
    for name in names:
        d = os.path.join('/tmp', name)
        os.mkdir(d)
        os.mkdir(os.path.join(d, 'wx'))

    # setup sys.path to see those dirs
    sys.path.append('/tmp')

    # now run some tests
    pprint.pprint( getInstalled())
    print checkInstalled("2.4")
    print checkInstalled("2.5-unicode")
    print checkInstalled("2.99-bogus")
    print "Current sys.path:"
    pprint.pprint(sys.path)
    print

    test("2.4")
    test("2.5")
    test("2.5-gtk2")
    test("2.5.2")
    test("2.5-ansi")
    test("2.5-unicode")
    test("2.6")
    test("2.6-ansi")
    test(["2.6-unicode", "2.7-unicode"])
    test(["2.6", "2.7"])
    test(["2.6-unicode", "2.7-unicode"], optionsRequired=True)

    # There isn't a unicode match for this one, but it will give the best
    # available 2.4.  Should it give an error instead?  I don't think so...
    test("2.4-unicode")

    # Try asking for multiple versions
    test(["2.5.2", "2.5.3", "2.6"])

    try:
        # expecting an error on this one
        test("2.9")
    except VersionError, e:
        print "Asked for 2.9:\t got Exception:", e

    # check for exception when incompatible versions are requested
    try:
        select("2.4")
        select("2.5")
    except VersionError, e:
        print "Asked for incompatible versions, got Exception:", e

    _EM_DEBUG=1
    testEM("2.6")
    testEM("2.6-unicode")
    testEM("2.6-unicode", True)
    try:
        testEM("2.9")
    except VersionError, e:
        print "EM: Asked for 2.9:\t got Exception:", e

    # cleanup
    for name in names:
        d = os.path.join('/tmp', name)
        os.rmdir(os.path.join(d, 'wx'))
        os.rmdir(d)


text: A tiny program to check whether there are different version of the same NuGet packages installed on the projects of a Visual Studio solution.


text:
class Fl::Framework::Neo4j::Rel::Core::IsOwnerOf
  include Neo4j::ActiveRel

  before_save :_check_rel
  validate :_owned_object

  from_class :any
  to_class   :any
  type 'IS_OWNER_OF'

  # only one IS_OWNER_OF relationship is allowed per object/user
  creates_unique

  private

  def _owned_object
    errors.add(:to_node) unless to_node.respond_to?(:owners) || to_node.respond_to?(:owner)
  end

  def _check_rel
  end
end


text:
package org.opencb.cellbase.app.transform;

import org.junit.Ignore;
import org.junit.Test;
import org.opencb.cellbase.core.serializer.CellBaseJsonFileSerializer;
import org.opencb.cellbase.core.serializer.CellBaseSerializer;

import java.nio.file.Path;
import java.nio.file.Paths;

import static org.junit.Assert.*;

/**
 * Created by imedina on 06/11/15.
 */
public class CaddScoreParserTest {

    // TODO: to finish - properly reimplement
    @Ignore
    @Test
    public void testParse() throws Exception {
        CellBaseSerializer cellBaseSerializer = new CellBaseJsonFileSerializer(Paths.get("/tmp/"), "cadd");

        Path inputPath = Paths.get(getClass().getResource("/cadd_example.txt.gz").toURI());
        CaddScoreParser caddScoreParser = new CaddScoreParser(inputPath, cellBaseSerializer);
        caddScoreParser.parse();

        // Next values are taken from the generated file at /tmp
        // They correspond to first and last scores in the file
        // Both raw and scaled scores ar tested
        long l1 = 2909650398779952672L;
//        long l1 = 246853554624987437L;
        long l2 = 2777354483929861664L;
        long l3 = 1701815202902769664L;
        long l4 = 421650576018505728L;

        float DECIMAL_RESOLUTION = 100f;

        // raw CADD scores tests
        float a = (((short) (l1 >> 48)) / DECIMAL_RESOLUTION) - 10;
        float c = (((short) (l1 >> 32)) / DECIMAL_RESOLUTION) - 10;
        float g = (((short) (l1 >> 16)) / DECIMAL_RESOLUTION) - 10;
        float t = (((short) (l1 >> 0) ) / DECIMAL_RESOLUTION) - 10;

//        assertEquals("Error getting A score value from raw CADD", 0.337f, a, 1 / DECIMAL_RESOLUTION);
//        assertEquals("Error getting C score value from raw CADD", 0.143f, c, 1 / DECIMAL_RESOLUTION);
//        assertEquals("Error getting G score value from raw CADD", 0.202f, g, 1 / DECIMAL_RESOLUTION);
//        assertEquals("Error getting T score value from raw CADD", 10f, t, 1 / DECIMAL_RESOLUTION);

        a = ((short) (l2 >> 48) - 10000) / DECIMAL_RESOLUTION;
        c = ((short) (l2 >> 32) - 10000) / DECIMAL_RESOLUTION;
        g = ((short) (l2 >> 16) - 10000) / DECIMAL_RESOLUTION;
        t = ((short) (l2 >> 0) - 10000) / DECIMAL_RESOLUTION;

        assertEquals("Error getting A score value from raw CADD", -0.133f, a, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting C score value from raw CADD", -0.4797f, c, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting G score value from raw CADD", -0.2772f, g, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting T score value from raw CADD", 10f, t, 1 / DECIMAL_RESOLUTION);

        // scaled CADD scores tests
        a = ((short) (l3 >> 48)) / DECIMAL_RESOLUTION;
        c = ((short) (l3 >> 32)) / DECIMAL_RESOLUTION;
        g = ((short) (l3 >> 16)) / DECIMAL_RESOLUTION;
        t = ((short) (l3 >> 0)) / DECIMAL_RESOLUTION;

        assertEquals("Error getting A score value from scaled CADD", 6.046f, a, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting C score value from scaled CADD", 4.073f, c, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting G score value from scaled CADD", 4.705f, g, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting T score value from scaled CADD", 0f, t, 1 / DECIMAL_RESOLUTION);

        a = ((short) (l4 >> 48)) / DECIMAL_RESOLUTION;
        c = ((short) (l4 >> 32)) / DECIMAL_RESOLUTION;
        g = ((short) (l4 >> 16)) / DECIMAL_RESOLUTION;
        t = ((short) (l4 >> 0)) / DECIMAL_RESOLUTION;

        assertEquals("Error getting A score value from scaled CADD", 1.498f, a, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting C score value from scaled CADD", 0.247f, c, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting G score value from scaled CADD", 0.748f, g, 1 / DECIMAL_RESOLUTION);
        assertEquals("Error getting T score value from scaled CADD", 0f, t, 1 / DECIMAL_RESOLUTION);
    }
}


text:
namespace client {

namespace {

MainMessageLoop* g_main_message_loop = NULL;

}  // namespace

MainMessageLoop::MainMessageLoop() {
  DCHECK(!g_main_message_loop);
  g_main_message_loop = this;
}

MainMessageLoop::~MainMessageLoop() {
  g_main_message_loop = NULL;
}

// static
MainMessageLoop* MainMessageLoop::Get() {
  DCHECK(g_main_message_loop);
  return g_main_message_loop;
}

void MainMessageLoop::PostClosure(const base::Closure& closure) {
  PostTask(CefCreateClosureTask(closure));
}

}  // namespace client


text:
package multasgt

import (
	"net/http"
	"sync"
)

// Tickets represents all collected tickets
type Tickets struct {
	Tickets []Ticket
	M       sync.Mutex
}

func getTickets(wg *sync.WaitGroup,
	plateType, plateNumber string,
	tckts *Tickets,
	checker TicketChecker) {
	defer wg.Done()
	var tickets []Ticket
	tickets, _ = checker.Check(plateType, plateNumber)
	tckts.M.Lock()
	tckts.Tickets = append(tckts.Tickets, tickets...)
	tckts.M.Unlock()
}

// GetAllTickets retrieves tickets from all entities.
func GetAllTickets(plateType, plateNumber string, c *http.Client) ([]Ticket, error) {
	var wg sync.WaitGroup
	wg.Add(7)
	var tickets Tickets
	// Emetra
	go getTickets(&wg, plateType, plateNumber, &tickets, &Emetra{Client: c})
	// Mixco
	go getTickets(&wg, plateType, plateNumber, &tickets, &Emixtra{Client: c})
	// SCP
	go getTickets(&wg, plateType, plateNumber, &tickets, &SCP{Client: c})
	// Fraijanes
	go getTickets(&wg, plateType, plateNumber, &tickets, &Fraijanes{Client: c})
	// Antigua
	go getTickets(&wg, plateType, plateNumber, &tickets, &Antigua{Client: c})
	// PNC
	go getTickets(&wg, plateType, plateNumber, &tickets, &PNC{Client: c})
	// VillaNueva
	go getTickets(&wg, plateType, plateNumber, &tickets, &VillaNueva{Client: c})
	wg.Wait()
	return tickets.Tickets, nil
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using Be.HexEditor.Properties;

namespace Be.HexEditor
{
    public partial class RecentFileHandler : Component
    {
        public class FileMenuItem : ToolStripMenuItem
        {
            string fileName;

            public string FileName
            {
                get { return fileName; }
                set { fileName = value; }
            }

            public FileMenuItem(string fileName)
            {
                this.fileName = fileName;
            }

            public override string Text
            {
                get
                {
                    ToolStripMenuItem parent = (ToolStripMenuItem)this.OwnerItem;
                    int index = parent.DropDownItems.IndexOf(this);
                    return string.Format("{0} {1}", index+1, fileName);
                }
                set
                {
                }
            }
        }

        public const int MaxRecentFiles = 24;

        public RecentFileHandler()
        {
            InitializeComponent();

            Init();
        }

        public RecentFileHandler(IContainer container)
        {
            container.Add(this);

            InitializeComponent();

            Init();
        }

        void Init()
        {
            Settings.Default.PropertyChanged += new PropertyChangedEventHandler(Default_PropertyChanged);
        }

        public void AddFile(string fileName)
        {
            if (this.recentFileToolStripItem == null)
                throw new OperationCanceledException("recentFileToolStripItem can not be null!");

            // check if the file is already in the collection
            int alreadyIn = GetIndexOfRecentFile(fileName);
            if (alreadyIn > 0) // remove it
            {
                Settings.Default.RecentFiles.RemoveAt(alreadyIn);
                if(recentFileToolStripItem.DropDownItems.Count > alreadyIn)
                    recentFileToolStripItem.DropDownItems.RemoveAt(alreadyIn);
            }
            else if (alreadyIn == 0) // it´s the latest file so return
            {
                return;
            }

            // insert the file on top of the list
            Settings.Default.RecentFiles.Insert(0, fileName);
            recentFileToolStripItem.DropDownItems.Insert(0, new FileMenuItem(fileName));

            // remove the last one, if max size is reached
            if (Settings.Default.RecentFiles.Count > MaxRecentFiles)
                Settings.Default.RecentFiles.RemoveAt(MaxRecentFiles);
            if (Settings.Default.RecentFiles.Count > Settings.Default.RecentFilesMax)
                this.recentFileToolStripItem.DropDownItems.RemoveAt(Settings.Default.RecentFilesMax);

            // enable the menu item if it´s disabled
            if (!recentFileToolStripItem.Enabled)
                recentFileToolStripItem.Enabled = true;

            // save the changes
            Settings.Default.Save();
        }

        int GetIndexOfRecentFile(string filename)
        {
            for (int i = 0; i < Settings.Default.RecentFiles.Count; i++)
            {
                string currentFile = Settings.Default.RecentFiles[i];
                if (string.Equals(currentFile, filename, StringComparison.OrdinalIgnoreCase))
                {
                    return i;
                }
            }
            return -1;
        }

        ToolStripMenuItem recentFileToolStripItem;

        public ToolStripMenuItem RecentFileToolStripItem
        {
            get { return recentFileToolStripItem; }
            set
            {
                if (recentFileToolStripItem == value)
                    return;

                recentFileToolStripItem = value;

                ReCreateItems();
            }
        }

        void Default_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "RecentFilesMax")
            {
                ReCreateItems();
            }
        }

        void ReCreateItems()
        {
            if (recentFileToolStripItem == null)
                return;

            if (Settings.Default.RecentFiles == null)
                Settings.Default.RecentFiles = new StringCollection();

            recentFileToolStripItem.DropDownItems.Clear();
            recentFileToolStripItem.Enabled = (Settings.Default.RecentFiles.Count > 0);

            int fileItemCount = Math.Min(Settings.Default.RecentFilesMax, Settings.Default.RecentFiles.Count);
            for(int i = 0; i < fileItemCount; i++)
            {
                string file = Settings.Default.RecentFiles[i];
                recentFileToolStripItem.DropDownItems.Add(new FileMenuItem(file));
            }
        }

        public void Clear()
        {
            Settings.Default.RecentFiles.Clear();
            ReCreateItems();
        }
    }
}


text:
class RoomsController < ApplicationController
  before_action :set_room, only: [:show, :edit, :update, :destroy]
  before_action :set_user

  # GET /users/1/rooms
  # GET /users/1/rooms.json
  def index
    @rooms = @user.rooms
  end

  # GET /users/1/rooms/1
  # GET /users/1/rooms/1.json
  def show
  end

  # GET /users/1/rooms/new
  def new
    @room = Room.new
  end

  # GET /users/1/rooms/1/edit
  def edit
  end

  # POST /users/1/rooms
  # POST /users/1/rooms.json
  def create
    @room = Room.new(room_params)
    @room.user = @user
    respond_to do |format|
      if @room.save
        format.html { redirect_to [@user, @room], notice: 'Room was successfully created.' }
        format.json { render :show, status: :created, location: [@user, @room] }
      else
        format.html { render :new }
        format.json { render json: @room.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1/rooms/1
  # PATCH/PUT /users/1/rooms/1.json
  def update
    respond_to do |format|
      if @room.update(room_params)
        format.html { redirect_to [@user, @room], notice: 'Room was successfully updated.' }
        format.json { render :show, status: :ok, location: [@user, @room] }
      else
        format.html { render :edit }
        format.json { render json: @room.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1/rooms/1
  # DELETE /users/1/rooms/1.json
  def destroy
    unless @room.user == @user
      head :unauthorized
      return
    end
    @room.destroy
    respond_to do |format|
      format.html { redirect_to user_rooms_url [@user], notice: 'Room was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def track
    @room = Room.find(params[:room_id])
    if @room.is_tracked || @room.user != @user
      head :unauthorized
      false
    end
    @room.session = current_session
    respond_to do |format|
      if @room.save
        format.json { head :no_content }
      else
        format.json { head :unprocessable_entity }
      end
    end
  end

  def untrack
    @room = Room.find(params[:room_id])
    unless @room.user == @user
      head :unauthorized
      return
    end
    @room.session = nil
    respond_to do |format|
      if @room.save
        format.json { head :no_content }
      else
        format.json { head :unprocessable_entity }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_room
      @room = Room.find(params[:id])
    end

    def set_user
      @user = User.find(params[:user_id])
      head :unauthorized unless @user == current_session.user || current_session.user.role_id == 1
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def room_params
      params.require(:room).permit(:name,
      :max_winter_temp, :max_summer_temp, :min_winter_temp, :min_summer_temp,
      :max_winter_humidity, :max_summer_humidity, :min_winter_humidity, :min_summer_humidity)
    end
end


text:
namespace ray {

namespace raylet {

using rpc::ErrorType;
using rpc::GcsNodeInfo;
using rpc::HeartbeatTableData;
using rpc::JobTableData;
using rpc::ResourceUsageBatchData;

struct NodeManagerConfig {
  /// The node's resource configuration.
  ResourceRequest resource_config;
  /// The IP address this node manager is running on.
  std::string node_manager_address;
  /// The port to use for listening to incoming connections. If this is 0 then
  /// the node manager will choose its own port.
  int node_manager_port;
  /// The lowest port number that workers started will bind on.
  /// If this is set to 0, workers will bind on random ports.
  int min_worker_port;
  /// The highest port number that workers started will bind on.
  /// If this is not set to 0, min_worker_port must also not be set to 0.
  int max_worker_port;
  /// An explicit list of open ports that workers started will bind
  /// on. This takes precedence over min_worker_port and max_worker_port.
  std::vector<int> worker_ports;
  /// The soft limit of the number of workers.
  int num_workers_soft_limit;
  /// Number of initial Python workers for the first job.
  int num_initial_python_workers_for_first_job;
  /// The maximum number of workers that can be started concurrently by a
  /// worker pool.
  int maximum_startup_concurrency;
  /// The commands used to start the worker process, grouped by language.
  WorkerCommandMap worker_commands;
  /// The native library path which includes the core libraries.
  std::string native_library_path;
  /// The command used to start agent.
  std::string agent_command;
  /// The time between reports resources in milliseconds.
  uint64_t report_resources_period_ms;
  /// The store socket name.
  std::string store_socket_name;
  /// The path to the ray temp dir.
  std::string temp_dir;
  /// The path of this ray log dir.
  std::string log_dir;
  /// The path of this ray session dir.
  std::string session_dir;
  /// The path of this ray resource dir.
  std::string resource_dir;
  /// If true make Ray debugger available externally.
  int ray_debugger_external;
  /// The raylet config list of this node.
  std::string raylet_config;
  // The time between record metrics in milliseconds, or 0 to disable.
  uint64_t record_metrics_period_ms;
  // The number if max io workers.
  int max_io_workers;
  // The minimum object size that can be spilled by each spill operation.
  int64_t min_spilling_size;
};

class HeartbeatSender {
 public:
  /// Create a heartbeat sender.
  ///
  /// \param self_node_id ID of this node.
  /// \param gcs_client GCS client to send heartbeat.
  HeartbeatSender(NodeID self_node_id, std::shared_ptr<gcs::GcsClient> gcs_client);

  ~HeartbeatSender();

 private:
  /// Send heartbeats to the GCS.
  void Heartbeat();

  /// ID of this node.
  NodeID self_node_id_;
  /// A client connection to the GCS.
  std::shared_ptr<gcs::GcsClient> gcs_client_;
  /// The io service used in heartbeat loop in case of it being
  /// blocked by main thread.
  instrumented_io_context heartbeat_io_service_;
  /// Heartbeat thread, using with heartbeat_io_service_.
  std::unique_ptr<std::thread> heartbeat_thread_;
  std::unique_ptr<PeriodicalRunner> heartbeat_runner_;
  /// The time that the last heartbeat was sent at. Used to make sure we are
  /// keeping up with heartbeats.
  uint64_t last_heartbeat_at_ms_;
};

class NodeManager : public rpc::NodeManagerServiceHandler,
                    public syncer::ReporterInterface,
                    public syncer::ReceiverInterface {
 public:
  /// Create a node manager.
  ///
  /// \param resource_config The initial set of node resources.
  /// \param object_manager A reference to the local object manager.
  NodeManager(instrumented_io_context &io_service,
              const NodeID &self_node_id,
              const std::string &self_node_name,
              const NodeManagerConfig &config,
              const ObjectManagerConfig &object_manager_config,
              std::shared_ptr<gcs::GcsClient> gcs_client);

  /// Process a new client connection.
  ///
  /// \param client The client to process.
  /// \return Void.
  void ProcessNewClient(ClientConnection &client);

  /// Process a message from a client. This method is responsible for
  /// explicitly listening for more messages from the client if the client is
  /// still alive.
  ///
  /// \param client The client that sent the message.
  /// \param message_type The message type (e.g., a flatbuffer enum).
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessClientMessage(const std::shared_ptr<ClientConnection> &client,
                            int64_t message_type,
                            const uint8_t *message_data);

  /// Subscribe to the relevant GCS tables and set up handlers.
  ///
  /// \return Status indicating whether this was done successfully or not.
  ray::Status RegisterGcs();

  /// Get initial node manager configuration.
  const NodeManagerConfig &GetInitialConfig() const;

  /// Returns debug string for class.
  ///
  /// \return string.
  std::string DebugString() const;

  /// Record metrics.
  void RecordMetrics();

  /// Report worker OOM kill stats
  void ReportWorkerOOMKillStats();

  /// Get the port of the node manager rpc server.
  int GetServerPort() const { return node_manager_server_.GetPort(); }

  void ConsumeSyncMessage(std::shared_ptr<const syncer::RaySyncMessage> message) override;

  std::optional<syncer::RaySyncMessage> CreateSyncMessage(
      int64_t after_version, syncer::MessageType message_type) const override;

  int GetObjectManagerPort() const { return object_manager_.GetServerPort(); }

  LocalObjectManager &GetLocalObjectManager() { return local_object_manager_; }

  /// Trigger global GC across the cluster to free up references to actors or
  /// object ids.
  void TriggerGlobalGC();

  /// Mark the specified objects as failed with the given error type.
  ///
  /// \param error_type The type of the error that caused this task to fail.
  /// \param object_ids The object ids to store error messages into.
  /// \param job_id The optional job to push errors to if the writes fail.
  void MarkObjectsAsFailed(const ErrorType &error_type,
                           const std::vector<rpc::ObjectReference> object_ids,
                           const JobID &job_id);

  /// Stop this node manager.
  void Stop();

  /// Query all of local core worker states.
  ///
  /// \param on_replied A callback that's called when each of query RPC is replied.
  /// \param send_reply_callback A reply callback that will be called when all
  /// RPCs are replied.
  /// \param include_memory_info If true, it requires every object ref information
  /// from all workers.
  /// \param include_task_info If true, it requires every task metadata information
  /// from all workers.
  /// \param limit A maximum number of task/object entries to return from each core
  /// worker.
  /// \param on_all_replied A callback that's called when every worker replies.
  void QueryAllWorkerStates(
      const std::function<void(const ray::Status &status,
                               const rpc::GetCoreWorkerStatsReply &r)> &on_replied,
      rpc::SendReplyCallback &send_reply_callback,
      bool include_memory_info,
      bool include_task_info,
      int64_t limit,
      const std::function<void()> &on_all_replied);

 private:
  /// Methods for handling nodes.

  /// Handle an unexpected failure notification from GCS pubsub.
  ///
  /// \param data The data of the worker that died.
  void HandleUnexpectedWorkerFailure(const rpc::WorkerDeltaData &data);

  /// Handler for the addition of a new node.
  ///
  /// \param data Data associated with the new node.
  /// \return Void.
  void NodeAdded(const GcsNodeInfo &data);

  /// Handler for the removal of a GCS node.
  /// \param node_id Id of the removed node.
  /// \return Void.
  void NodeRemoved(const NodeID &node_id);

  /// Handler for the addition or updation of a resource in the GCS
  /// \param node_id ID of the node that created or updated resources.
  /// \param createUpdatedResources Created or updated resources.
  /// \return Whether the update is applied.
  bool ResourceCreateUpdated(const NodeID &node_id,
                             const ResourceRequest &createUpdatedResources);

  /// Handler for the deletion of a resource in the GCS
  /// \param node_id ID of the node that deleted resources.
  /// \param resource_names Names of deleted resources.
  /// \return Whether the deletion is applied.
  bool ResourceDeleted(const NodeID &node_id,
                       const std::vector<std::string> &resource_names);

  /// Evaluates the local infeasible queue to check if any tasks can be scheduled.
  /// This is called whenever there's an update to the resources on the local node.
  /// \return Void.
  void TryLocalInfeasibleTaskScheduling();

  /// Fill out the normal task resource report.
  void FillNormalTaskResourceUsage(rpc::ResourcesData &resources_data);

  /// Fill out the resource report. This can be called by either method to transport the
  /// report to GCS.
  void FillResourceReport(rpc::ResourcesData &resources_data);

  /// Write out debug state to a file.
  void DumpDebugState() const;

  /// Flush objects that are out of scope in the application. This will attempt
  /// to eagerly evict all plasma copies of the object from the cluster.
  void FlushObjectsToFree();

  /// Handler for a resource usage notification from the GCS.
  ///
  /// \param id The ID of the node manager that sent the resources data.
  /// \param data The resources data including load information.
  /// \return Whether the node resource usage is updated.
  bool UpdateResourceUsage(const NodeID &id, const rpc::ResourcesData &data);

  /// Handle a worker finishing its assigned task.
  ///
  /// \param worker The worker that finished the task.
  /// \return Whether the worker should be returned to the idle pool. This is
  /// only false for direct actor creation calls, which should never be
  /// returned to idle.
  bool FinishAssignedTask(const std::shared_ptr<WorkerInterface> &worker_ptr);

  /// Handle a worker finishing an assigned actor creation task.
  /// \param worker The worker that finished the task.
  /// \param task The actor task or actor creation task.
  /// \return Void.
  void FinishAssignedActorCreationTask(WorkerInterface &worker, const RayTask &task);

  /// Handle blocking gets of objects. This could be a task assigned to a worker,
  /// an out-of-band task (e.g., a thread created by the application), or a
  /// driver task. This can be triggered when a client starts a get call or a
  /// wait call.
  ///
  /// \param client The client that is executing the blocked task.
  /// \param required_object_refs The objects that the client is blocked waiting for.
  /// \param current_task_id The task that is blocked.
  /// \param ray_get Whether the task is blocked in a `ray.get` call.
  /// \param mark_worker_blocked Whether to mark the worker as blocked. This
  ///                            should be False for direct calls.
  /// \return Void.
  void AsyncResolveObjects(const std::shared_ptr<ClientConnection> &client,
                           const std::vector<rpc::ObjectReference> &required_object_refs,
                           const TaskID &current_task_id,
                           bool ray_get,
                           bool mark_worker_blocked);

  /// Handle end of a blocking object get. This could be a task assigned to a
  /// worker, an out-of-band task (e.g., a thread created by the application),
  /// or a driver task. This can be triggered when a client finishes a get call
  /// or a wait call. The given task must be blocked, via a previous call to
  /// AsyncResolveObjects.
  ///
  /// \param client The client that is executing the unblocked task.
  /// \param current_task_id The task that is unblocked.
  /// \param worker_was_blocked Whether we previously marked the worker as
  ///                           blocked in AsyncResolveObjects().
  /// \return Void.
  void AsyncResolveObjectsFinish(const std::shared_ptr<ClientConnection> &client,
                                 const TaskID &current_task_id,
                                 bool was_blocked);

  /// Handle a direct call task that is blocked. Note that this callback may
  /// arrive after the worker lease has been returned to the node manager.
  ///
  /// \param worker Shared ptr to the worker, or nullptr if lost.
  void HandleDirectCallTaskBlocked(const std::shared_ptr<WorkerInterface> &worker,
                                   bool release_resources);

  /// Handle a direct call task that is unblocked. Note that this callback may
  /// arrive after the worker lease has been returned to the node manager.
  /// However, it is guaranteed to arrive after DirectCallTaskBlocked.
  ///
  /// \param worker Shared ptr to the worker, or nullptr if lost.
  void HandleDirectCallTaskUnblocked(const std::shared_ptr<WorkerInterface> &worker);

  /// Kill a worker.
  ///
  /// \param worker The worker to kill.
  /// \param force true to kill immediately, false to give time for the worker to
  /// clean up and exit gracefully.
  /// \return Void.
  void KillWorker(std::shared_ptr<WorkerInterface> worker, bool force = false);

  /// Destroy a worker.
  /// We will disconnect the worker connection first and then kill the worker.
  ///
  /// \param worker The worker to destroy.
  /// \param disconnect_type The reason why this worker process is disconnected.
  /// \param disconnect_detail The detailed reason for a given exit.
  /// \param force true to destroy immediately, false to give time for the worker to
  /// clean up and exit gracefully.
  /// \return Void.
  void DestroyWorker(std::shared_ptr<WorkerInterface> worker,
                     rpc::WorkerExitType disconnect_type,
                     const std::string &disconnect_detail,
                     bool force = false);

  /// When a job finished, loop over all of the queued tasks for that job and
  /// treat them as failed.
  ///
  /// \param job_id The job that exited.
  /// \return Void.
  void CleanUpTasksForFinishedJob(const JobID &job_id);

  /// Handle an object becoming local. This updates any local accounting, but
  /// does not write to any global accounting in the GCS.
  ///
  /// \param object_info The info about the object that is locally available.
  /// \return Void.
  void HandleObjectLocal(const ObjectInfo &object_info);
  /// Handle an object that is no longer local. This updates any local
  /// accounting, but does not write to any global accounting in the GCS.
  ///
  /// \param object_id The object that has been evicted locally.
  /// \return Void.
  void HandleObjectMissing(const ObjectID &object_id);

  /// Handles the event that a job is started.
  ///
  /// \param job_id ID of the started job.
  /// \param job_data Data associated with the started job.
  /// \return Void
  void HandleJobStarted(const JobID &job_id, const JobTableData &job_data);

  /// Handles the event that a job is finished.
  ///
  /// \param job_id ID of the finished job.
  /// \param job_data Data associated with the finished job.
  /// \return Void.
  void HandleJobFinished(const JobID &job_id, const JobTableData &job_data);

  /// Process client message of NotifyDirectCallTaskBlocked
  ///
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessDirectCallTaskBlocked(const std::shared_ptr<ClientConnection> &client,
                                    const uint8_t *message_data);

  /// Process client message of RegisterClientRequest
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessRegisterClientRequestMessage(
      const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data);

  /// Process client message of AnnounceWorkerPort
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessAnnounceWorkerPortMessage(const std::shared_ptr<ClientConnection> &client,
                                        const uint8_t *message_data);

  /// Handle the case that a worker is available.
  ///
  /// \param client The connection for the worker.
  /// \return Void.
  void HandleWorkerAvailable(const std::shared_ptr<ClientConnection> &client);

  /// Handle the case that a worker is available.
  ///
  /// \param worker The pointer to the worker
  /// \return Void.
  void HandleWorkerAvailable(const std::shared_ptr<WorkerInterface> &worker);

  /// Handle a client that has disconnected. This can be called multiple times
  /// on the same client because this is triggered both when a client
  /// disconnects and when the node manager fails to write a message to the
  /// client.
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessDisconnectClientMessage(const std::shared_ptr<ClientConnection> &client,
                                      const uint8_t *message_data);

  /// Process client message of FetchOrReconstruct
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessFetchOrReconstructMessage(const std::shared_ptr<ClientConnection> &client,
                                        const uint8_t *message_data);

  /// Process client message of WaitRequest
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessWaitRequestMessage(const std::shared_ptr<ClientConnection> &client,
                                 const uint8_t *message_data);

  /// Process client message of WaitForDirectActorCallArgsRequest
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessWaitForDirectActorCallArgsRequestMessage(
      const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data);

  /// Process client message of PushErrorRequest
  ///
  /// \param message_data A pointer to the message data.
  /// \return Void.
  void ProcessPushErrorRequestMessage(const uint8_t *message_data);

  /// Process worker subscribing to a given plasma object become available. This handler
  /// makes sure that the plasma object is local and calls core worker's PlasmaObjectReady
  /// gRPC endpoint.
  ///
  /// \param client The client that sent the message.
  /// \param message_data A pointer to the message data.
  /// \return void.
  void ProcessSubscribePlasmaReady(const std::shared_ptr<ClientConnection> &client,
                                   const uint8_t *message_data);

  void HandleUpdateResourceUsage(rpc::UpdateResourceUsageRequest request,
                                 rpc::UpdateResourceUsageReply *reply,
                                 rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `RequestResourceReport` request.
  void HandleRequestResourceReport(rpc::RequestResourceReportRequest request,
                                   rpc::RequestResourceReportReply *reply,
                                   rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GetResourceLoad` request.
  void HandleGetResourceLoad(rpc::GetResourceLoadRequest request,
                             rpc::GetResourceLoadReply *reply,
                             rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `PrepareBundleResources` request.
  void HandlePrepareBundleResources(rpc::PrepareBundleResourcesRequest request,
                                    rpc::PrepareBundleResourcesReply *reply,
                                    rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `CommitBundleResources` request.
  void HandleCommitBundleResources(rpc::CommitBundleResourcesRequest request,
                                   rpc::CommitBundleResourcesReply *reply,
                                   rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ResourcesReturn` request.
  void HandleCancelResourceReserve(rpc::CancelResourceReserveRequest request,
                                   rpc::CancelResourceReserveReply *reply,
                                   rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `WorkerLease` request.
  void HandleRequestWorkerLease(rpc::RequestWorkerLeaseRequest request,
                                rpc::RequestWorkerLeaseReply *reply,
                                rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ReportWorkerBacklog` request.
  void HandleReportWorkerBacklog(rpc::ReportWorkerBacklogRequest request,
                                 rpc::ReportWorkerBacklogReply *reply,
                                 rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ReturnWorker` request.
  void HandleReturnWorker(rpc::ReturnWorkerRequest request,
                          rpc::ReturnWorkerReply *reply,
                          rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ReleaseUnusedWorkers` request.
  void HandleReleaseUnusedWorkers(rpc::ReleaseUnusedWorkersRequest request,
                                  rpc::ReleaseUnusedWorkersReply *reply,
                                  rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ShutdownRaylet` request.
  void HandleShutdownRaylet(rpc::ShutdownRayletRequest request,
                            rpc::ShutdownRayletReply *reply,
                            rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ReturnWorker` request.
  void HandleCancelWorkerLease(rpc::CancelWorkerLeaseRequest request,
                               rpc::CancelWorkerLeaseReply *reply,
                               rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `PinObjectIDs` request.
  void HandlePinObjectIDs(rpc::PinObjectIDsRequest request,
                          rpc::PinObjectIDsReply *reply,
                          rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `NodeStats` request.
  void HandleGetNodeStats(rpc::GetNodeStatsRequest request,
                          rpc::GetNodeStatsReply *reply,
                          rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GlobalGC` request.
  void HandleGlobalGC(rpc::GlobalGCRequest request,
                      rpc::GlobalGCReply *reply,
                      rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `FormatGlobalMemoryInfo`` request.
  void HandleFormatGlobalMemoryInfo(rpc::FormatGlobalMemoryInfoRequest request,
                                    rpc::FormatGlobalMemoryInfoReply *reply,
                                    rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `RequestObjectSpillage` request.
  void HandleRequestObjectSpillage(rpc::RequestObjectSpillageRequest request,
                                   rpc::RequestObjectSpillageReply *reply,
                                   rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `ReleaseUnusedBundles` request.
  void HandleReleaseUnusedBundles(rpc::ReleaseUnusedBundlesRequest request,
                                  rpc::ReleaseUnusedBundlesReply *reply,
                                  rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GetSystemConfig` request.
  void HandleGetSystemConfig(rpc::GetSystemConfigRequest request,
                             rpc::GetSystemConfigReply *reply,
                             rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GetTasksInfo` request.
  void HandleGetTasksInfo(rpc::GetTasksInfoRequest request,
                          rpc::GetTasksInfoReply *reply,
                          rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GetTaskFailureCause` request.
  void HandleGetTaskFailureCause(rpc::GetTaskFailureCauseRequest request,
                                 rpc::GetTaskFailureCauseReply *reply,
                                 rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `GetObjectsInfo` request.
  void HandleGetObjectsInfo(rpc::GetObjectsInfoRequest request,
                            rpc::GetObjectsInfoReply *reply,
                            rpc::SendReplyCallback send_reply_callback) override;

  /// Handle a `NotifyGCSRestart` request
  void HandleNotifyGCSRestart(rpc::NotifyGCSRestartRequest request,
                              rpc::NotifyGCSRestartReply *reply,
                              rpc::SendReplyCallback send_reply_callback) override;

  /// Trigger local GC on each worker of this raylet.
  void DoLocalGC(bool triggered_by_global_gc = false);

  /// Push an error to the driver if this node is full of actors and so we are
  /// unable to schedule new tasks or actors at all.
  void WarnResourceDeadlock();

  /// Dispatch tasks to available workers.
  void DispatchScheduledTasksToWorkers();

  /// Whether a task is an actor creation task.
  bool IsActorCreationTask(const TaskID &task_id);

  /// Return back all the bundle resource.
  ///
  /// \param bundle_spec: Specification of bundle whose resources will be returned.
  /// \return Whether the resource is returned successfully.
  bool ReturnBundleResources(const BundleSpecification &bundle_spec);

  /// Publish the infeasible task error to GCS so that drivers can subscribe to it and
  /// print.
  ///
  /// \param task RayTask that is infeasible
  void PublishInfeasibleTaskError(const RayTask &task) const;

  /// Get pointers to objects stored in plasma. They will be
  /// released once the returned references go out of scope.
  ///
  /// \param[in] object_ids The objects to get.
  /// \param[out] results The pointers to objects stored in
  /// plasma.
  /// \return Whether the request was successful.
  bool GetObjectsFromPlasma(const std::vector<ObjectID> &object_ids,
                            std::vector<std::unique_ptr<RayObject>> *results);

  /// Populate the relevant parts of the heartbeat table. This is intended for
  /// sending raylet <-> gcs heartbeats. In particular, this should fill in
  /// resource_load and resource_load_by_shape.
  ///
  /// \param Output parameter. `resource_load` and `resource_load_by_shape` are the only
  /// fields used.
  void FillResourceUsage(rpc::ResourcesData &data);

  /// Disconnect a client.
  ///
  /// \param client The client that sent the message.
  /// \param disconnect_type The reason to disconnect the specified client.
  /// \param disconnect_detail Disconnection information in details.
  /// \param client_error_message Extra error messages about this disconnection
  /// \return Void.
  void DisconnectClient(const std::shared_ptr<ClientConnection> &client,
                        rpc::WorkerExitType disconnect_type,
                        const std::string &disconnect_detail,
                        const rpc::RayException *creation_task_exception = nullptr);

  bool TryLocalGC();

  /// Creates the callback used in the memory monitor.
  MemoryUsageRefreshCallback CreateMemoryUsageRefreshCallback();

  /// Creates the detail message for the worker that is killed due to memory running low.
  const std::string CreateOomKillMessageDetails(
      const std::shared_ptr<WorkerInterface> &worker,
      const NodeID &node_id,
      const MemorySnapshot &system_memory,
      float usage_threshold) const;

  /// Creates the suggestion message for the worker that is killed due to memory running
  /// low.
  const std::string CreateOomKillMessageSuggestions(
      const std::shared_ptr<WorkerInterface> &worker) const;

  /// Stores the failure reason for the task. The entry will be cleaned up by a periodic
  /// function post TTL.
  void SetTaskFailureReason(const TaskID &task_id,
                            const rpc::RayErrorInfo &failure_reason);

  /// Checks the expiry time of the task failures and garbage collect them.
  void GCTaskFailureReason();

  /// ID of this node.
  NodeID self_node_id_;
  /// The user-given identifier or name of this node.
  std::string self_node_name_;
  instrumented_io_context &io_service_;
  /// A client connection to the GCS.
  std::shared_ptr<gcs::GcsClient> gcs_client_;
  /// Class to send heartbeat to GCS.
  std::unique_ptr<HeartbeatSender> heartbeat_sender_;
  /// A pool of workers.
  WorkerPool worker_pool_;
  /// The `ClientCallManager` object that is shared by all `NodeManagerClient`s
  /// as well as all `CoreWorkerClient`s.
  rpc::ClientCallManager client_call_manager_;
  /// Pool of RPC client connections to core workers.
  rpc::CoreWorkerClientPool worker_rpc_pool_;
  /// The raylet client to initiate the pubsub to core workers (owners).
  /// It is used to subscribe objects to evict.
  std::unique_ptr<pubsub::SubscriberInterface> core_worker_subscriber_;
  /// The object table. This is shared between the object manager and node
  /// manager.
  std::unique_ptr<IObjectDirectory> object_directory_;
  /// Manages client requests for object transfers and availability.
  ObjectManager object_manager_;
  /// A Plasma object store client. This is used for creating new objects in
  /// the object store (e.g., for actor tasks that can't be run because the
  /// actor died) and to pin objects that are in scope in the cluster.
  plasma::PlasmaClient store_client_;
  /// The runner to run function periodically.
  PeriodicalRunner periodical_runner_;
  /// The period used for the resources report timer.
  uint64_t report_resources_period_ms_;
  /// Incremented each time we encounter a potential resource deadlock condition.
  /// This is reset to zero when the condition is cleared.
  int resource_deadlock_warned_ = 0;
  /// Whether we have recorded any metrics yet.
  bool recorded_metrics_ = false;
  /// The path to the ray temp dir.
  std::string temp_dir_;
  /// Initial node manager configuration.
  const NodeManagerConfig initial_config_;

  /// A manager to resolve objects needed by queued tasks and workers that
  /// called `ray.get` or `ray.wait`.
  DependencyManager dependency_manager_;

  /// A manager for wait requests.
  WaitManager wait_manager_;

  std::shared_ptr<AgentManager> agent_manager_;

  /// The RPC server.
  rpc::GrpcServer node_manager_server_;

  /// The node manager RPC service.
  rpc::NodeManagerGrpcService node_manager_service_;

  /// The agent manager RPC service.
  std::unique_ptr<rpc::AgentManagerServiceHandler> agent_manager_service_handler_;
  rpc::AgentManagerGrpcService agent_manager_service_;

  /// Manages all local objects that are pinned (primary
  /// copies), freed, and/or spilled.
  LocalObjectManager local_object_manager_;

  /// Map from node ids to addresses of the remote node managers.
  absl::flat_hash_map<NodeID, std::pair<std::string, int32_t>>
      remote_node_manager_addresses_;

  /// Map of workers leased out to direct call clients.
  absl::flat_hash_map<WorkerID, std::shared_ptr<WorkerInterface>> leased_workers_;

  /// Optional extra information about why the task failed.
  absl::flat_hash_map<TaskID, ray::TaskFailureEntry> task_failure_reasons_;

  /// Whether to trigger global GC in the next resource usage report. This will broadcast
  /// a global GC message to all raylets except for this one.
  bool should_global_gc_ = false;

  /// Whether to trigger local GC in the next resource usage report. This will trigger gc
  /// on all local workers of this raylet.
  bool should_local_gc_ = false;

  /// When plasma storage usage is high, we'll run gc to reduce it.
  double high_plasma_storage_usage_ = 1.0;

  /// the timestampe local gc run
  uint64_t local_gc_run_time_ns_;

  /// Throttler for local gc
  Throttler local_gc_throttler_;

  /// Throttler for global gc
  Throttler global_gc_throttler_;

  /// Target being evicted or null if no target
  std::shared_ptr<WorkerInterface> high_memory_eviction_target_;

  /// Seconds to initialize a local gc
  const uint64_t local_gc_interval_ns_;

  /// These two classes make up the new scheduler. ClusterResourceScheduler is
  /// responsible for maintaining a view of the cluster state w.r.t resource
  /// usage. ClusterTaskManager is responsible for queuing, spilling back, and
  /// dispatching tasks.
  std::shared_ptr<ClusterResourceScheduler> cluster_resource_scheduler_;
  std::shared_ptr<LocalTaskManager> local_task_manager_;
  std::shared_ptr<ClusterTaskManagerInterface> cluster_task_manager_;

  absl::flat_hash_map<ObjectID, std::unique_ptr<RayObject>> pinned_objects_;

  // TODO(swang): Evict entries from these caches.
  /// Cache for the WorkerTable in the GCS.
  absl::flat_hash_set<WorkerID> failed_workers_cache_;
  /// Cache for the NodeTable in the GCS.
  absl::flat_hash_set<NodeID> failed_nodes_cache_;

  /// Concurrency for the following map
  mutable absl::Mutex plasma_object_notification_lock_;

  /// Keeps track of workers waiting for objects
  absl::flat_hash_map<ObjectID, absl::flat_hash_set<std::shared_ptr<WorkerInterface>>>
      async_plasma_objects_notification_ GUARDED_BY(plasma_object_notification_lock_);

  /// Fields that are used to report metrics.
  /// The period between debug state dumps.
  uint64_t record_metrics_period_ms_;

  /// Last time metrics are recorded.
  uint64_t last_metrics_recorded_at_ms_;

  /// The number of workers killed due to memory above threshold since last report.
  uint64_t number_workers_killed_by_oom_ = 0;

  /// The number of workers killed not by memory above threshold since last report.
  uint64_t number_workers_killed_ = 0;

  /// Number of tasks that are received and scheduled.
  uint64_t metrics_num_task_scheduled_;

  /// Number of tasks that are executed at this node.
  uint64_t metrics_num_task_executed_;

  /// Number of tasks that are spilled back to other nodes.
  uint64_t metrics_num_task_spilled_back_;

  /// Managers all bundle-related operations.
  std::shared_ptr<PlacementGroupResourceManager> placement_group_resource_manager_;

  /// Next resource broadcast seq no. Non-incrementing sequence numbers
  /// indicate network issues (dropped/duplicated/ooo packets, etc).
  int64_t next_resource_seq_no_;

  /// Whether or not if the node draining process has already received.
  bool is_node_drained_ = false;

  /// Ray syncer for synchronization
  syncer::RaySyncer ray_syncer_;

  /// Resource message updated
  absl::flat_hash_map<NodeID, rpc::ResourcesData> resource_message_udpated_;

  /// RaySyncerService for gRPC
  syncer::RaySyncerService ray_syncer_service_;

  /// Monitors and reports node memory usage and whether it is above threshold.
  std::unique_ptr<MemoryMonitor> memory_monitor_;
};

}  // namespace raylet

}  // namespace ray


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/cookies/resources/testharness-helpers.js"></script>
<body>
<script>
function addFrame(url) {
  var i = document.createElement('iframe');
  i.src = url;
  document.body.appendChild(i);
  return i;
}

// Set cookies on ORIGINAL_HOST, then move ourselves to TEST_ROOT so
// we can verify registrable domain and cross-origin behavior.
if (window.location.hostname == "127.0.0.1") {
    window.location.hostname = ORIGINAL_HOST;
} else if (window.location.hostname == ORIGINAL_HOST) {
    clearKnownCookies();
    document.cookie = STRICT_DOM + "=1; SameSite=Strict; Max-Age=100; path=/";
    document.cookie = LAX_DOM + "=1; SameSite=Lax; Max-Age=100; path=/";
    document.cookie = UNSPECIFIED_DOM + "=1; Max-Age=100; path=/";
    // SameSite=None cookies must be Secure.
    document.cookie = NONE_DOM + "=1; SameSite=None; Secure; Max-Age=100; path=/";
    window.location.hostname = TEST_HOST;
} else {
    test(_ => {
        clearKnownCookies();
        assert_equals(document.cookie, "");

        document.cookie = STRICT_DOM + "=2; SameSite=Strict; domain=" + TEST_HOST + "; path=/";
        document.cookie = LAX_DOM + "=2; SameSite=Lax; domain=" + TEST_HOST + "; path=/";
        document.cookie = UNSPECIFIED_DOM + "=2; domain=" + TEST_HOST + "; path=/";
        document.cookie = NONE_DOM + "=2; SameSite=None; Secure; domain=" + TEST_HOST + "; path=/";
        assert_equals(document.cookie, STRICT_DOM + "=2; " + LAX_DOM + "=2; " + UNSPECIFIED_DOM + "=2; " + NONE_DOM + "=2");
    }, "Set cookies for TEST_HOST");

    // Framed
    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], "2", "strict http");
          assert_equals(http_cookies[LAX_DOM], "2", "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], "2", "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "2", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, STRICT_DOM + "=2; " + LAX_DOM + "=2; " + UNSPECIFIED_DOM + "=2; " + NONE_DOM + "=2");

          r();
        };
        frame = addFrame("https://" + TEST_HOST + ":8443/cookies/resources/post-cookies-to-top.php");
      });
    }, "Same-origin frame receives all SameSite cookies.");

    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], undefined, "strict http");
          assert_equals(http_cookies[LAX_DOM], undefined, "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], undefined, "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "1", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, NONE_DOM + "=1");

          r();
        };
        frame = addFrame("https://" + ORIGINAL_HOST + ":8443/cookies/resources/post-cookies-to-top.php");
      });
    }, "Cross-origin frame receives no SameSite cookies.");

    // Nested Frames
    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], "2", "strict http");
          assert_equals(http_cookies[LAX_DOM], "2", "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], "2", "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "2", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, STRICT_DOM + "=2; " + LAX_DOM + "=2; " + UNSPECIFIED_DOM + "=2; " + NONE_DOM + "=2");

          r();
        };
        frame = addFrame(
            "https://" + TEST_HOST + ":8443/cookies/resources/frame.php?url=" +
            encodeURIComponent("https://" + TEST_HOST + ":8443/cookies/resources/post-cookies-to-top.php")
        );
      });
    }, "Same-origin frame nested in same-origin frame receives all SameSite cookies.");

    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], undefined, "strict http");
          assert_equals(http_cookies[LAX_DOM], undefined, "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], undefined, "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "2", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, NONE_DOM + "=2");

          r();
        };
        frame = addFrame(
            "https://" + ORIGINAL_HOST + ":8443/cookies/resources/frame.php?url=" +
            encodeURIComponent("https://" + TEST_HOST + ":8443/cookies/resources/post-cookies-to-top.php")
        );
      });
    }, "Same-origin frame nested in cross-origin frame receives no SameSite cookies.");

    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], undefined, "strict http");
          assert_equals(http_cookies[LAX_DOM], undefined, "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], undefined, "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "1", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, NONE_DOM + "=1");

          r();
        };
        frame = addFrame(
            "https://" + TEST_HOST + ":8443/cookies/resources/frame.php?url=" +
            encodeURIComponent("https://" + ORIGINAL_HOST + ":8443/cookies/resources/post-cookies-to-top.php")
        );
      });
    }, "Cross-origin frame nested in same-origin frame receives no SameSite cookies.");

    promise_test(_ => {
      var frame;
      return new Promise(r => {
        window.onmessage = e => {
          var http_cookies = e.data.http;
          assert_equals(http_cookies[STRICT_DOM], undefined, "strict http");
          assert_equals(http_cookies[LAX_DOM], undefined, "lax http");
          assert_equals(http_cookies[UNSPECIFIED_DOM], undefined, "unspecified http");
          assert_equals(http_cookies[NONE_DOM], "1", "none http");

          var dom_cookies = e.data.document;
          assert_equals(dom_cookies, NONE_DOM + "=1");

          r();
        };
        frame = addFrame(
            "https://" + ORIGINAL_HOST + ":8443/cookies/resources/frame.php?url=" +
            encodeURIComponent("https://" + ORIGINAL_HOST + ":8443/cookies/resources/post-cookies-to-top.php")
        );
      });
    }, "Cross-origin frame nested in cross-origin frame receives no SameSite cookies.");
}
</script>


text:
using System;

namespace TCC2.API
{
    public class ProgressEventArgs : EventArgs
    {
        public const float ProgressUndefined = -1.0f;

        public ProgressEventArgs(long total, long progress)
        {
            Total = total;
            Progress = progress;
        }

        public long Total { get; private set; }
        public long Progress { get; private set; }

        public float Percent
        {
            get
            {
                if (Total <= 0 || Total < Progress)
                    return ProgressUndefined;

                return (float)Progress / (float)Total * 100.0f;
            }
        }
    }
}


text:
package support

// BotInfo contains informations about the bot
type BotInfo struct {
	Ok     bool `json:"ok"`
	Result User `json:"result"`
}


text:
<?php

namespace Serwisant\SerwisantApi\Types\SchemaPublic;

use Serwisant\SerwisantApi;
use Serwisant\SerwisantApi\Types;

class CustomField extends Types\Type
{
  /**
   * @var string
  */
  public $ID;

  /**
   * @var Dictionary
  */
  public $concern;

  /**
   * @var string
  */
  public $description;

  /**
   * @var string
  */
  public $name;

  /**
   * @var bool
  */
  public $required;

  /**
   * @var string[]
  */
  public $selectOptions = [];
  /**
   * @var string
  */
  public $type;

  protected function schemaNamespace()
  {
    return 'SchemaPublic';
  }
}


text: echo "test multipart file"


text:
package com.derf.ei.items.rods;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class EIItemRodSmelting extends EIItemRod {

	public EIItemRodSmelting(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public EnumActionResult onItemUse(ItemStack stack,
			EntityPlayer player, World world,
			BlockPos pos, EnumHand hand,
			EnumFacing facing, float fx,
			float fy, float fz) {

		if(!world.isRemote) {
			ItemStack block = new ItemStack(world.getBlockState(pos).getBlock());

			if(FurnaceRecipes.instance().getSmeltingResult(block) != null) {
				ItemStack temp = FurnaceRecipes.instance().getSmeltingResult(block);
				world.spawnEntityInWorld(new EntityItem(world, pos.getX(), pos.getY(), pos.getZ(), temp.copy()));
				world.setBlockToAir(pos);
			}
		}

		return EnumActionResult.SUCCESS;
	}

}


text:
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(factory());
}(this, (function () { 'use strict';

	for ( let i = 0; i < 10; i += 1 ) console.log( i );
	for ( const letter of array ) console.log( letter );
	for ( const index in array ) console.log( index );

	let i;
	for ( i = 0; i < 10; i += 1 ) console.log( i );

	let letter;
	for ( letter of array ) console.log( letter );

	let index;
	for ( index in array ) console.log( index );

})));


text:
(function(){
  // Pts.namespace( this ); // add Pts into scope if needed

  var demoID = "group_segments";

  // create Space and Form
  var space = new CanvasSpace("#"+demoID).setup({ retina: true, bgcolor: "#e2e6ef", resize: true });
  var form = space.getForm();

  var group = new Group();

  // animation
  space.add({
    start: (bound) => {
      let c = space.center;
      group = new Group( c.$subtract( 20, 0 ), c.clone(), c.$add( 20, 0 ) );
    },

    animate: (time, ftime) => {

      let lastPt = group[group.length-1];

      // record last 50 pointer positions
      if ( !lastPt.equals( space.pointer ) ) {
        group.push( space.pointer.clone() );
        if (group.length > 50 ) group.shift();
      }

      // drawing
      if (group.length >= 3 ) {

        // get segments from the group to generate circle position and size
        let cs = group.segments(2, 5).map(
          (g) => Circle.fromCenter( g[0], Math.min( 50, g[1].$subtract(g[0]).magnitude()) )
        );

        form.strokeOnly("#123", 10, "round");
        form.line( group );
        form.fill("#fff").circles( cs );
        form.fillOnly("#f05").point( lastPt, 10, "circle" );

      }
    }
  });

  // start
  // Note that `playOnce(200)` will stop after 200ms. Use `play()` to run the animation loop continuously.
  space.playOnce(200).bindMouse().bindTouch();

  // For use in demo page only
  if (window.registerDemo) window.registerDemo(demoID, space);

})();


text:
package se.scalablesolutions.skalman

import javax.persistence.{EntityManager, NoResultException}
import java.util.{List => JList}

import javax.ejb.{TransactionAttribute, TransactionAttributeType}

import scala.collection.jcl.Conversions._

import ManagedComponentContext._
import JPA._
import util.Helpers._
import util.HashCode

// Exceptions
class CreateException(msg: String) extends RuntimeException(msg)
class UpdateException(msg: String) extends RuntimeException(msg)
class FindException(msg: String) extends RuntimeException(msg)
class DeleteException(msg: String) extends RuntimeException(msg)
class EntityExistsException(msg: String) extends RuntimeException(msg)

trait GenericRepository[T, PK] {
  val clazz: Class[T]

  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  def create(entity: T): T = {
    try { persist(entity) } catch {
      case e: javax.persistence.EntityExistsException =>
        throw new EntityExistsException(e.getMessage())
    }
    entity
  }

  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  def update(entity: T): T = merge(entity)

  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  def delete(entity: T) = attachAndRemove(entity)

  def find(id: PK): T = withEntityManager { _.find(clazz, id).asInstanceOf[T] }
  def findAll: List[T] = withEntityManager { _.createQuery("from " + clazz.getSimpleName).getResultList.asInstanceOf[JList[T]].toList }
}

/**
 * Defines a ranged of results, to be used with f.e. listings etc.
 */
@serializable
class ResultRange(val first: Int, val limit: Int) {
  def this() = this(0, 0)

  def last = first + limit

  override def hashCode(): Int = {
    var result = HashCode.SEED
    result = HashCode.hash(result, first)
    result = HashCode.hash(result, limit)
    result
  }

  override def equals(that: Any) : Boolean = {
    that != null &&
    that.isInstanceOf[ResultRange] && {
      val other = that.asInstanceOf[ResultRange]
      other.first == first &&
      other.limit == limit
    }
  }
}


text:
[![Build Status](https://secure.travis-ci.org/zendframework/zend-navigation.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-navigation)
[![Coverage Status](https://coveralls.io/repos/github/zendframework/zend-navigation/badge.svg?branch=master)](https://coveralls.io/github/zendframework/zend-navigation?branch=master)

`Zend\Navigation` is a component for managing trees of pointers to web pages.
Simply put: It can be used for creating menus, breadcrumbs, links, and sitemaps,
or serve as a model for other navigation related purposes.

- File issues at https://github.com/zendframework/zend-navigation/issues
- Documentation is at https://docs.zendframework.com/zend-navigation/


text:
<!DOCTYPE html>

  <meta charset=utf-8 />

  <title>Arduino Mega 2560 Example</title>

Arduino Mega 2560 Test Example

Pot value:

Heading:

Button:


text:
package com.querydsl.jpa.domain;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

/**
 * The Class Payment.
 */
@Entity
public class Payment extends Item {
    @ManyToOne
    Status currentStatus, status;

    @Enumerated
    PaymentStatus paymentStatus;

    @OneToMany
    Collection<StatusChange> statusChanges;
}