text:
import tempfile
import os
import sys
import re
import errno
import warnings

import unittest
from test import test_support

warnings.filterwarnings("ignore",
                        category=RuntimeWarning,
                        message="mktemp", module=__name__)

if hasattr(os, 'stat'):
    import stat
    has_stat = 1
else:
    has_stat = 0

has_textmode = (tempfile._text_openflags != tempfile._bin_openflags)
has_spawnl = hasattr(os, 'spawnl')

# TEST_FILES may need to be tweaked for systems depending on the maximum
# number of files that can be opened at one time (see ulimit -n)
if sys.platform == 'mac':
    TEST_FILES = 32
elif sys.platform == 'openbsd3':
    TEST_FILES = 48
else:
    TEST_FILES = 100

# This is organized as one test for each chunk of code in tempfile.py,
# in order of their appearance in the file.  Testing which requires
# threads is not done here.

# Common functionality.
class TC(unittest.TestCase):

    str_check = re.compile(r"[a-zA-Z0-9_-]{6}$")

    def failOnException(self, what, ei=None):
        if ei is None:
            ei = sys.exc_info()
        self.fail("%s raised %s: %s" % (what, ei[0], ei[1]))

    def nameCheck(self, name, dir, pre, suf):
        (ndir, nbase) = os.path.split(name)
        npre  = nbase[:len(pre)]
        nsuf  = nbase[len(nbase)-len(suf):]

        # check for equality of the absolute paths!
        self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir),
                         "file '%s' not in directory '%s'" % (name, dir))
        self.assertEqual(npre, pre,
                         "file '%s' does not begin with '%s'" % (nbase, pre))
        self.assertEqual(nsuf, suf,
                         "file '%s' does not end with '%s'" % (nbase, suf))

        nbase = nbase[len(pre):len(nbase)-len(suf)]
        self.assert_(self.str_check.match(nbase),
                     "random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/"
                     % nbase)

test_classes = []

class test_exports(TC):
    def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.failUnless(len(unexp) == 0,
                        "unexpected keys: %s" % unexp)

test_classes.append(test_exports)

class test__RandomNameSequence(TC):
    """Test the internal iterator object _RandomNameSequence."""

    def setUp(self):
        self.r = tempfile._RandomNameSequence()

    def test_get_six_char_str(self):
        # _RandomNameSequence returns a six-character string
        s = self.r.next()
        self.nameCheck(s, '', '', '')

    def test_many(self):
        # _RandomNameSequence returns no duplicate strings (stochastic)

        dict = {}
        r = self.r
        for i in xrange(TEST_FILES):
            s = r.next()
            self.nameCheck(s, '', '', '')
            self.failIf(s in dict)
            dict[s] = 1

    def test_supports_iter(self):
        # _RandomNameSequence supports the iterator protocol

        i = 0
        r = self.r
        try:
            for s in r:
                i += 1
                if i == 20:
                    break
        except:
            failOnException("iteration")

test_classes.append(test__RandomNameSequence)

class test__candidate_tempdir_list(TC):
    """Test the internal function _candidate_tempdir_list."""

    def test_nonempty_list(self):
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.failIf(len(cand) == 0)
        for c in cand:
            self.assert_(isinstance(c, basestring),
                         "%s is not a string" % c)

    def test_wanted_dirs(self):
        # _candidate_tempdir_list contains the expected directories

        # Make sure the interesting environment variables are all set.
        added = []
        try:
            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname:
                    os.environ[envname] = os.path.abspath(envname)
                    added.append(envname)

            cand = tempfile._candidate_tempdir_list()

            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname: raise ValueError
                self.assert_(dirname in cand)

            try:
                dirname = os.getcwd()
            except (AttributeError, os.error):
                dirname = os.curdir

            self.assert_(dirname in cand)

            # Not practical to try to verify the presence of OS-specific
            # paths in this list.
        finally:
            for p in added:
                del os.environ[p]

test_classes.append(test__candidate_tempdir_list)

# We test _get_default_tempdir by testing gettempdir.

class test__get_candidate_names(TC):
    """Test the internal function _get_candidate_names."""

    def test_retval(self):
        # _get_candidate_names returns a _RandomNameSequence object
        obj = tempfile._get_candidate_names()
        self.assert_(isinstance(obj, tempfile._RandomNameSequence))

    def test_same_thing(self):
        # _get_candidate_names always returns the same object
        a = tempfile._get_candidate_names()
        b = tempfile._get_candidate_names()

        self.assert_(a is b)

test_classes.append(test__get_candidate_names)

class test__mkstemp_inner(TC):
    """Test the internal function _mkstemp_inner."""

    class mkstemped:
        _bflags = tempfile._bin_openflags
        _tflags = tempfile._text_openflags
        _close = os.close
        _unlink = os.unlink

        def __init__(self, dir, pre, suf, bin):
            if bin: flags = self._bflags
            else:   flags = self._tflags

            (self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags)

        def write(self, str):
            os.write(self.fd, str)

        def __del__(self):
            self._close(self.fd)
            self._unlink(self.name)

    def do_create(self, dir=None, pre="", suf="", bin=1):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            file = self.mkstemped(dir, pre, suf, bin)
        except:
            self.failOnException("_mkstemp_inner")

        self.nameCheck(file.name, dir, pre, suf)
        return file

    def test_basic(self):
        # _mkstemp_inner can create files
        self.do_create().write("blat")
        self.do_create(pre="a").write("blat")
        self.do_create(suf="b").write("blat")
        self.do_create(pre="a", suf="b").write("blat")
        self.do_create(pre="aa", suf=".txt").write("blat")

    def test_basic_many(self):
        # _mkstemp_inner can create many files (stochastic)
        extant = range(TEST_FILES)
        for i in extant:
            extant[i] = self.do_create(pre="aa")

    def test_choose_directory(self):
        # _mkstemp_inner can create files in a user-selected directory
        dir = tempfile.mkdtemp()
        try:
            self.do_create(dir=dir).write("blat")
        finally:
            os.rmdir(dir)

    def test_file_mode(self):
        # _mkstemp_inner creates files with the proper mode
        if not has_stat:
            return            # ugh, can't use TestSkipped.

        file = self.do_create()
        mode = stat.S_IMODE(os.stat(file.name).st_mode)
        expected = 0600
        if sys.platform in ('win32', 'os2emx', 'mac'):
            # There's no distinction among 'user', 'group' and 'world';
            # replicate the 'user' bits.
            user = expected >> 6
            expected = user * (1 + 8 + 64)
        self.assertEqual(mode, expected)

    def test_noinherit(self):
        # _mkstemp_inner file handles are not inherited by child processes
        if not has_spawnl:
            return            # ugh, can't use TestSkipped.

        if test_support.verbose:
            v="v"
        else:
            v="q"

        file = self.do_create()
        fd = "%d" % file.fd

        try:
            me = __file__
        except NameError:
            me = sys.argv[0]

        # We have to exec something, so that FD_CLOEXEC will take
        # effect.  The core of this test is therefore in
        # tf_inherit_check.py, which see.
        tester = os.path.join(os.path.dirname(os.path.abspath(me)),
                              "tf_inherit_check.py")

        # On Windows a spawn* /path/ with embedded spaces shouldn't be quoted,
        # but an arg with embedded spaces should be decorated with double
        # quotes on each end
        if sys.platform in ('win32'):
            decorated = '"%s"' % sys.executable
            tester = '"%s"' % tester
        else:
            decorated = sys.executable

        retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd)
        self.failIf(retval < 0,
                    "child process caught fatal signal %d" % -retval)
        self.failIf(retval > 0, "child process reports failure")

    def test_textmode(self):
        # _mkstemp_inner can create files in text mode
        if not has_textmode:
            return            # ugh, can't use TestSkipped.

        self.do_create(bin=0).write("blat\n")
        # XXX should test that the file really is a text file

test_classes.append(test__mkstemp_inner)

class test_gettempprefix(TC):
    """Test gettempprefix()."""

    def test_sane_template(self):
        # gettempprefix returns a nonempty prefix string
        p = tempfile.gettempprefix()

        self.assert_(isinstance(p, basestring))
        self.assert_(len(p) > 0)

    def test_usable_template(self):
        # gettempprefix returns a usable prefix string

        # Create a temp directory, avoiding use of the prefix.
        # Then attempt to create a file whose name is
        # prefix + 'xxxxxx.xxx' in that directory.
        p = tempfile.gettempprefix() + "xxxxxx.xxx"
        d = tempfile.mkdtemp(prefix="")
        try:
            p = os.path.join(d, p)
            try:
                fd = os.open(p, os.O_RDWR | os.O_CREAT)
            except:
                self.failOnException("os.open")
            os.close(fd)
            os.unlink(p)
        finally:
            os.rmdir(d)

test_classes.append(test_gettempprefix)

class test_gettempdir(TC):
    """Test gettempdir()."""

    def test_directory_exists(self):
        # gettempdir returns a directory which exists

        dir = tempfile.gettempdir()
        self.assert_(os.path.isabs(dir) or dir == os.curdir,
                     "%s is not an absolute path" % dir)
        self.assert_(os.path.isdir(dir),
                     "%s is not a directory" % dir)

    def test_directory_writable(self):
        # gettempdir returns a directory writable by the user

        # sneaky: just instantiate a NamedTemporaryFile, which
        # defaults to writing into the directory returned by
        # gettempdir.
        try:
            file = tempfile.NamedTemporaryFile()
            file.write("blat")
            file.close()
        except:
            self.failOnException("create file in %s" % tempfile.gettempdir())

    def test_same_thing(self):
        # gettempdir always returns the same object
        a = tempfile.gettempdir()
        b = tempfile.gettempdir()

        self.assert_(a is b)

test_classes.append(test_gettempdir)

class test_mkstemp(TC):
    """Test mkstemp()."""

    def do_create(self, dir=None, pre="", suf="", ):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
            (ndir, nbase) = os.path.split(name)
            adir = os.path.abspath(dir)
            self.assertEqual(adir, ndir,
                "Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
        except:
            self.failOnException("mkstemp")

        try:
            self.nameCheck(name, dir, pre, suf)
        finally:
            os.close(fd)
            os.unlink(name)

    def test_basic(self):
        # mkstemp can create files
        self.do_create()
        self.do_create(pre="a")
        self.do_create(suf="b")
        self.do_create(pre="a", suf="b")
        self.do_create(pre="aa", suf=".txt")
        self.do_create(dir=".")

    def test_choose_directory(self):
        # mkstemp can create directories in a user-selected directory
        dir = tempfile.mkdtemp()
        try:
            self.do_create(dir=dir)
        finally:
            os.rmdir(dir)

test_classes.append(test_mkstemp)

class test_mkdtemp(TC):
    """Test mkdtemp()."""

    def do_create(self, dir=None, pre="", suf=""):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
        except:
            self.failOnException("mkdtemp")

        try:
            self.nameCheck(name, dir, pre, suf)
            return name
        except:
            os.rmdir(name)
            raise

    def test_basic(self):
        # mkdtemp can create directories
        os.rmdir(self.do_create())
        os.rmdir(self.do_create(pre="a"))
        os.rmdir(self.do_create(suf="b"))
        os.rmdir(self.do_create(pre="a", suf="b"))
        os.rmdir(self.do_create(pre="aa", suf=".txt"))

    def test_basic_many(self):
        # mkdtemp can create many directories (stochastic)
        extant = range(TEST_FILES)
        try:
            for i in extant:
                extant[i] = self.do_create(pre="aa")
        finally:
            for i in extant:
                if(isinstance(i, basestring)):
                    os.rmdir(i)

    def test_choose_directory(self):
        # mkdtemp can create directories in a user-selected directory
        dir = tempfile.mkdtemp()
        try:
            os.rmdir(self.do_create(dir=dir))
        finally:
            os.rmdir(dir)

    def test_mode(self):
        # mkdtemp creates directories with the proper mode
        if not has_stat:
            return            # ugh, can't use TestSkipped.

        dir = self.do_create()
        try:
            mode = stat.S_IMODE(os.stat(dir).st_mode)
            mode &= 0777 # Mask off sticky bits inherited from /tmp
            expected = 0700
            if sys.platform in ('win32', 'os2emx', 'mac'):
                # There's no distinction among 'user', 'group' and 'world';
                # replicate the 'user' bits.
                user = expected >> 6
                expected = user * (1 + 8 + 64)
            self.assertEqual(mode, expected)
        finally:
            os.rmdir(dir)

test_classes.append(test_mkdtemp)

class test_mktemp(TC):
    """Test mktemp()."""

    # For safety, all use of mktemp must occur in a private directory.
    # We must also suppress the RuntimeWarning it generates.
    def setUp(self):
        self.dir = tempfile.mkdtemp()

    def tearDown(self):
        if self.dir:
            os.rmdir(self.dir)
            self.dir = None

    class mktemped:
        _unlink = os.unlink
        _bflags = tempfile._bin_openflags

        def __init__(self, dir, pre, suf):
            self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
            # Create the file.  This will raise an exception if it's
            # mysteriously appeared in the meanwhile.
            os.close(os.open(self.name, self._bflags, 0600))

        def __del__(self):
            self._unlink(self.name)

    def do_create(self, pre="", suf=""):
        try:
            file = self.mktemped(self.dir, pre, suf)
        except:
            self.failOnException("mktemp")

        self.nameCheck(file.name, self.dir, pre, suf)
        return file

    def test_basic(self):
        # mktemp can choose usable file names
        self.do_create()
        self.do_create(pre="a")
        self.do_create(suf="b")
        self.do_create(pre="a", suf="b")
        self.do_create(pre="aa", suf=".txt")

    def test_many(self):
        # mktemp can choose many usable file names (stochastic)
        extant = range(TEST_FILES)
        for i in extant:
            extant[i] = self.do_create(pre="aa")

##     def test_warning(self):
##         # mktemp issues a warning when used
##         warnings.filterwarnings("error",
##                                 category=RuntimeWarning,
##                                 message="mktemp")
##         self.assertRaises(RuntimeWarning,
##                           tempfile.mktemp, dir=self.dir)

test_classes.append(test_mktemp)

# We test _TemporaryFileWrapper by testing NamedTemporaryFile.

class test_NamedTemporaryFile(TC):
    """Test NamedTemporaryFile()."""

    def do_create(self, dir=None, pre="", suf=""):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf)
        except:
            self.failOnException("NamedTemporaryFile")

        self.nameCheck(file.name, dir, pre, suf)
        return file

    def test_basic(self):
        # NamedTemporaryFile can create files
        self.do_create()
        self.do_create(pre="a")
        self.do_create(suf="b")
        self.do_create(pre="a", suf="b")
        self.do_create(pre="aa", suf=".txt")

    def test_creates_named(self):
        # NamedTemporaryFile creates files with names
        f = tempfile.NamedTemporaryFile()
        self.failUnless(os.path.exists(f.name),
                        "NamedTemporaryFile %s does not exist" % f.name)

    def test_del_on_close(self):
        # A NamedTemporaryFile is deleted when closed
        dir = tempfile.mkdtemp()
        try:
            f = tempfile.NamedTemporaryFile(dir=dir)
            f.write('blat')
            f.close()
            self.failIf(os.path.exists(f.name),
                        "NamedTemporaryFile %s exists after close" % f.name)
        finally:
            os.rmdir(dir)

    def test_multiple_close(self):
        # A NamedTemporaryFile can be closed many times without error

        f = tempfile.NamedTemporaryFile()
        f.write('abc\n')
        f.close()
        try:
            f.close()
            f.close()
        except:
            self.failOnException("close")

    # How to test the mode and bufsize parameters?

test_classes.append(test_NamedTemporaryFile)

class test_TemporaryFile(TC):
    """Test TemporaryFile()."""

    def test_basic(self):
        # TemporaryFile can create files
        # No point in testing the name params - the file has no name.
        try:
            tempfile.TemporaryFile()
        except:
            self.failOnException("TemporaryFile")

    def test_has_no_name(self):
        # TemporaryFile creates files with no names (on this system)
        dir = tempfile.mkdtemp()
        f = tempfile.TemporaryFile(dir=dir)
        f.write('blat')

        # Sneaky: because this file has no name, it should not prevent
        # us from removing the directory it was created in.
        try:
            os.rmdir(dir)
        except:
            ei = sys.exc_info()
            # cleanup
            f.close()
            os.rmdir(dir)
            self.failOnException("rmdir", ei)

    def test_multiple_close(self):
        # A TemporaryFile can be closed many times without error
        f = tempfile.TemporaryFile()
        f.write('abc\n')
        f.close()
        try:
            f.close()
            f.close()
        except:
            self.failOnException("close")

    # How to test the mode and bufsize parameters?

if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
    test_classes.append(test_TemporaryFile)

def test_main():
    test_support.run_unittest(*test_classes)

if __name__ == "__main__":
    test_main()


text:
/**
 * A mixin for groups of Focusable things (Components, Widgets, etc) that
 * should respond to arrow keys to navigate among the peers, but keep only
 * one of the peers focusable by default (tabIndex=0)
 *
 * Some examples: Toolbars, Radio groups, Tab bars
 */

Ext.define('Ext.util.FocusableContainer', {
    extend: 'Ext.Mixin',

    requires: [
        'Ext.util.KeyNav'
    ],

    mixinConfig: {
        id: 'focusablecontainer',

        before: {
            onAdd: 'onFocusableChildAdd',
            onRemove: 'onFocusableChildRemove',
            destroy: 'destroyFocusableContainer',
            onFocusEnter: 'onFocusEnter'
        },

        after: {
            afterRender: 'initFocusableContainer',
            onFocusLeave: 'onFocusLeave'
        }
    },

    isFocusableContainer: true,

    /**
     * @cfg {Boolean} [enableFocusableContainer=true] Enable or disable
     * navigation with arrow keys for this FocusableContainer. This option may
     * be useful with nested FocusableContainers such as Grid column headers,
     * when only the root container should handle keyboard events.
     */
    enableFocusableContainer: true,

    /**
     * @cfg {Number} [activeChildTabIndex=0] DOM tabIndex attribute to set on the
     * active Focusable child of this container when using the "Roaming tabindex"
     * technique. Set this value to > 0 to precisely control the tabbing order
     * of the components/containers on the page.
     */
    activeChildTabIndex: 0,

    /**
     * @cfg {Number} [inactiveChildTabIndex=-1] DOM tabIndex attribute to set on
     * inactive Focusable children of this container when using the "Roaming tabindex"
     * technique. This value rarely needs to be changed from its default.
     */
    inactiveChildTabIndex: -1,

    privates: {
        initFocusableContainer: function() {
            // Allow nested containers to optionally disable
            // children containers' behavior
            if (this.enableFocusableContainer) {
                this.doInitFocusableContainer();
            }
        },

        doInitFocusableContainer: function() {
            var me = this,
                el;

            el = me.getFocusableContainerEl();

            // We set tabIndex on the focusable container el so that the user
            // could tab into it; we catch its focus event and focus a child instead
            me.activateFocusableContainerEl(el);

            me.mon(el, 'mousedown', me.onFocusableContainerMousedown, me);

            me.focusableKeyNav = me.createFocusableContainerKeyNav(el);
        },

        createFocusableContainerKeyNav: function(el) {
            var me = this;

            return new Ext.util.KeyNav(el, {
                ignoreInputFields: true,
                scope: me,

                tab: me.onFocusableContainerTabKey,
                enter: me.onFocusableContainerEnterKey,
                space: me.onFocusableContainerSpaceKey,
                up: me.onFocusableContainerUpKey,
                down: me.onFocusableContainerDownKey,
                left: me.onFocusableContainerLeftKey,
                right: me.onFocusableContainerRightKey
            });
        },

        destroyFocusableContainer: function() {
            if (this.enableFocusableContainer) {
                this.doDestroyFocusableContainer();
            }
        },

        doDestroyFocusableContainer: function() {
            var keyNav = this.focusableKeyNav;

            if (keyNav) {
                keyNav.destroy();
                delete this.focusableKeyNav;
            }
        },

        // Default FocusableContainer implies a flat list of focusable children
        getFocusables: function() {
            return this.items.items;
        },

        initDefaultFocusable: function(beforeRender) {
            var me = this,
                activeIndex = me.activeChildTabIndex,
                haveFocusable = false,
                items, item, i, len, tabIdx;

            items = me.getFocusables();
            len   = items.length;

            if (!len) {
                return;
            }

            // Check if any child Focusable is already active.
            // Note that we're not determining *which* focusable child
            // to focus here, only that we have some focusables.
            for (i = 0; i < len; i++) {
                item = items[i];

                if (item.focusable) {
                    haveFocusable = true;
                    tabIdx = item.getTabIndex();

                    if (tabIdx != null && tabIdx >= activeIndex) {
                        return item;
                    }
                }
            }

            // No interactive children found, no point in going further
            if (!haveFocusable) {
                return;
            }

            // No child is focusable by default, so the first *interactive*
            // one gets initial childTabIndex. We are not looking for a focusable
            // child here because it may not be focusable yet if this happens
            // before rendering; we assume that an interactive child will become
            // focusable later and now activateFocusable() will just assign it
            // the respective tabIndex.
            item = me.findNextFocusableChild(null, true, items, beforeRender);

            if (item) {
                me.activateFocusable(item);
            }

            return item;
        },

        clearFocusables: function() {
            var me = this,
                items = me.getFocusables(),
                len = items.length,
                item, i;

            for (i = 0; i < len; i++) {
                item = items[i];

                if (item.focusable) {
                    me.deactivateFocusable(item);
                }
            }
        },

        activateFocusable: function(child, /* optional */ newTabIndex) {
            var activeIndex = newTabIndex != null ? newTabIndex : this.activeChildTabIndex;

            child.setTabIndex(activeIndex);
        },

        deactivateFocusable: function(child, /* optional */ newTabIndex) {
            var inactiveIndex = newTabIndex != null ? newTabIndex : this.inactiveChildTabIndex;

            child.setTabIndex(inactiveIndex);
        },

        onFocusableContainerTabKey: function() {
            return true;
        },

        onFocusableContainerEnterKey: function() {
            return true;
        },

        onFocusableContainerSpaceKey: function() {
            return true;
        },

        onFocusableContainerUpKey: function(e) {
            return this.moveChildFocus(e, false);
        },

        onFocusableContainerLeftKey: function(e) {
            return this.moveChildFocus(e, false);
        },

        onFocusableContainerRightKey: function(e) {
            return this.moveChildFocus(e, true);
        },

        onFocusableContainerDownKey: function(e) {
            return this.moveChildFocus(e, true);
        },

        getFocusableFromEvent: function(e) {
            var child = Ext.ComponentManager.byElement(e.getTarget());

            //<debug>
            if (!child) {
                Ext.Error.raise("No focusable child found for keyboard event!");
            }
            //</debug>

            return child;
        },

        moveChildFocus: function(e, forward) {
            var child = this.getFocusableFromEvent(e);

            return this.focusChild(child, forward, e);
        },

        focusChild: function(child, forward) {
            var nextChild = this.findNextFocusableChild(child, forward);

            if (nextChild) {
                nextChild.focus();
            }

            return nextChild;
        },

        findNextFocusableChild: function(child, step, items, beforeRender) {
            var item, idx, i, len;

            items = items || this.getFocusables();

            // If the child is null or undefined, idx will be -1.
            // The loop below will account for that, trying to find
            // the first focusable child from either end (depending on step)
            idx = Ext.Array.indexOf(items, child);

            // It's often easier to pass a boolean for 1/-1
            step = step === true ? 1 : step === false ? -1 : step;

            len = items.length;
            i   = step > 0 ? (idx < len ? idx + step : 0) : (idx > 0 ? idx + step : len - 1);

            for (;; i += step) {
                // We're looking for the first or last focusable child
                // and we've reached the end of the items, so punt
                if (idx < 0 && (i >= len || i < 0)) {
                    return null;
                }

                // Loop over forward
                else if (i >= len) {
                    i = -1; // Iterator will increase it once more
                    continue;
                }

                // Loop over backward
                else if (i < 0) {
                    i = len;
                    continue;
                }

                // Looped to the same item, give up
                else if (i === idx) {
                    return null;
                }

                item = items[i];

                if (!item || !item.focusable) {
                    continue;
                }

                // This loop can be run either at FocusableContainer init time,
                // or later when we need to navigate upon pressing an arrow key.
                // When we're navigating, we have to know exactly if the child is
                // focusable or not, hence only rendered children will make the cut.
                // At the init time item.isFocusable() may return false incorrectly
                // just because the item has not been rendered yet and its focusEl
                // is not defined, so we don't bother to call isFocus and return
                // the first potentially focusable child.
                if (beforeRender || item.isFocusable()) {
                    return item;
                }
            }

            return null;
        },

        getFocusableContainerEl: function() {
            return this.el;
        },

        onFocusableChildAdd: function(child) {
            return this.doFocusableChildAdd(child);
        },

        activateFocusableContainerEl: function(el) {
            el = el || this.getFocusableContainerEl();

            el.set({ tabindex: this.activeChildTabIndex });
        },

        deactivateFocusableContainerEl: function(el) {
            el = el || this.getFocusableContainerEl();

            el.set({ tabindex: this.inactiveChildTabIndex });
        },

        doFocusableChildAdd: function(child) {
            if (child.focusable) {
                child.focusableContainer = this;
                this.deactivateFocusable(child);
            }
        },

        onFocusableChildRemove: function(child) {
            return this.doFocusableChildRemove(child);
        },

        doFocusableChildRemove: function(child) {
            // If the focused child is being removed, we deactivate the FocusableContainer
            // So that it returns to the tabbing order.
            // For example, locking a grid column must return the owning HeaderContainer to tabbability
            if (child === this.lastFocusedChild) {
                this.lastFocusedChild = null;
                this.activateFocusableContainerEl();
            }
            delete child.focusableContainer;
        },

        onFocusableContainerMousedown: function(e, target) {
            var targetCmp = Ext.ComponentManager.byElement(target);

            // Capture the timestamp for the mousedown. If we're navigating into the container itself
            // via the mouse we don't want to default focus the first child like we would when using
            // the keyboard. By the time we get to the focusenter handling, we don't know what has caused
            // the focus to be triggered, so if the timestamp falls within some small epsilon, the focus enter
            // has been caused via the mouse and we can react accordingly.
            this.mousedownTimestamp = targetCmp === this ? Ext.Date.now() : 0;
        },

        onFocusEnter: function(e) {
            var me = this,
                target = e.toComponent,
                mousedownTimestamp = me.mousedownTimestamp,
                epsilon = 50,
                child;

            me.mousedownTimestamp = 0;
            if (target === me) {
                if (!mousedownTimestamp || Ext.Date.now() - mousedownTimestamp > epsilon) {
                    child = me.initDefaultFocusable();

                    if (child) {
                        me.deactivateFocusableContainerEl();
                        child.focus();
                    }
                }
            } else {
                me.deactivateFocusableContainerEl();
            }

            return target;
        },

        onFocusLeave: function(e) {
            var me = this,
                lastFocused = me.lastFocusedChild;

            if (!me.isDestroyed) {
                me.clearFocusables();

                if (lastFocused) {
                    me.activateFocusable(lastFocused);
                }
                else {
                    me.activateFocusableContainerEl();
                }
            }
        },

        beforeFocusableChildBlur: Ext.privateFn,
        afterFocusableChildBlur: Ext.privateFn,

        beforeFocusableChildFocus: function(child) {
            var me = this;

            me.clearFocusables();
            me.activateFocusable(child);

            if (child.needArrowKeys) {
                me.guardFocusableChild(child);
            }
        },

        guardFocusableChild: function(child) {
            var me = this,
                index = me.activeChildTabIndex,
                guard;

            guard = me.findNextFocusableChild(child, -1);

            if (guard) {
                guard.setTabIndex(index);
            }

            guard = me.findNextFocusableChild(child, 1);

            if (guard) {
                guard.setTabIndex(index);
            }
        },

        afterFocusableChildFocus: function(child) {
            this.lastFocusedChild = child;
        },

        // TODO
        onFocusableChildShow: Ext.privateFn,
        onFocusableChildHide: Ext.privateFn,
        onFocusableChildEnable: Ext.privateFn,
        onFocusableChildDisable: Ext.privateFn,
        onFocusableChildMasked: Ext.privateFn,
        onFocusableChildDestroy: Ext.privateFn,
        onFocusableChildUpdate: Ext.privateFn
    }
});

redpajama_set_name: RedPajamaGithub


text:
<ion-modal-view>
	<ion-header-bar>

공지

			<button class="button button-clear" ng-click="modal.hide()">닫기</button>

	</ion-header-bar>
	<ion-content id="notice-content">

{{::notice.title}}

	</ion-content>
</ion-modal-view>


text:
[![Build Status](https://travis-ci.org/davewwww/FlaggingVoters.svg)](https://travis-ci.org/davewwww/FlaggingVoters) [![Coverage Status](https://coveralls.io/repos/davewwww/FlaggingVoters/badge.svg)](https://coveralls.io/r/davewwww/FlaggingVoters)

FlaggingVoters
--------------

:TODO:


text:
package nl.utwente.viskell.ui.components;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import javafx.application.Platform;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.layout.StackPane;
import nl.utwente.viskell.haskell.expr.Expression;
import nl.utwente.viskell.haskell.expr.LetExpression;
import nl.utwente.viskell.ui.*;
import nl.utwente.viskell.ui.serialize.Bundleable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Predicate;

/**
 * Base block shaped UI Component that other visual elements will extend from.
 * Blocks can add input and output values by implementing the InputBlock and
 * OutputBlock interfaces.
 *

 * MouseEvents are used for setting the selection state of a block, single
 * clicks can toggle the state to selected. When a block has already been
 * selected and receives another single left click it will toggle a contextual
 * menu for the block.
 *

 *

 * Each block implementation should also feature it's own FXML implementation.
 *

 */
public abstract class Block extends StackPane implements Bundleable, ComponentLoader {
    private static final String BLOCK_ID_PARAMETER = "id";
    private static final String BLOCK_X_PARAMETER = "x";
    private static final String BLOCK_Y_PARAMETER = "y";
    private static final String BLOCK_PROPERTIES_PARAMETER = "properties";

    /** The pane that is used to hold state and place all components on. */
    private final ToplevelPane toplevel;

    /** The context that deals with dragging and touch event for this Block */
    protected DragContext dragContext;

    /** Whether the anchor types are fresh*/
    private boolean freshAnchorTypes;

    /** Status of change updating process in this block. */
    private boolean updateInProgress;

    /** The container to which this Block currently belongs */
    protected BlockContainer container;

    /** Whether this block has a meaningful interpretation the current container context. */
    protected boolean inValidContext;

    /**
     * In order to serialize using simple class names we need some way to map the simple class
     * name to the full class names. This is one that should survive automatic refactoring of classes
     * into different packages - but won't survive class renaming
     */
    private static final Map<String, String> blockClassMap;
    static {
        Map<String, String> aMap = new HashMap<>();
        aMap.put(JoinerBlock.class.getSimpleName(), JoinerBlock.class.getName());
        aMap.put(LambdaBlock.class.getSimpleName(), LambdaBlock.class.getName());
        aMap.put(ConstantMatchBlock.class.getSimpleName(), ConstantMatchBlock.class.getName());
        aMap.put(ChoiceBlock.class.getSimpleName(), ChoiceBlock.class.getName());
        aMap.put(LiftingBlock.class.getSimpleName(), LiftingBlock.class.getName());
        aMap.put(MatchBlock.class.getSimpleName(), MatchBlock.class.getName());
        aMap.put(GraphBlock.class.getSimpleName(), GraphBlock.class.getName());
        aMap.put(FunApplyBlock.class.getSimpleName(), FunApplyBlock.class.getName());
        aMap.put(BinOpApplyBlock.class.getSimpleName(), BinOpApplyBlock.class.getName());
        aMap.put(SimulateBlock.class.getSimpleName(), SimulateBlock.class.getName());
        aMap.put(DisplayBlock.class.getSimpleName(), DisplayBlock.class.getName());
        aMap.put(SplitterBlock.class.getSimpleName(), SplitterBlock.class.getName());
        aMap.put(ArbitraryBlock.class.getSimpleName(), ArbitraryBlock.class.getName());
        aMap.put(SliderBlock.class.getSimpleName(), SliderBlock.class.getName());
        aMap.put(ConstantBlock.class.getSimpleName(), ConstantBlock.class.getName());
        blockClassMap = Collections.unmodifiableMap(aMap);
    }

    /**
     * @param pane The pane this block belongs to.
     */
    public Block(ToplevelPane pane) {
        this.toplevel = pane;
        this.freshAnchorTypes = false;
        this.updateInProgress = false;
        this.container = pane;
        this.container.attachBlock(this);
        this.inValidContext = true;

        // only the actual shape should be selected for events, not the larger outside bounds
        this.setPickOnBounds(false);

        if (! this.belongsOnBottom()) {
            // make all non container blocks resize themselves around horizontal midpoint to reduce visual movement
            this.translateXProperty().bind(this.widthProperty().divide(2).negate());
        }

        this.dragContext = new DragContext(this);
        this.dragContext.setSecondaryClickAction((p, byMouse) -> CircleMenu.showFor(this, this.localToParent(p), byMouse));
        this.dragContext.setDragFinishAction(event -> refreshContainer());
        this.dragContext.setContactAction(x -> this.getStyleClass().add("activated"));
        this.dragContext.setReleaseAction(x -> this.getStyleClass().removeAll("activated"));
    }

    /** @return the parent CustomUIPane of this component. */
    public final ToplevelPane getToplevel() {
        return this.toplevel;
    }

    public boolean isActivated() {
        return this.dragContext.isActivated();
    }

    /**
     * @return All InputAnchors of the block.
     */
    public abstract List<InputAnchor> getAllInputs();

    /**
     * @return All OutputAnchors of the Block.
     */
    public abstract List<OutputAnchor> getAllOutputs();

    public List<ConnectionAnchor> getAllAnchors() {
        List<ConnectionAnchor> result = new ArrayList<>(this.getAllInputs());
        result.addAll(this.getAllOutputs());
        return result;
    }

    /** @return true if no connected output anchor exist */
    public boolean isBottomMost() {
        for (OutputAnchor anchor : getAllOutputs()) {
            if (anchor.hasConnection()) {
                return false;
            }
        }

        return true;
    }

    /**
     * Starts a new (2 phase) change propagation process from this block.
     */
    public final void initiateConnectionChanges() {
        this.handleConnectionChanges(false);
        this.handleConnectionChanges(true);
    }

    /**
     * Connection change preparation; set fresh types in all anchors.
     */
    public final void prepareConnectionChanges() {
        if (this.updateInProgress || this.freshAnchorTypes) {
            return; // refresh anchor types in each block only once
        }
        this.freshAnchorTypes = true;
        this.refreshAnchorTypes();

        this.inValidContext = this.checkValidInCurrentContainer();
        if (this.inValidContext) {
            this.getStyleClass().removeAll("invalid");
        } else {
            this.getStyleClass().removeAll("invalid");
            this.getStyleClass().add("invalid");
        }
    }

    /**
     * Set fresh types in all anchors of this block for the next typechecking cycle.
     */
    protected abstract void refreshAnchorTypes();

    /**
     * Handle the expression and types changes caused by modified connections or values.
     * Propagate the changes through connected blocks, and if final phase trigger a visual update.
     * @param finalPhase whether the change propagation is in the second (final) phase.
     */
    public void handleConnectionChanges(boolean finalPhase) {
        if (this.updateInProgress != finalPhase) {
            return; // avoid doing extra work and infinite recursion
        }

        if (! finalPhase) {
            // in first phase ensure that anchor types are refreshed
            this.prepareConnectionChanges();
        }

        this.updateInProgress = !finalPhase;
        this.freshAnchorTypes = false;

        // First make sure that all connected inputs will be updated too.
        for (InputAnchor input : this.getAllInputs()) {
            input.getConnection().ifPresent(c -> c.handleConnectionChangesUpwards(finalPhase));
        }

        // propagate changes down from the output anchor to connected inputs
        this.getAllOutputs().stream().forEach(output -> output.getOppositeAnchors().forEach(input -> input.handleConnectionChanges(finalPhase)));

        // propagate changes to the outside of a choiceblock
        if (container instanceof Lane) {
            ((Lane)container).handleConnectionChanges(finalPhase);
        }

        if (finalPhase) {
            // Now that the expressions and types are fully updated, initiate a visual refresh.
            Platform.runLater(this::invalidateVisualState);
        }
    }

    /**
     * @param outsideAnchors the set being accumulated of out-of-reach OutputAnchors that are required for the expression.
     * @return The expression this block represents.
     */
    public abstract Expression getLocalExpr(Set<OutputAnchor> outsideAnchors);

    /**
     * This method is only used for the inspector window.
     * @return A complete expression of this block and all its dependencies.
     */
    public final Expression getFullExpr() {
        Set<OutputAnchor> outerAnchors = new HashSet<>();
        Expression localExpr = getLocalExpr(outerAnchors);

        LetExpression fullExpr = new LetExpression(localExpr, false);
        extendExprGraph(fullExpr, this.toplevel, outerAnchors);

        outerAnchors.forEach(block -> block.extendExprGraph(fullExpr, this.toplevel, new HashSet<>()));

        return fullExpr;
    }

    /**
     * Extends the expression graph to include all subexpression required
     * @param exprGraph the let expression representing the current expression graph
     * @param container the container to which this expression graph is constrained
     * @param outsideAnchors a mutable set of required OutputAnchors from a surrounding container
     */
    protected void extendExprGraph(LetExpression exprGraph, BlockContainer container, Set<OutputAnchor> outsideAnchors) {
         for (InputAnchor input : this.getAllInputs()) {
             input.extendExprGraph(exprGraph, container, outsideAnchors);
         }
    }

    /** Called when the VisualState changed. */
    public abstract void invalidateVisualState();

    /** @return whether this block is visually shown below common blocks (is constant per instance). */
    public boolean belongsOnBottom() {
        return false;
    }

    /** @return class-specific properties of this Block. */
    protected Map<String, Object> toBundleFragment() {
        return ImmutableMap.of();
    }

    /** @return the container to which this block belongs */
    public BlockContainer getContainer() {
        return container;
    }

    /** @return the list of internal containers wrapped inside this block */
    public List<? extends WrappedContainer> getInternalContainers() {
        return ImmutableList.of();
    }

    /** @return an independent copy of this Block, or Optional.empty if the internal state is too complex too copy.  */
    public abstract Optional<Block> getNewCopy();

    /** Remove all associations of this block with others in preparation of removal, including all connections */
    public void deleteAllLinks() {
        this.getAllInputs().forEach(InputAnchor::removeConnections);
        this.getAllOutputs().forEach(OutputAnchor::removeConnections);
        this.container.detachBlock(this);
        this.container = TrashContainer.instance;
    }

    public void moveIntoContainer(BlockContainer target) {
        BlockContainer source = this.container;
        if (source != target) {
            this.container.detachBlock(this);
            this.container = target;
            target.attachBlock(this);

            if (this.getInternalContainers().size() > 0) {
                this.toplevel.moveInFrontOfParentContainers(this);
            }

            if (source instanceof WrappedContainer) {
                ((WrappedContainer)source).handleConnectionChanges(false);
                ((WrappedContainer)source).handleConnectionChanges(true);
            }

            if (target instanceof WrappedContainer) {
                ((WrappedContainer)target).handleConnectionChanges(false);
                ((WrappedContainer)target).handleConnectionChanges(true);
            }

            this.initiateConnectionChanges();
        }

    }

    /** @return the bounds of this block in scene coordinates, excluding the parts sticking out such as anchors. */
    public Bounds getBodyBounds() {
        Node body = this.getChildren().get(0);
        return body.localToScene(body.getLayoutBounds());
    }

    /** Scans for and attaches to a new container, if any */
    public void refreshContainer() {
        Bounds myBounds = this.getBodyBounds();
        Point2D center = new Point2D((myBounds.getMinX()+myBounds.getMaxX())/2, (myBounds.getMinY()+myBounds.getMaxY())/2);
        List<Point2D> corners = ImmutableList.of(
                new Point2D(myBounds.getMinX(), myBounds.getMinY()),
                new Point2D(myBounds.getMaxX(), myBounds.getMinY()),
                new Point2D(myBounds.getMinX(), myBounds.getMaxY()),
                new Point2D(myBounds.getMaxX(), myBounds.getMaxY()));

        // use center point plus one corner to determine wherein this block is, to ease moving a block into a small container
        Predicate<Bounds> within = bounds -> bounds.contains(center) && corners.stream().anyMatch(bounds::contains);

        // a container may never end up in itself or its children
        List<? extends WrappedContainer> internals = this.getInternalContainers();
        Predicate<BlockContainer> notInSelf = con -> internals.stream().noneMatch(con::isContainedWithin);

        BlockContainer newContainer = toplevel.getAllBlockContainers().
            filter(container -> within.test(container.containmentBoundsInScene()) && notInSelf.test(container)).
                reduce((a, b) -> !a.containmentBoundsInScene().contains(b.containmentBoundsInScene()) ? a : b).
                    orElse(this.toplevel);

        Bounds fitBounds = this.localToParent(this.sceneToLocal(myBounds));
        this.moveIntoContainer(newContainer);
        newContainer.expandToFit(new BoundingBox(fitBounds.getMinX()-10, fitBounds.getMinY()-10, fitBounds.getWidth()+20, fitBounds.getHeight()+20));
    }

    /** @return whether this block has a meaningful interpretation the current container. */
    public boolean checkValidInCurrentContainer() {
        return ! (this.container instanceof TrashContainer);
    }

    public boolean canAlterAnchors() {
        return false;
    }

    public void alterAnchorCount(boolean isRemove) {
        // does not if not supported
    }

    @Override
    public Map<String, Object> toBundle() {
        return ImmutableMap.of(
                Bundleable.KIND, getClass().getSimpleName(),
                BLOCK_ID_PARAMETER, hashCode(),
                BLOCK_X_PARAMETER, getLayoutX(),
                BLOCK_Y_PARAMETER, getLayoutY(),
                BLOCK_PROPERTIES_PARAMETER, toBundleFragment()
        );
    }

    public static Block fromBundle(Map<String,Object> blockBundle,
                                   ToplevelPane toplevelPane,
                                   Map<Integer, Block> blockLookupTable)
            throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String kind = (String)blockBundle.get(Bundleable.KIND);
        String className = blockClassMap.get(kind);
        Class<?> clazz = Class.forName(className);

        // Find the static "fromBundleFragment" method for the named type and call it
        Method fromBundleMethod = clazz.getDeclaredMethod("fromBundleFragment", ToplevelPane.class, Map.class);
        Block block = (Block) fromBundleMethod.invoke(null, toplevelPane, blockBundle.get(BLOCK_PROPERTIES_PARAMETER));
        block.setLayoutX((Double)blockBundle.get(BLOCK_X_PARAMETER));
        block.setLayoutY((Double) blockBundle.get(BLOCK_Y_PARAMETER));
        blockLookupTable.put(((Double)blockBundle.get(Block.BLOCK_ID_PARAMETER)).intValue(), block);

        // Ensure initialization of types related to the block
        block.initiateConnectionChanges();
        return block;
    }
}


text:
package com.communote.server.web.api.service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import com.communote.server.web.api.to.ApiResult;

/**
 * Base controller for api rest calls
 *
 * @author Communote GmbH - http://www.communote.com/
 * @deprecated Use new generated REST-API instead
 * @param <GET>
 *            Return type of doGet
 * @param <POST>
 *            Return type of doPost
 */
@Deprecated
public class BaseRestApiController<GET, POST> extends ApiResultApiController {

    /**
     * Do the get on a resource
     *
     * @param apiResult
     *            the apiResult
     * @param request
     *            the request
     * @param response
     *            the response
     * @return the post resource
     * @throws ApiException
     *             an error occured
     */
    protected GET doGet(ApiResult apiResult, HttpServletRequest request,
            HttpServletResponse response) throws ApiException {
        throw new ApiException("Request Method '" + request.getMethod() + "'not supported");
    }

    /**
     * Do a a post resource
     *
     * @param apiResult
     *            the apiResult
     * @param request
     *            the request
     * @param response
     *            the response
     * @return null
     * @throws HttpRequestMethodNotSupportedException
     *             if method not implemented
     * @throws ApiException
     *             in case of an error
     * @throws Exception
     */
    protected POST doPost(ApiResult apiResult, HttpServletRequest request,
            HttpServletResponse response) throws HttpRequestMethodNotSupportedException,
            ApiException {
        throw new ApiException("Request Method '" + request.getMethod() + "'not supported");
    }

    /**
     * {@inheritDoc}
     *
     * @throws RequestedResourceNotFoundException
     * @throws HttpRequestMethodNotSupportedException
     */
    @Override
    protected Object execute(ApiResult apiResult, HttpServletRequest request,
            HttpServletResponse response) throws ApiException, ServletException {

        if (StringUtils.equalsIgnoreCase("GET", request.getMethod())) {
            return doGet(apiResult, request, response);
        } else if (StringUtils.equalsIgnoreCase("POST", request.getMethod())) {
            return doPost(apiResult, request, response);
        }
        throw new ApiException("Request Method '" + request.getMethod() + "'not supported");

    }
}


text:
@interface GallaryViewCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImageView *gallaryImage;

@end


text:
begin
  require "rubygems/deprecate"
rescue LoadError
  # it's fine if it doesn't exist on the current RubyGems...
  nil
end

module Bundler
  # If Bundler::Deprecate is an autoload constant, we need to define it
  if defined?(Bundler::Deprecate) && !autoload?(:Deprecate)
    # nothing to do!
  elsif defined? ::Deprecate
    Deprecate = ::Deprecate
  elsif defined? Gem::Deprecate
    Deprecate = Gem::Deprecate
  else
    class Deprecate
    end
  end

  unless Deprecate.respond_to?(:skip_during)
    def Deprecate.skip_during
      original = skip
      self.skip = true
      yield
    ensure
      self.skip = original
    end
  end

  unless Deprecate.respond_to?(:skip)
    def Deprecate.skip
      @skip ||= false
    end
  end

  unless Deprecate.respond_to?(:skip=)
    def Deprecate.skip=(skip)
      @skip = skip
    end
  end
end


text:
package org.springframework.richclient.widget;

import org.springframework.richclient.command.AbstractCommand;

import javax.swing.*;
import java.awt.*;

/* ButtonSwitcher is a simple widget that puts 2 buttons from the same command (but with
 * different face id's) on a cardlayout.
 *
 * This makes it easy to switch between 2 faces.
 */
public class ButtonSwitcherWidget extends AbstractWidget
{

    private final CardLayout switcher;
    private final JPanel panel;

    public static final String DEFAULT = "default";
    public static final String ALTERNATIVE = "alternative";

    public ButtonSwitcherWidget(AbstractCommand command, String alternativeFaceId)
    {
        AbstractButton defaultButton = command.createButton();
        AbstractButton alternButton = command.createButton(alternativeFaceId);
        this.switcher = new CardLayout();
        this.panel = new JPanel(this.switcher);
        this.panel.add(defaultButton, DEFAULT);
        this.panel.add(alternButton, ALTERNATIVE);
    }

    public JComponent getComponent()
    {
        return this.panel;
    }

    public void showDefault()
    {
        this.switcher.first(this.panel);
    }

    public void showAlternative()
    {
        this.switcher.last(this.panel);
    }

    public void show(String mode)
    {
        this.switcher.show(this.panel, mode);

    }
}


text:
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;
using Coevery.Mvc.Filters;

namespace Coevery.Users.Services {

    /// <summary>
    /// This class is responsible for redirecting the user to the authentication page
    /// of the current tenant.
    /// </summary>
    public class AuthenticationRedirectionFilter : FilterProvider, IAuthenticationFilter {

        public void OnAuthentication(AuthenticationContext filterContext) {
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) {
            if (filterContext.Result is HttpUnauthorizedResult) {
                filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                {
                    { "controller", "Account" },
                    { "action", "AccessDenied" },
                    { "area", "Coevery.Users"},
                    { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                });
            }
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Salix tschuktschorum A.K.Skvortsov

### Remarks
null


text:
from enum import Enum

class TextOperationStatusCodes(Enum):

    not_started = "Not Started"
    running = "Running"
    failed = "Failed"
    succeeded = "Succeeded"

class ComputerVisionErrorCodes(Enum):

    invalid_image_url = "InvalidImageUrl"
    invalid_image_format = "InvalidImageFormat"
    invalid_image_size = "InvalidImageSize"
    not_supported_visual_feature = "NotSupportedVisualFeature"
    not_supported_image = "NotSupportedImage"
    invalid_details = "InvalidDetails"
    not_supported_language = "NotSupportedLanguage"
    bad_argument = "BadArgument"
    failed_to_process = "FailedToProcess"
    timeout = "Timeout"
    internal_server_error = "InternalServerError"
    unspecified = "Unspecified"
    storage_exception = "StorageException"

class VisualFeatureTypes(Enum):

    image_type = "ImageType"
    faces = "Faces"
    adult = "Adult"
    categories = "Categories"
    color = "Color"
    tags = "Tags"
    description = "Description"

class OcrLanguages(Enum):

    unk = "unk"
    zh_hans = "zh-Hans"
    zh_hant = "zh-Hant"
    cs = "cs"
    da = "da"
    nl = "nl"
    en = "en"
    fi = "fi"
    fr = "fr"
    de = "de"
    el = "el"
    hu = "hu"
    it = "it"
    ja = "ja"
    ko = "ko"
    nb = "nb"
    pl = "pl"
    pt = "pt"
    ru = "ru"
    es = "es"
    sv = "sv"
    tr = "tr"
    ar = "ar"
    ro = "ro"
    sr_cyrl = "sr-Cyrl"
    sr_latn = "sr-Latn"
    sk = "sk"

class AzureRegions(Enum):

    westus = "westus"
    westeurope = "westeurope"
    southeastasia = "southeastasia"
    eastus2 = "eastus2"
    westcentralus = "westcentralus"
    westus2 = "westus2"
    eastus = "eastus"
    southcentralus = "southcentralus"
    northeurope = "northeurope"
    eastasia = "eastasia"
    australiaeast = "australiaeast"
    brazilsouth = "brazilsouth"

class Details(Enum):

    celebrities = "Celebrities"
    landmarks = "Landmarks"

class Language1(Enum):

    en = "en"
    zh = "zh"

class DomainModels(Enum):

    celebrities = "Celebrities"
    landmarks = "Landmarks"


text:
<?php

/**
 * Class wrapper for the render and compile template functions
 *
 * @package Divinity
 * @author  Simon Holloway <holloway.sy@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 */
class Divinity_Template extends Glyph
{
	/**
	 * Template directory where a collection of templates are stored
	 *
	 * @var boolean|string
	 */
	public $template_directory = false;

	/**
	 * Template location within the template directory
	 *
	 * @var boolean|string
	 */
	public $template = false;

	/**
	 * Template engine for the template
	 *
	 * @var Divinity_Engine
	 */
	protected $engine;

	/**
	 * Setup the template with required properties
	 *
	 * @param string          $template_directory
	 * @param string          $template
	 * @param Divinity_Engine $engine
	 * @param array           $data
	 */
	public function __construct($template_directory, $template, Divinity_Engine $engine, array $data = array())
	{
		$this->template_directory = $template_directory;
		$this->template = $template;
		$this->data = $data;
		$this->engine = $engine;
	}

	/**
	 * Set the template engine
	 *
	 * @param Divinity_Engine $template
	 * @return self
	 */
	public function set_engine(Divinity_Engine $engine)
	{
		$this->engine = $engine;
		return $this;
	}

	/**
	 * Get the template engine
	 *
	 * @return string
	 */
	public function get_engine()
	{
		return $this->engine;
	}

	/**
	 * Set the template data from an array
	 *
	 * @param string $data data to set
	 * @return self
	 */
	public function bulk_set(array $data)
	{
		$data = array_dot($data);
		foreach ($data as $index => $item) {
			$this->set($index, $item);
		}
		return $this;
	}

	/**
	 * Render the template markup
	 *
	 * @return void
	 */
	public function render()
	{
		return $this->engine->render(
			$this->template_directory,
			$this->template,
			$this->data
		);
	}

	/**
	 * Compile and return the template markup
	 *
	 * @return string
	 */
	public function compile()
	{
		return $this->engine->compile(
			$this->template_directory,
			$this->template,
			$this->data
		);
	}

	/**
	 * Compile this template and return as a string
	 *
	 * @param string|interger $index
	 */
	public function __toString()
	{
		return $this->compile();
	}
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="/src/css/style.css">


text:
#ifndef StringObject_h
#define StringObject_h

#include "JSWrapperObject.h"
#include "JSString.h"

namespace JSC {

    class StringObject : public JSWrapperObject {
    public:
        typedef JSWrapperObject Base;

        static StringObject* create(ExecState* exec, Structure* structure)
        {
            JSString* string = jsEmptyString(exec);
            StringObject* object = new (NotNull, allocateCell<StringObject>(*exec->heap())) StringObject(exec->vm(), structure);
            object->finishCreation(exec->vm(), string);
            return object;
        }
        static StringObject* create(ExecState* exec, Structure* structure, JSString* string)
        {
            StringObject* object = new (NotNull, allocateCell<StringObject>(*exec->heap())) StringObject(exec->vm(), structure);
            object->finishCreation(exec->vm(), string);
            return object;
        }
        static StringObject* create(ExecState*, JSGlobalObject*, JSString*);

        static bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&);
        static bool getOwnPropertySlotByIndex(JSObject*, ExecState*, unsigned propertyName, PropertySlot&);

        static void put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);
        static void putByIndex(JSCell*, ExecState*, unsigned propertyName, JSValue, bool shouldThrow);

        static bool deleteProperty(JSCell*, ExecState*, PropertyName);
        static bool deletePropertyByIndex(JSCell*, ExecState*, unsigned propertyName);
        static void getOwnPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
        static bool defineOwnProperty(JSObject*, ExecState*, PropertyName, const PropertyDescriptor&, bool shouldThrow);

        DECLARE_EXPORT_INFO;

        JSString* internalValue() const { return asString(JSWrapperObject::internalValue());}

        static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
        {
            return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
        }

    protected:
        JS_EXPORT_PRIVATE void finishCreation(VM&, JSString*);
        static const unsigned StructureFlags = OverridesGetOwnPropertySlot | InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | OverridesGetPropertyNames | JSWrapperObject::StructureFlags;
        JS_EXPORT_PRIVATE StringObject(VM&, Structure*);
    };

    StringObject* asStringObject(JSValue);

    inline StringObject* asStringObject(JSValue value)
    {
        ASSERT(asObject(value)->inherits(StringObject::info()));
        return static_cast<StringObject*>(asObject(value));
    }

    JS_EXPORT_PRIVATE StringObject* constructString(ExecState*, JSGlobalObject*, JSValue);

} // namespace JSC

#endif // StringObject_h


text:
<?php

final class PhabricatorPeopleSearchEngine
  extends PhabricatorApplicationSearchEngine {

  public function buildSavedQueryFromRequest(AphrontRequest $request) {
    $saved = new PhabricatorSavedQuery();

    $saved->setParameter('usernames', $request->getStrList('usernames'));
    $saved->setParameter('nameLike', $request->getStr('nameLike'));
    $saved->setParameter('isAdmin', $request->getStr('isAdmin'));
    $saved->setParameter('isDisabled', $request->getStr('isDisabled'));
    $saved->setParameter('isSystemAgent', $request->getStr('isSystemAgent'));
    $saved->setParameter('createdStart', $request->getStr('createdStart'));
    $saved->setParameter('createdEnd', $request->getStr('createdEnd'));

    return $saved;
  }

  public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
    $query = id(new PhabricatorPeopleQuery())
      ->needPrimaryEmail(true);

    $usernames = $saved->getParameter('usernames', array());
    if ($usernames) {
      $query->withUsernames($usernames);
    }

    $like = $saved->getParameter('nameLike');
    if ($like) {
      $query->withNameLike($like);
    }

    $is_admin = $saved->getParameter('isAdmin');
    $is_disabled = $saved->getParameter('isDisabled');
    $is_system_agent = $saved->getParameter('isSystemAgent');

    if ($is_admin) {
      $query->withIsAdmin(true);
    }

    if ($is_disabled) {
      $query->withIsDisabled(true);
    }

    if ($is_system_agent) {
      $query->withIsSystemAgent(true);
    }

    $start = $this->parseDateTime($saved->getParameter('createdStart'));
    $end = $this->parseDateTime($saved->getParameter('createdEnd'));

    if ($start) {
      $query->withDateCreatedAfter($start);
    }

    if ($end) {
      $query->withDateCreatedBefore($end);
    }
    return $query;
  }

  public function buildSearchForm(
    AphrontFormView $form,
    PhabricatorSavedQuery $saved) {

    $usernames = $saved->getParameter('usernames', array());
    $like = $saved->getParameter('nameLike');

    $is_admin = $saved->getParameter('isAdmin');
    $is_disabled = $saved->getParameter('isDisabled');
    $is_system_agent = $saved->getParameter('isSystemAgent');

    $form
      ->appendChild(
        id(new AphrontFormTextControl())
          ->setName('usernames')
          ->setLabel(pht('Usernames'))
          ->setValue(implode(', ', $usernames)))
      ->appendChild(
        id(new AphrontFormTextControl())
          ->setName('nameLike')
          ->setLabel(pht('Name Contains'))
          ->setValue($like))
      ->appendChild(
        id(new AphrontFormCheckboxControl())
          ->setLabel('Role')
          ->addCheckbox(
            'isAdmin',
            1,
            pht('Show only Administrators.'),
            $is_admin)
          ->addCheckbox(
            'isDisabled',
            1,
            pht('Show only disabled users.'),
            $is_disabled)
          ->addCheckbox(
            'isSystemAgent',
            1,
            pht('Show only System Agents.'),
            $is_system_agent));

    $this->buildDateRange(
      $form,
      $saved,
      'createdStart',
      pht('Joined After'),
      'createdEnd',
      pht('Joined Before'));
  }

  protected function getURI($path) {
    return '/people/'.$path;
  }

  public function getBuiltinQueryNames() {
    $names = array(
      'all' => pht('All'),
    );

    return $names;
  }

  public function buildSavedQueryFromBuiltin($query_key) {
    $query = $this->newSavedQuery();
    $query->setQueryKey($query_key);

    switch ($query_key) {
      case 'all':
        return $query;
    }

    return parent::buildSavedQueryFromBuiltin($query_key);
  }

}


text:
from .base import GeneratedItem, convertValueToObjc, const
from .view import View, Pack

# Views in tab items have different margins than normal views.
class TabSubView(View):
    INNER_MARGIN_LEFT = 17
    INNER_MARGIN_RIGHT = 17
    INNER_MARGIN_ABOVE = 3
    INNER_MARGIN_BELOW = 17

class TabViewItem(GeneratedItem):
    OBJC_CLASS = 'NSTabViewItem'

    def __init__(self, tabview, label, identifier=None):
        GeneratedItem.__init__(self)
        self.label = label
        self._view = TabSubView(None, tabview.width - tabview.OVERHEAD_W,
            tabview.height - tabview.OVERHEAD_H)
        self.identifier = identifier

    @property
    def view(self):
        return self._view

    def dependencies(self):
        return [self.view] + self.view.subviews

    def generateInit(self):
        tmpl = GeneratedItem.generateInit(self)
        if self.identifier is not None:
            tmpl.initmethod = "initWithIdentifier:$identifier$"
            tmpl.identifier = convertValueToObjc(self.identifier)
        self.properties['label'] = self.label
        self.properties['view'] = self.view
        return tmpl

class TabView(View):
    OBJC_CLASS = 'NSTabView'
    PROPERTIES = View.PROPERTIES + ['tabViewType']
    OVERHEAD_W = 6
    OVERHEAD_H = 30

    def __init__(self, parent):
        View.__init__(self, parent, 160, 110)
        self.tabs = []
        self._tabViewType = const.NSTopTabsBezelBorder
        self._updateLayoutDeltas()

    def _updatePos(self):
        for tab in self.tabs:
            tab.view.width = self.width - self.OVERHEAD_W
            tab.view.height = self.height - self.OVERHEAD_H

    def _updateLayoutDeltas(self):
        if self.tabViewType == const.NSNoTabsNoBorder:
            self.layoutDeltaX = 0
            self.layoutDeltaY = 0
            self.layoutDeltaW = 0
            self.layoutDeltaH = 0
        else:
            self.layoutDeltaX = -7
            self.layoutDeltaY = -10
            self.layoutDeltaW = 14
            self.layoutDeltaH = 16

    def innerMarginDelta(self, side):
        if side == Pack.Above:
            return -12
        else:
            return View.innerMarginDelta(self, side)

    def addTab(self, label, identifier=None):
        tab = TabViewItem(self, label, identifier)
        self.tabs.append(tab)
        return tab

    @property
    def tabViewType(self):
        return self._tabViewType

    @tabViewType.setter
    def tabViewType(self, value):
        self._tabViewType = value
        self._updateLayoutDeltas()

    def generateInit(self):
        tmpl = View.generateInit(self)
        viewsetup = ""
        for tab in self.tabs:
            tabcode = tab.generate()
            tabcode += "[$varname$ addTabViewItem:%s];\n" % tab.varname
            viewsetup += tabcode
        tmpl.viewsetup = viewsetup
        return tmpl


text:
//
//  JSONResponse.h
//  JSONClient
//
//  Created by John Clayton on 9/6/2009.
//  Copyright 2009 Fivesquare Software, LLC. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface JSONResponse : NSObject {
	NSURLRequest *urlRequest;

	NSInteger status;
	NSDictionary *headers;
	NSString *body;
	id result;
	NSError *error;
}

@property (nonatomic, retain) NSURLRequest *urlRequest;
@property (nonatomic, assign) NSInteger status;
@property (nonatomic, retain) NSDictionary *headers;
@property (nonatomic, retain) NSString *body;
@property (nonatomic, retain) id result;
@property (nonatomic, retain) NSError *error;

/** Specific codes */

- (BOOL) isOk; // 200
- (BOOL) isCreated; // 201

- (BOOL) isFound; // 302

- (BOOL) isUnauthorized; // 401
- (BOOL) isForbidden; // 403
- (BOOL) isNotFound; // 404
- (BOOL) isUnprocessableEntity; // 422

/** Ranges of codes */

- (BOOL) wasSuccessful; // 200's
- (BOOL) wasRedirect; // 300's
- (BOOL) wasClientErrror; // 400's
- (BOOL) wasServerError; // 500's

@end


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Formo_Core_Driver_Optgroup extends Formo_Driver {

	protected $_view_file = 'optgroup';

	public function val($value = NULL)
	{
		if (func_num_args() === 0)
			return $this->_field->parent()->val();

		return $this->_field->parent()->val($value);
	}

	public function html()
	{
		foreach ($this->_field->get('options') as $label => $options)
		{
			$this->_field->append(Formo::field($label, 'option', $options));
		}

		$this->_view
			->set_var('tag', 'optgroup')
			->attr('label', $this->_field->alias());
	}

}


text:
package servlet.booking;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import servlet.GetResult;
import servlet.MyServlet;
import servlet.ServletResult;
import storage.DatabaseManager;

import com.j256.ormlite.stmt.QueryBuilder;

import entity.Booking;

/**
 * Servlet implementation class GetAllBooking
 */
@WebServlet("/Booking/GetAll")
public class GetAllBooking extends MyServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public GetAllBooking() {

    }

	@Override
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		DatabaseManager manager=DatabaseManager.getManager();

		String begin=request.getParameter(Booking.BEGIN);
		String end=request.getParameter(Booking.END);

		try {
			if(!MyServlet.isEmpty(begin) && !MyServlet.isEmpty(end)){
				SimpleDateFormat df=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
				QueryBuilder<Booking, Integer> query=manager.getBookingDao().queryBuilder();

				query.where().ge("begin", df.parse(begin))
						.and().lt("end", df.parse(end));

				ServletResult.sendResult(response, new GetResult(
						ServletResult.SUCCESS, fill(manager, query.query())));
			}
			else{
				ServletResult.sendResult(response, new GetResult(
						ServletResult.SUCCESS, fill(manager, manager.getBookingDao().queryForAll())));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			ServletResult.sendResult(response, ServletResult.ERROR);
		} catch (ParseException e) {
			e.printStackTrace();
			ServletResult.sendResult(response, ServletResult.BAD_DATE_FORMAT);
		}
	}

	private static List<Booking> fill(DatabaseManager manager, List<Booking> list){
		for(Booking booking : list){
			booking.setRooms(manager.getRoom(booking));
			booking.setEquipments(manager.getEquipment(booking));
		}

		return list;
	}

}


text:
A small and easily embeddable Java Http server for use in applications.

[![Build Status](https://travis-ci.org/nikkiii/embedhttp.svg?branch=master)](https://travis-ci.org/nikkiii/embedhttp)

## Requirements

- Java Development Kit/Java Runtime Environment 1.6+ (Could work in 1.5?)

## Usage

	HttpServer server = new HttpServer();

	//~ Add any request handlers
	// static file handler (from jar's resources) :
	server.addRequestHandler(new HttpStaticJarFileHandler());
    // static file handler (from jar's resources with path) :
    server.addRequestHandler(new HttpStaticJarFileHandler("/assets/http/"));
	// static file handler (from filesystem) :
	server.addRequestHandler(new HttpStaticFileHandler(new File(".")));
	//Or your own:
	server.addRequestHandler(new HttpRequestHandler() {
		@Override
		public HttpResponse handleRequest(HttpRequest request) {
			return new HttpResponse(HttpStatus.OK, "Hello, world!");
		}
	});
	server.bind(8081);
	server.start();

## License

The MIT License (MIT)

Copyright (c) 2014 Nikki

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
from typing import Optional, Dict, Any, TypeVar, Callable, Type, cast

T = TypeVar("T")

def from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]:
    assert isinstance(x, dict)
    return { k: f(v) for (k, v) in x.items() }

def from_str(x: Any) -> str:
    assert isinstance(x, str)
    return x

def from_none(x: Any) -> Any:
    assert x is None
    return x

def from_union(fs, x):
    for f in fs:
        try:
            return f(x)
        except:
            pass
    assert False

def to_class(c: Type[T], x: Any) -> dict:
    assert isinstance(x, c)
    return cast(Any, x).to_dict()

class Message:
    """The message that was published."""
    """Attributes for this message."""
    attributes: Optional[Dict[str, str]]
    """The binary data in the message."""
    data: Optional[str]
    """ID of this message, assigned by the server when the message is published.
    Guaranteed to be unique within the topic.
    """
    message_id: Optional[str]

    def __init__(self, attributes: Optional[Dict[str, str]], data: Optional[str], message_id: Optional[str]) -> None:
        self.attributes = attributes
        self.data = data
        self.message_id = message_id

    @staticmethod
    def from_dict(obj: Any) -> 'Message':
        assert isinstance(obj, dict)
        attributes = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("attributes"))
        data = from_union([from_str, from_none], obj.get("data"))
        message_id = from_union([from_str, from_none], obj.get("messageId"))
        return Message(attributes, data, message_id)

    def to_dict(self) -> dict:
        result: dict = {}
        result["attributes"] = from_union([lambda x: from_dict(from_str, x), from_none], self.attributes)
        result["data"] = from_union([from_str, from_none], self.data)
        result["messageId"] = from_union([from_str, from_none], self.message_id)
        return result

class MessagePublishedData:
    """The event data when a message is published to a topic."""
    """The message that was published."""
    message: Optional[Message]
    """The resource name of the subscription for which this event was
    generated. The format of the value is
    `projects/{project-id}/subscriptions/{subscription-id}`.
    """
    subscription: Optional[str]

    def __init__(self, message: Optional[Message], subscription: Optional[str]) -> None:
        self.message = message
        self.subscription = subscription

    @staticmethod
    def from_dict(obj: Any) -> 'MessagePublishedData':
        assert isinstance(obj, dict)
        message = from_union([Message.from_dict, from_none], obj.get("message"))
        subscription = from_union([from_str, from_none], obj.get("subscription"))
        return MessagePublishedData(message, subscription)

    def to_dict(self) -> dict:
        result: dict = {}
        result["message"] = from_union([lambda x: to_class(Message, x), from_none], self.message)
        result["subscription"] = from_union([from_str, from_none], self.subscription)
        return result

def message_published_data_from_dict(s: Any) -> MessagePublishedData:
    return MessagePublishedData.from_dict(s)

def message_published_data_to_dict(x: MessagePublishedData) -> Any:
    return to_class(MessagePublishedData, x)


text:
> {%= description %}

[![code climate][codeclimate-img]][codeclimate-url] [![standard code style][standard-img]][standard-url] [![travis build status][travis-img]][travis-url] [![coverage status][coveralls-img]][coveralls-url] [![dependency status][david-img]][david-url]

You might also be interested in [relike][], [relike-all][], [relike-value][] and [{%= varname %}-value][].

## Table Of Contents
<!-- toc -->

## Highlights
> A few features and main points.

- promisify sync, async and generator functions
- lower lever than "promisify" - giving function to 1st argument, the next arguments are passed to it
- thin wrapper around [relike][] package to add support for generators, using [co][]
- full compatibility with `co@4` and passing 100% of its tests (works as drop-in replacement)
- correct detecting async (callback-style) functions
- correct handling of optional arguments, just `fn.length` not works - believe
- great handling of errors, uncaught exceptions, rejections and optional arguments
- always stay to the standards and specs
- always trying to use native Promise first if available, then another if provided
- throws only if no native Promises and not custom Promise module is given
- works on any nodejs version - from `v0.10.x` to latest `v6+` [Node.js](https://nodejs.org)
- accept and works with javascript internal functions like `JSON.stringify` and `JSON.parse`

## Notes

### Sync and async functions
Note that it treats functions as asynchronous, based on [is-async-function][].

Why you should be aware of that? Because if you give async function which don't have last argument called with some of the [common-callback-names][] it will treat that function as synchronous and things may not work as expected.

It's not a problem for most of the cases and for node's native packages, because that's a convention.

### Working on old environment

Note that `{%= name %}` will work out-of-the-box in most cases and without problems. But in old environment which don't have support for native Promises there's little thing that you should remember.

## Install
```
npm i {%= name %} --save
```

## Usage
> For more use-cases see the [tests](./test.js), [examples](./examples) or all the passing [`co@4` tests](./test/co)

```js
const fs = require('fs')
const {%= varname %} = require('{%= name %}')

const promise = {%= varname %}(function * () {
  let result = yield Promise.resolve(123)
  return result
})

promise.then(value => {
  console.log(value) // => 123
}, err => {
  console.error(err.stack)
})
```

If you want to convert generator function to regular function that returns a Promise use [{%= varname %}.promisify](#promisify)

**Example**

```js
const {%= varname %} = require('{%= name %}')
const fn = {%= varname %}.promisify(function * (number) {
  return yield Promise.resolve(number)
})

fn(456).then(number => {
  console.log(number) // => 456
}, err => {
  console.error(err.stack)
})
```

If you want to promisify **any** type of function, again, just use the [.promisify](#promisify) method, like you do with [bluebird][].promisify.

```js
const fs = require('fs')
const {%= varname %} = require('{%= name %}')
const readFile = {%= varname %}.promisify(fs.readFile)

readFile('package.json', 'utf8')
  .then(JSON.parse)
  .then(value => {
    console.log(value.name) // => '{%= varname %}'
  })
  .catch(SyntaxError, err => {
    console.error('File had syntax error', err)
  })
  // Catch any other error
  .catch(err => {
    console.error(err.stack)
  })
```

## API
{%= apidocs('index.js') %}

### .Promise

While `{%= varname %}` always trying to use native Promise if available in the enviroment, you can
give a Promise constructor to be used on enviroment where there's no support - for example, old
broswers or node's 0.10 version. By default, `{%= varname %}` will use and include [bluebird][] on old enviroments,
as it is the fastest implementation of Promises. So, you are able to give Promise constructor, but
it won't be used in modern enviroments - it always will use native Promise, you can't trick that. You
can't give custom promise implementation to be used in any enviroment.

**Example**

```js
var fs = require('fs')
var {%= varname %} = require('{%= varname %}')

{%= varname %}.Promise = require('q') // using `Q` promise on node 0.10
var readFile = {%= varname %}.promisify(fs.readFile)

readFile('package.json', 'utf8')
  .then(console.log, err => {
    console.error(err.stack)
  })
```

One way to pass a custom Promise constructor is as shown above. But the other way is passing it to `.Promise` of the promisified function, like that

```js
var fs = require('fs')
var {%= varname %} = require('{%= varname %}')
var statFile = {%= varname %}.promisify(fs.stat)

statFile.Promise = require('when') // using `when` promise on node 0.10
statFile('package.json').then(console.log, console.error)
```

One more thing, is that you can access the used Promise and can detect what promise is used. It is easy, just as `promise.Promise` and you'll get it.
Or look for `promise.___bluebirdPromise` and `promise.___customPromise` properties. `.___bluebirdPromise` (yea, with three underscores in front) will be true if enviroment is old and you didn't provide promise constructor to `.Promise`.
So, when you give constructor `.__customPromise` will be true and `.___bluebirdPromise` will be false.

```js
var fs = require('fs')
var {%= varname %} = require('{%= varname %}')

var promise = {%= varname %}(fs.readFile, 'package.json', 'utf8')
promise.then(JSON.parse).then(function (val) {
  console.log(val.name) // => '{%= varname %}'
}, console.error)

console.log(promise.Promise) // => used Promise constructor
console.log(promise.___bluebirdPromise) // => `true` on old env, falsey otherwise
console.log(promise.___customPromise) // => `true` when pass `.Promise`, falsey otherwise
```

## Examples
> Few working examples with what can be passed and how `{%= varname %}` acts.

- Callback functions
- Generator functions
- JSON.stringify
- Synchronous functions
- Exceptions and rejections
- Returning errors
- Passing function as last argument

### Callback functions
> Can accept asynchronous (callback) functions as well.

**Example**

```js
const fs = require('fs')
const {%= varname %} = require('{%= varname %}')

{%= varname %}(fs.readFile, 'package.json', 'utf8')
  .then(JSON.parse)
  .then(data => {
    console.log(data.name) // => '{%= varname %}'
  }, err => {
    console.error(err.stack)
  })

// callback `fs.stat` function
{%= varname %}(fs.stat, 'package.json')
  .then(stats => {
    console.log(stats.isFile()) // => true
  }, err => {
    console.error(err.stack)
  })
```

### Generator functions
> Accept generator functions same as `co` and acts like [`co@4`](https://github.com/tj/co).

**Example**

```js
const fs = require('fs')
const {%= varname %} = require('{%= varname %}')

{%= varname %}(function * (filepath) {
  return yield {%= varname %}(fs.readFile, filepath, 'utf8')
}, 'package.json')
  .then(JSON.parse)
  .then(data => {
    console.log(data.name) // => '{%= varname %}'
  }, err => {
    console.error(err.stack)
  })
```

### JSON.stringify
> Specific use-case which shows correct handling of optional arguments.

```js
const {%= varname %} = require('{%= varname %}')

{%= varname %}(JSON.stringify, { foo: 'bar' })
  .then(data => {
    console.log(data) // => {"foo":"bar"}
  }, console.error)

// result with identation
{%= varname %}(JSON.stringify, {foo: 'bar'}, null, 2)
  .then(data => {
    console.log(data)
    // =>
    // {
    //   "foo": "bar"
    // }
  }, console.error)
```

### Synchronous functions
> Again, showing correct handling of optinal arguments using native `fs` module.

```js
const fs = require('fs')
const {%= varname %} = require('{%= varname %}')

// sync function
{%= varname %}(fs.statSync, 'package.json')
  .then(stats => {
    console.log(stats.isFile()) // => true
  })
  .catch(err => console.error(err.stack))

// correct handling of optional arguments
{%= varname %}(fs.readFileSync, 'package.json')
  .then(buf => {
    console.log(Buffer.isBuffer(buf)) // => true
  })
  .catch(err => {
    console.error(err.stack)
  })
```

### Exceptions and rejections
> Handles `uncaughtException` and `unhandledRejection` by default.

**Example**

```js
const fs = require('fs')
const {%= varname %} = require('{%= varname %}')

{%= varname %}(fs.readFile, 'foobar.json')
  .then(console.log, err => {
    console.error(err.code) // => 'ENOENT'
  })

// handles ReferenceError,
// SyntaxError and etc
const promise = {%= varname %}(function () {
  foo
  return true
})

promise.catch(err => {
  console.error(err) // => 'ReferenceError: foo is not defined'
})
```

### Returning errors
> You should **notice** that if some function **returns** instance of `Error` it will acts as usual - receive it in `.then` not in `.catch`. Review the `examples/errors.js` example.

**Example**

```js
const {%= varname %} = require('{%= varname %}')

const promise = {%= varname %}(function () {
  return new Error('foo err bar')
})

promise.then(errorAsResultValue => {
  console.log(errorAsResultValue instanceof Error) // => true
  console.log(errorAsResultValue.message) // => 'foo err bar'
})
```

### Passing function as last argument
> You can also pass normal (non-callback) function as last argument without problem. It won't be assumed as callback, until you name it or have argument with some of [common-callback-names][].

**Example**

```js
const assert = require('assert')
const {%= varname %} = require('{%= varname %}')

function regular (str, num, obj, fn) {
  assert.strictEqual(str, 'foo')
  assert.strictEqual(num, 123)
  assert.deepEqual(obj, { a: 'b' })
  assert.strictEqual(typeof str, 'string')
  assert.strictEqual(typeof num, 'number')
  assert.strictEqual(typeof obj, 'object')
  assert.strictEqual(typeof fn, 'function')
  return obj
}

{%= varname %}(regular, 'foo', 123, {a: 'b'}, function someFn () {})
  .then(result => {
    console.log(result) // => { a: 'b' }
  })
```

{% if (verb.related && verb.related.list && verb.related.list.length) { %}
## Related
{%= related(verb.related.list, {words: 12}) %}
{% } %}

## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/{%= repository %}/issues/new).
But before doing anything, please read the [CONTRIBUTING.md](./CONTRIBUTING.md) guidelines.

## [Charlike Make Reagent](http://j.mp/1stW47C) [![new message to charlike][new-message-img]][new-message-url] [![freenode #charlike][freenode-img]][freenode-url]

[![{%= author.username %}.tk][author-www-img]][author-www-url] [![keybase {%= author.username %}][keybase-img]][keybase-url] [![{%= author.username %} npm][author-npm-img]][author-npm-url] [![{%= author.username %} twitter][author-twitter-img]][author-twitter-url] [![{%= author.username %} github][author-github-img]][author-github-url]

{%= reflinks(verb.reflinks) %}

[npmjs-url]: https://www.npmjs.com/package/{%= name %}
[npmjs-img]: https://img.shields.io/npm/v/{%= name %}.svg?label={%= name %}

[license-url]: https://github.com/{%= repository %}/blob/master/LICENSE
[license-img]: https://img.shields.io/npm/l/{%= name %}.svg

[downloads-url]: https://www.npmjs.com/package/{%= name %}
[downloads-img]: https://img.shields.io/npm/dm/{%= name %}.svg

[codeclimate-url]: https://codeclimate.com/github/{%= repository %}
[codeclimate-img]: https://img.shields.io/codeclimate/github/{%= repository %}.svg

[travis-url]: https://travis-ci.org/{%= repository %}
[travis-img]: https://img.shields.io/travis/{%= repository %}/master.svg

[coveralls-url]: https://coveralls.io/r/{%= repository %}
[coveralls-img]: https://img.shields.io/coveralls/{%= repository %}.svg

[david-url]: https://david-dm.org/{%= repository %}
[david-img]: https://img.shields.io/david/{%= repository %}.svg

[standard-url]: https://github.com/feross/standard
[standard-img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg

[author-www-url]: http://www.{%= author.username.toLowerCase() %}.tk
[author-www-img]: https://img.shields.io/badge/www-{%= author.username.toLowerCase() %}.tk-fe7d37.svg

[keybase-url]: https://keybase.io/{%= author.username.toLowerCase() %}
[keybase-img]: https://img.shields.io/badge/keybase-{%= author.username.toLowerCase() %}-8a7967.svg

[author-npm-url]: https://www.npmjs.com/~{%= author.username.toLowerCase() %}
[author-npm-img]: https://img.shields.io/badge/npm-~{%= author.username.toLowerCase() %}-cb3837.svg

[author-twitter-url]: https://twitter.com/{%= author.username %}
[author-twitter-img]: https://img.shields.io/badge/twitter-@{%= author.username %}-55acee.svg

[author-github-url]: https://github.com/{%= author.username %}
[author-github-img]: https://img.shields.io/badge/github-@{%= author.username %}-4183c4.svg

[freenode-url]: http://webchat.freenode.net/?channels=charlike
[freenode-img]: https://img.shields.io/badge/freenode-%23charlike-5654a4.svg

[new-message-url]: https://github.com/{%= author.username %}/ama
[new-message-img]: https://img.shields.io/badge/ask%20me-anything-green.svg


text:
<?xml version="1.0" encoding="windows_1255"?>
<!--
SkipUnless:  __import__('codecs').lookup('windows_1255')
Description: \x80 character in windows_1255 encoding
Expect:      not bozo and feed['title'] == u'\u20ac'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<title>€</title>
</feed>


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

<title>SocketChannelIOHelper</title>
<meta name="date" content="2014-06-19">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.java_websocket

Class SocketChannelIOHelper

java.lang.Object

org.java_websocket.SocketChannelIOHelper

public class SocketChannelIOHelper
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

SocketChannelIOHelper()

Method Summary

Methods

Modifier and Type
Method and Description

static boolean
batch(WebSocketImpl ws,
     java.nio.channels.ByteChannel sockchannel)

Returns whether the whole outQueue has been flushed

static boolean
read(java.nio.ByteBuffer buf,
    WebSocketImpl ws,
    java.nio.channels.ByteChannel channel)

static boolean
readMore(java.nio.ByteBuffer buf,
        WebSocketImpl ws,
        WrappedByteChannel channel)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SocketChannelIOHelper

public SocketChannelIOHelper()

Method Detail

read

public static boolean read(java.nio.ByteBuffer buf,
           WebSocketImpl ws,
           java.nio.channels.ByteChannel channel)
                    throws java.io.IOException

Throws:

java.io.IOException

readMore

public static boolean readMore(java.nio.ByteBuffer buf,
               WebSocketImpl ws,
               WrappedByteChannel channel)
                        throws java.io.IOException

Returns:

returns whether there is more data left which can be obtained via readMore(ByteBuffer, WebSocketImpl, WrappedByteChannel)

Throws:

java.io.IOException

See Also:

WrappedByteChannel.readMore(ByteBuffer)

batch

public static boolean batch(WebSocketImpl ws,
            java.nio.channels.ByteChannel sockchannel)
                     throws java.io.IOException

Returns whether the whole outQueue has been flushed

Throws:

java.io.IOException

Overview

Package

Class

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD