text:
package net

import (
	"errors"
	"io"
	"os"
	"runtime"
	"sync"
	"syscall"
	"time"
	"unsafe"
)

var (
	initErr error
	ioSync  uint64
)

// CancelIo Windows API cancels all outstanding IO for a particular
// socket on current thread. To overcome that limitation, we run
// special goroutine, locked to OS single thread, that both starts
// and cancels IO. It means, there are 2 unavoidable thread switches
// for every IO.
// Some newer versions of Windows has new CancelIoEx API, that does
// not have that limitation and can be used from any thread. This
// package uses CancelIoEx API, if present, otherwise it fallback
// to CancelIo.

var (
	canCancelIO                               bool // determines if CancelIoEx API is present
	skipSyncNotif                             bool
	hasLoadSetFileCompletionNotificationModes bool
)

func sysInit() {
	var d syscall.WSAData
	e := syscall.WSAStartup(uint32(0x202), &d)
	if e != nil {
		initErr = os.NewSyscallError("WSAStartup", e)
	}
	canCancelIO = syscall.LoadCancelIoEx() == nil
	if syscall.LoadGetAddrInfo() == nil {
		lookupPort = newLookupPort
		lookupIP = newLookupIP
	}

	hasLoadSetFileCompletionNotificationModes = syscall.LoadSetFileCompletionNotificationModes() == nil
	if hasLoadSetFileCompletionNotificationModes {
		// It's not safe to use FILE_SKIP_COMPLETION_PORT_ON_SUCCESS if non IFS providers are installed:
		// http://support.microsoft.com/kb/2568167
		skipSyncNotif = true
		protos := [2]int32{syscall.IPPROTO_TCP, 0}
		var buf [32]syscall.WSAProtocolInfo
		len := uint32(unsafe.Sizeof(buf))
		n, err := syscall.WSAEnumProtocols(&protos[0], &buf[0], &len)
		if err != nil {
			skipSyncNotif = false
		} else {
			for i := int32(0); i < n; i++ {
				if buf[i].ServiceFlags1&syscall.XP1_IFS_HANDLES == 0 {
					skipSyncNotif = false
					break
				}
			}
		}
	}
}

func closesocket(s syscall.Handle) error {
	return syscall.Closesocket(s)
}

func canUseConnectEx(net string) bool {
	switch net {
	case "udp", "udp4", "udp6", "ip", "ip4", "ip6":
		// ConnectEx windows API does not support connectionless sockets.
		return false
	}
	return syscall.LoadConnectEx() == nil
}

func dial(net string, ra Addr, dialer func(time.Time) (Conn, error), deadline time.Time) (Conn, error) {
	if !canUseConnectEx(net) {
		// Use the relatively inefficient goroutine-racing
		// implementation of DialTimeout.
		return dialChannel(net, ra, dialer, deadline)
	}
	return dialer(deadline)
}

// operation contains superset of data necessary to perform all async IO.
type operation struct {
	// Used by IOCP interface, it must be first field
	// of the struct, as our code rely on it.
	o syscall.Overlapped

	// fields used by runtime.netpoll
	runtimeCtx uintptr
	mode       int32
	errno      int32
	qty        uint32

	// fields used only by net package
	fd     *netFD
	errc   chan error
	buf    syscall.WSABuf
	sa     syscall.Sockaddr
	rsa    *syscall.RawSockaddrAny
	rsan   int32
	handle syscall.Handle
	flags  uint32
}

func (o *operation) InitBuf(buf []byte) {
	o.buf.Len = uint32(len(buf))
	o.buf.Buf = nil
	if len(buf) != 0 {
		o.buf.Buf = &buf[0]
	}
}

// ioSrv executes net IO requests.
type ioSrv struct {
	req chan ioSrvReq
}

type ioSrvReq struct {
	o      *operation
	submit func(o *operation) error // if nil, cancel the operation
}

// ProcessRemoteIO will execute submit IO requests on behalf
// of other goroutines, all on a single os thread, so it can
// cancel them later. Results of all operations will be sent
// back to their requesters via channel supplied in request.
// It is used only when the CancelIoEx API is unavailable.
func (s *ioSrv) ProcessRemoteIO() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	for r := range s.req {
		if r.submit != nil {
			r.o.errc <- r.submit(r.o)
		} else {
			r.o.errc <- syscall.CancelIo(r.o.fd.sysfd)
		}
	}
}

// ExecIO executes a single IO operation o. It submits and cancels
// IO in the current thread for systems where Windows CancelIoEx API
// is available. Alternatively, it passes the request onto
// runtime netpoll and waits for completion or cancels request.
func (s *ioSrv) ExecIO(o *operation, name string, submit func(o *operation) error) (int, error) {
	fd := o.fd
	// Notify runtime netpoll about starting IO.
	err := fd.pd.Prepare(int(o.mode))
	if err != nil {
		return 0, &OpError{name, fd.net, fd.laddr, err}
	}
	// Start IO.
	if canCancelIO {
		err = submit(o)
	} else {
		// Send request to a special dedicated thread,
		// so it can stop the IO with CancelIO later.
		s.req <- ioSrvReq{o, submit}
		err = <-o.errc
	}
	switch err {
	case nil:
		// IO completed immediately
		if o.fd.skipSyncNotif {
			// No completion message will follow, so return immediately.
			return int(o.qty), nil
		}
		// Need to get our completion message anyway.
	case syscall.ERROR_IO_PENDING:
		// IO started, and we have to wait for its completion.
		err = nil
	default:
		return 0, &OpError{name, fd.net, fd.laddr, err}
	}
	// Wait for our request to complete.
	err = fd.pd.Wait(int(o.mode))
	if err == nil {
		// All is good. Extract our IO results and return.
		if o.errno != 0 {
			err = syscall.Errno(o.errno)
			return 0, &OpError{name, fd.net, fd.laddr, err}
		}
		return int(o.qty), nil
	}
	// IO is interrupted by "close" or "timeout"
	netpollErr := err
	switch netpollErr {
	case errClosing, errTimeout:
		// will deal with those.
	default:
		panic("net: unexpected runtime.netpoll error: " + netpollErr.Error())
	}
	// Cancel our request.
	if canCancelIO {
		err := syscall.CancelIoEx(fd.sysfd, &o.o)
		// Assuming ERROR_NOT_FOUND is returned, if IO is completed.
		if err != nil && err != syscall.ERROR_NOT_FOUND {
			// TODO(brainman): maybe do something else, but panic.
			panic(err)
		}
	} else {
		s.req <- ioSrvReq{o, nil}
		<-o.errc
	}
	// Wait for cancellation to complete.
	fd.pd.WaitCanceled(int(o.mode))
	if o.errno != 0 {
		err = syscall.Errno(o.errno)
		if err == syscall.ERROR_OPERATION_ABORTED { // IO Canceled
			err = netpollErr
		}
		return 0, &OpError{name, fd.net, fd.laddr, err}
	}
	// We issued cancellation request. But, it seems, IO operation succeeded
	// before cancellation request run. We need to treat IO operation as
	// succeeded (the bytes are actually sent/recv from network).
	return int(o.qty), nil
}

// Start helper goroutines.
var rsrv, wsrv *ioSrv
var onceStartServer sync.Once

func startServer() {
	rsrv = new(ioSrv)
	wsrv = new(ioSrv)
	if !canCancelIO {
		// Only CancelIo API is available. Lets start two special goroutines
		// locked to an OS thread, that both starts and cancels IO. One will
		// process read requests, while other will do writes.
		rsrv.req = make(chan ioSrvReq)
		go rsrv.ProcessRemoteIO()
		wsrv.req = make(chan ioSrvReq)
		go wsrv.ProcessRemoteIO()
	}
}

// Network file descriptor.
type netFD struct {
	// locking/lifetime of sysfd + serialize access to Read and Write methods
	fdmu fdMutex

	// immutable until Close
	sysfd         syscall.Handle
	family        int
	sotype        int
	isConnected   bool
	skipSyncNotif bool
	net           string
	laddr         Addr
	raddr         Addr

	rop operation // read operation
	wop operation // write operation

	// wait server
	pd pollDesc
}

func newFD(sysfd syscall.Handle, family, sotype int, net string) (*netFD, error) {
	if initErr != nil {
		return nil, initErr
	}
	onceStartServer.Do(startServer)
	return &netFD{sysfd: sysfd, family: family, sotype: sotype, net: net}, nil
}

func (fd *netFD) init() error {
	if err := fd.pd.Init(fd); err != nil {
		return err
	}
	if hasLoadSetFileCompletionNotificationModes {
		// We do not use events, so we can skip them always.
		flags := uint8(syscall.FILE_SKIP_SET_EVENT_ON_HANDLE)
		// It's not safe to skip completion notifications for UDP:
		// http://blogs.technet.com/b/winserverperformance/archive/2008/06/26/designing-applications-for-high-performance-part-iii.aspx
		if skipSyncNotif && fd.net == "tcp" {
			flags |= syscall.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
		}
		err := syscall.SetFileCompletionNotificationModes(fd.sysfd, flags)
		if err == nil && flags&syscall.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS != 0 {
			fd.skipSyncNotif = true
		}
	}
	fd.rop.mode = 'r'
	fd.wop.mode = 'w'
	fd.rop.fd = fd
	fd.wop.fd = fd
	fd.rop.runtimeCtx = fd.pd.runtimeCtx
	fd.wop.runtimeCtx = fd.pd.runtimeCtx
	if !canCancelIO {
		fd.rop.errc = make(chan error)
		fd.wop.errc = make(chan error)
	}
	return nil
}

func (fd *netFD) setAddr(laddr, raddr Addr) {
	fd.laddr = laddr
	fd.raddr = raddr
	runtime.SetFinalizer(fd, (*netFD).Close)
}

func (fd *netFD) connect(la, ra syscall.Sockaddr, deadline time.Time) error {
	// Do not need to call fd.writeLock here,
	// because fd is not yet accessible to user,
	// so no concurrent operations are possible.
	if err := fd.init(); err != nil {
		return err
	}
	if !deadline.IsZero() {
		fd.setWriteDeadline(deadline)
		defer fd.setWriteDeadline(noDeadline)
	}
	if !canUseConnectEx(fd.net) {
		return syscall.Connect(fd.sysfd, ra)
	}
	// ConnectEx windows API requires an unconnected, previously bound socket.
	if la == nil {
		switch ra.(type) {
		case *syscall.SockaddrInet4:
			la = &syscall.SockaddrInet4{}
		case *syscall.SockaddrInet6:
			la = &syscall.SockaddrInet6{}
		default:
			panic("unexpected type in connect")
		}
		if err := syscall.Bind(fd.sysfd, la); err != nil {
			return err
		}
	}
	// Call ConnectEx API.
	o := &fd.wop
	o.sa = ra
	_, err := wsrv.ExecIO(o, "ConnectEx", func(o *operation) error {
		return syscall.ConnectEx(o.fd.sysfd, o.sa, nil, 0, nil, &o.o)
	})
	if err != nil {
		return err
	}
	// Refresh socket properties.
	return syscall.Setsockopt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_UPDATE_CONNECT_CONTEXT, (*byte)(unsafe.Pointer(&fd.sysfd)), int32(unsafe.Sizeof(fd.sysfd)))
}

func (fd *netFD) destroy() {
	if fd.sysfd == syscall.InvalidHandle {
		return
	}
	// Poller may want to unregister fd in readiness notification mechanism,
	// so this must be executed before closesocket.
	fd.pd.Close()
	closesocket(fd.sysfd)
	fd.sysfd = syscall.InvalidHandle
	// no need for a finalizer anymore
	runtime.SetFinalizer(fd, nil)
}

// Add a reference to this fd.
// Returns an error if the fd cannot be used.
func (fd *netFD) incref() error {
	if !fd.fdmu.Incref() {
		return errClosing
	}
	return nil
}

// Remove a reference to this FD and close if we've been asked to do so
// (and there are no references left).
func (fd *netFD) decref() {
	if fd.fdmu.Decref() {
		fd.destroy()
	}
}

// Add a reference to this fd and lock for reading.
// Returns an error if the fd cannot be used.
func (fd *netFD) readLock() error {
	if !fd.fdmu.RWLock(true) {
		return errClosing
	}
	return nil
}

// Unlock for reading and remove a reference to this FD.
func (fd *netFD) readUnlock() {
	if fd.fdmu.RWUnlock(true) {
		fd.destroy()
	}
}

// Add a reference to this fd and lock for writing.
// Returns an error if the fd cannot be used.
func (fd *netFD) writeLock() error {
	if !fd.fdmu.RWLock(false) {
		return errClosing
	}
	return nil
}

// Unlock for writing and remove a reference to this FD.
func (fd *netFD) writeUnlock() {
	if fd.fdmu.RWUnlock(false) {
		fd.destroy()
	}
}

func (fd *netFD) Close() error {
	if !fd.fdmu.IncrefAndClose() {
		return errClosing
	}
	// unblock pending reader and writer
	fd.pd.Evict()
	fd.decref()
	return nil
}

func (fd *netFD) shutdown(how int) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	err := syscall.Shutdown(fd.sysfd, how)
	if err != nil {
		return &OpError{"shutdown", fd.net, fd.laddr, err}
	}
	return nil
}

func (fd *netFD) closeRead() error {
	return fd.shutdown(syscall.SHUT_RD)
}

func (fd *netFD) closeWrite() error {
	return fd.shutdown(syscall.SHUT_WR)
}

func (fd *netFD) Read(buf []byte) (int, error) {
	if err := fd.readLock(); err != nil {
		return 0, err
	}
	defer fd.readUnlock()
	o := &fd.rop
	o.InitBuf(buf)
	n, err := rsrv.ExecIO(o, "WSARecv", func(o *operation) error {
		return syscall.WSARecv(o.fd.sysfd, &o.buf, 1, &o.qty, &o.flags, &o.o, nil)
	})
	if err == nil && n == 0 {
		err = io.EOF
	}
	if raceenabled {
		raceAcquire(unsafe.Pointer(&ioSync))
	}
	return n, err
}

func (fd *netFD) readFrom(buf []byte) (n int, sa syscall.Sockaddr, err error) {
	if len(buf) == 0 {
		return 0, nil, nil
	}
	if err := fd.readLock(); err != nil {
		return 0, nil, err
	}
	defer fd.readUnlock()
	o := &fd.rop
	o.InitBuf(buf)
	n, err = rsrv.ExecIO(o, "WSARecvFrom", func(o *operation) error {
		if o.rsa == nil {
			o.rsa = new(syscall.RawSockaddrAny)
		}
		o.rsan = int32(unsafe.Sizeof(*o.rsa))
		return syscall.WSARecvFrom(o.fd.sysfd, &o.buf, 1, &o.qty, &o.flags, o.rsa, &o.rsan, &o.o, nil)
	})
	if err != nil {
		return 0, nil, err
	}
	sa, _ = o.rsa.Sockaddr()
	return
}

func (fd *netFD) Write(buf []byte) (int, error) {
	if err := fd.writeLock(); err != nil {
		return 0, err
	}
	defer fd.writeUnlock()
	if raceenabled {
		raceReleaseMerge(unsafe.Pointer(&ioSync))
	}
	o := &fd.wop
	o.InitBuf(buf)
	return wsrv.ExecIO(o, "WSASend", func(o *operation) error {
		return syscall.WSASend(o.fd.sysfd, &o.buf, 1, &o.qty, 0, &o.o, nil)
	})
}

func (fd *netFD) writeTo(buf []byte, sa syscall.Sockaddr) (int, error) {
	if len(buf) == 0 {
		return 0, nil
	}
	if err := fd.writeLock(); err != nil {
		return 0, err
	}
	defer fd.writeUnlock()
	o := &fd.wop
	o.InitBuf(buf)
	o.sa = sa
	return wsrv.ExecIO(o, "WSASendto", func(o *operation) error {
		return syscall.WSASendto(o.fd.sysfd, &o.buf, 1, &o.qty, 0, o.sa, &o.o, nil)
	})
}

func (fd *netFD) acceptOne(toAddr func(syscall.Sockaddr) Addr, rawsa []syscall.RawSockaddrAny, o *operation) (*netFD, error) {
	// Get new socket.
	s, err := sysSocket(fd.family, fd.sotype, 0)
	if err != nil {
		return nil, &OpError{"socket", fd.net, fd.laddr, err}
	}

	// Associate our new socket with IOCP.
	netfd, err := newFD(s, fd.family, fd.sotype, fd.net)
	if err != nil {
		closesocket(s)
		return nil, &OpError{"accept", fd.net, fd.laddr, err}
	}
	if err := netfd.init(); err != nil {
		fd.Close()
		return nil, err
	}

	// Submit accept request.
	o.handle = s
	o.rsan = int32(unsafe.Sizeof(rawsa[0]))
	_, err = rsrv.ExecIO(o, "AcceptEx", func(o *operation) error {
		return syscall.AcceptEx(o.fd.sysfd, o.handle, (*byte)(unsafe.Pointer(&rawsa[0])), 0, uint32(o.rsan), uint32(o.rsan), &o.qty, &o.o)
	})
	if err != nil {
		netfd.Close()
		return nil, err
	}

	// Inherit properties of the listening socket.
	err = syscall.Setsockopt(s, syscall.SOL_SOCKET, syscall.SO_UPDATE_ACCEPT_CONTEXT, (*byte)(unsafe.Pointer(&fd.sysfd)), int32(unsafe.Sizeof(fd.sysfd)))
	if err != nil {
		netfd.Close()
		return nil, &OpError{"Setsockopt", fd.net, fd.laddr, err}
	}

	return netfd, nil
}

func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (*netFD, error) {
	if err := fd.readLock(); err != nil {
		return nil, err
	}
	defer fd.readUnlock()

	o := &fd.rop
	var netfd *netFD
	var err error
	var rawsa [2]syscall.RawSockaddrAny
	for {
		netfd, err = fd.acceptOne(toAddr, rawsa[:], o)
		if err == nil {
			break
		}
		// Sometimes we see WSAECONNRESET and ERROR_NETNAME_DELETED is
		// returned here. These happen if connection reset is received
		// before AcceptEx could complete. These errors relate to new
		// connection, not to AcceptEx, so ignore broken connection and
		// try AcceptEx again for more connections.
		operr, ok := err.(*OpError)
		if !ok {
			return nil, err
		}
		errno, ok := operr.Err.(syscall.Errno)
		if !ok {
			return nil, err
		}
		switch errno {
		case syscall.ERROR_NETNAME_DELETED, syscall.WSAECONNRESET:
			// ignore these and try again
		default:
			return nil, err
		}
	}

	// Get local and peer addr out of AcceptEx buffer.
	var lrsa, rrsa *syscall.RawSockaddrAny
	var llen, rlen int32
	syscall.GetAcceptExSockaddrs((*byte)(unsafe.Pointer(&rawsa[0])),
		0, uint32(o.rsan), uint32(o.rsan), &lrsa, &llen, &rrsa, &rlen)
	lsa, _ := lrsa.Sockaddr()
	rsa, _ := rrsa.Sockaddr()

	netfd.setAddr(toAddr(lsa), toAddr(rsa))
	return netfd, nil
}

func skipRawSocketTests() (skip bool, skipmsg string, err error) {
	// From http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548.aspx:
	// Note: To use a socket of type SOCK_RAW requires administrative privileges.
	// Users running Winsock applications that use raw sockets must be a member of
	// the Administrators group on the local computer, otherwise raw socket calls
	// will fail with an error code of WSAEACCES. On Windows Vista and later, access
	// for raw sockets is enforced at socket creation. In earlier versions of Windows,
	// access for raw sockets is enforced during other socket operations.
	s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, 0)
	if err == syscall.WSAEACCES {
		return true, "skipping test; no access to raw socket allowed", nil
	}
	if err != nil {
		return true, "", err
	}
	defer syscall.Closesocket(s)
	return false, "", nil
}

// Unimplemented functions.

func (fd *netFD) dup() (*os.File, error) {
	// TODO: Implement this
	return nil, os.NewSyscallError("dup", syscall.EWINDOWS)
}

var errNoSupport = errors.New("address family not supported")

func (fd *netFD) readMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error) {
	return 0, 0, 0, nil, errNoSupport
}

func (fd *netFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) {
	return 0, 0, errNoSupport
}


text:
package uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.view.ViewGroup;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import uk.co.samuelwall.materialtaptargetprompt.UnitTestUtils;
import uk.co.samuelwall.materialtaptargetprompt.extras.PromptFocal;
import uk.co.samuelwall.materialtaptargetprompt.extras.PromptOptions;
import uk.co.samuelwall.materialtaptargetprompt.extras.TestPromptText;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.LOLLIPOP_MR1)
public class RectanglePromptBackgroundUnitTest
{
    private PromptOptions createOptions(Rect clipBounds, RectF focalBounds)
    {
        final PromptOptions options = UnitTestUtils.createPromptOptionsWithTestResourceFinder();
        final ViewGroup parentView = options.getResourceFinder().getPromptParentView();
        when(parentView.getWidth()).thenReturn(clipBounds.width());
        when(parentView.getRight()).thenReturn(clipBounds.right);
        when(parentView.getLeft()).thenReturn(clipBounds.left);
        options.load(-1);
        final RectanglePromptBackground promptBackground = new RectanglePromptBackground();
        promptBackground.setColour(Color.YELLOW);
        promptBackground.setCornerRadius(12, 14);
        options.setPromptBackground(promptBackground);
        options.setPromptFocal(mock(PromptFocal.class));
        when(options.getPromptFocal().getBounds()).thenReturn(focalBounds);
        options.setPromptText(new TestPromptText(300f));
        options.setPrimaryText("Primary Text");
        options.setSecondaryText("Secondary Text");
        options.setFocalPadding(20f);
        options.setTextPadding(20f);
        options.setMaxTextWidth(300f);
        options.setTextSeparation(20f);

        options.create();

        options.getPromptText().prepare(options, false, clipBounds);
        options.getPromptText().update(options, 1, 1);
        return options;
    }

    @Test
    public void testRectanglePromptBackground_Top_Left()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(1036, 1876, 1080, 1920);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(760, 1436, 1060, 1856), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(1058, promptBackground.mBounds.left, 1);
        assertEquals(1898, promptBackground.mBounds.top, 1);
        assertEquals(1058, promptBackground.mBounds.right, 1);
        assertEquals(1898, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(899, promptBackground.mBounds.left, 1);
        assertEquals(1657, promptBackground.mBounds.top, 1);
        assertEquals(1079, promptBackground.mBounds.right, 1);
        assertEquals(1919, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(1058, 1898));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(740, promptBackground.mBounds.left, 1);
        assertEquals(1416, promptBackground.mBounds.top, 1);
        assertEquals(1100, promptBackground.mBounds.right, 1);
        assertEquals(1940, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(1058, 1898));
        assertFalse(promptBackground.contains(200, 22));
    }

    @Test
    public void testRectanglePromptBackground_Top_Right()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(0, 1876, 44, 1920);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(20, 1436, 320, 1856), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(22, 1898));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(22, promptBackground.mBounds.left, 1);
        assertEquals(1898, promptBackground.mBounds.top, 1);
        assertEquals(22, promptBackground.mBounds.right, 1);
        assertEquals(1898, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(22, 1898));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(1, promptBackground.mBounds.left, 1);
        assertEquals(1657, promptBackground.mBounds.top, 1);
        assertEquals(181, promptBackground.mBounds.right, 1);
        assertEquals(1919, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(22, 1898));
        assertFalse(promptBackground.contains(22, 700));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(1416, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1940, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(-20, promptBackground.mBounds.left, 1);
        assertEquals(1416, promptBackground.mBounds.top, 1);
        assertEquals(340, promptBackground.mBounds.right, 1);
        assertEquals(1940, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(22, 1898));
        assertFalse(promptBackground.contains(22, 600));
    }

    @Test
    public void testRectanglePromptBackground_Bottom_Left()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(1036, 0, 1080, 44);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(760, 64, 1060, 484), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(1058, promptBackground.mBounds.left, 1);
        assertEquals(22, promptBackground.mBounds.top, 1);
        assertEquals(1058, promptBackground.mBounds.right, 1);
        assertEquals(22, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(899, promptBackground.mBounds.left, 1);
        assertEquals(1, promptBackground.mBounds.top, 1);
        assertEquals(1079, promptBackground.mBounds.right, 1);
        assertEquals(263, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(1058, 22));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(740, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(1100, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(740, promptBackground.mBounds.left, 1);
        assertEquals(-20, promptBackground.mBounds.top, 1);
        assertEquals(1100, promptBackground.mBounds.right, 1);
        assertEquals(504, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(1058, 22));
        assertFalse(promptBackground.contains(200, 22));
    }

    @Test
    public void testRectanglePromptBackground_Bottom_Right()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(0, 0, 44, 44);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(20, 64, 320, 484), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(22, promptBackground.mBounds.left, 1);
        assertEquals(22, promptBackground.mBounds.top, 1);
        assertEquals(22, promptBackground.mBounds.right, 1);
        assertEquals(22, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(1, promptBackground.mBounds.left, 1);
        assertEquals(1, promptBackground.mBounds.top, 1);
        assertEquals(181, promptBackground.mBounds.right, 1);
        assertEquals(263, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(22, 22));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(-20, promptBackground.mBaseBounds.left, 1);
        assertEquals(-20, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(504, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(-20, promptBackground.mBounds.left, 1);
        assertEquals(-20, promptBackground.mBounds.top, 1);
        assertEquals(340, promptBackground.mBounds.right, 1);
        assertEquals(504, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(22, 22));
        assertFalse(promptBackground.contains(600, 22));
    }

    @Test
    public void testRectanglePromptBackground_Centre_Top_Left()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(948, 1788, 992, 1832);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(690, 1348, 990, 1768), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(970, promptBackground.mBounds.left, 1);
        assertEquals(1810, promptBackground.mBounds.top, 1);
        assertEquals(970, promptBackground.mBounds.right, 1);
        assertEquals(1810, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(820, promptBackground.mBounds.left, 1);
        assertEquals(1569, promptBackground.mBounds.top, 1);
        assertEquals(991, promptBackground.mBounds.right, 1);
        assertEquals(1831, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(840, 1600));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(670, promptBackground.mBounds.left, 1);
        assertEquals(1328, promptBackground.mBounds.top, 1);
        assertEquals(1012, promptBackground.mBounds.right, 1);
        assertEquals(1852, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(840, 1600));
        assertFalse(promptBackground.contains(200, 22));
    }

    @Test
    public void testRectanglePromptBackground_Centre_Top_Right()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(88, 1788, 132, 1832);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(20, 1348, 320, 1768), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(22, 1898));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(110, promptBackground.mBounds.left, 1);
        assertEquals(1810, promptBackground.mBounds.top, 1);
        assertEquals(110, promptBackground.mBounds.right, 1);
        assertEquals(1810, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(22, 1898));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(55, promptBackground.mBounds.left, 1);
        assertEquals(1569, promptBackground.mBounds.top, 1);
        assertEquals(225, promptBackground.mBounds.right, 1);
        assertEquals(1831, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(180, 1572));
        assertFalse(promptBackground.contains(22, 700));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(1328, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(1852, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(1328, promptBackground.mBounds.top, 1);
        assertEquals(340, promptBackground.mBounds.right, 1);
        assertEquals(1852, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(180, 1572));
        assertFalse(promptBackground.contains(22, 600));
    }

    @Test
    public void testRectanglePromptBackground_Centre_Bottom_Left()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(948, 88, 992, 132);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(690, 152, 990, 572), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(970, promptBackground.mBounds.left, 1);
        assertEquals(110, promptBackground.mBounds.top, 1);
        assertEquals(970, promptBackground.mBounds.right, 1);
        assertEquals(110, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(820, promptBackground.mBounds.left, 1);
        assertEquals(89, promptBackground.mBounds.top, 1);
        assertEquals(991, promptBackground.mBounds.right, 1);
        assertEquals(351, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(861, 333));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(670, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(1012, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(670, promptBackground.mBounds.left, 1);
        assertEquals(68, promptBackground.mBounds.top, 1);
        assertEquals(1012, promptBackground.mBounds.right, 1);
        assertEquals(592, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(861, 333));
        assertFalse(promptBackground.contains(200, 22));
    }

    @Test
    public void testRectanglePromptBackground_Centre_Bottom_Right()
    {
        final Canvas canvas = mock(Canvas.class);
        final Rect clipBounds = new Rect(0, 0, 1080, 1920);
        final RectF focalBounds = new RectF(88, 88, 132, 132);
        final PromptOptions options = createOptions(clipBounds, focalBounds);
        final RectanglePromptBackground promptBackground = (RectanglePromptBackground) options.getPromptBackground();
        assertEquals(new RectF(20, 152, 320, 572), options.getPromptText().getBounds());
        promptBackground.prepare(options, false, clipBounds);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(0, promptBackground.mBounds.top, 1);
        assertEquals(0, promptBackground.mBounds.right, 1);
        assertEquals(0, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0, 0);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(110, promptBackground.mBounds.left, 1);
        assertEquals(110, promptBackground.mBounds.top, 1);
        assertEquals(110, promptBackground.mBounds.right, 1);
        assertEquals(110, promptBackground.mBounds.bottom, 1);
        assertFalse(promptBackground.contains(1058, 22));
        promptBackground.update(options, 0.5f, 0.5f);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(55, promptBackground.mBounds.left, 1);
        assertEquals(89, promptBackground.mBounds.top, 1);
        assertEquals(225, promptBackground.mBounds.right, 1);
        assertEquals(351, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(110, 110));
        assertFalse(promptBackground.contains(700, 22));
        promptBackground.update(options, 1, 1);
        promptBackground.draw(canvas);
        assertEquals(0, promptBackground.mBaseBounds.left, 1);
        assertEquals(68, promptBackground.mBaseBounds.top, 1);
        assertEquals(340, promptBackground.mBaseBounds.right, 1);
        assertEquals(592, promptBackground.mBaseBounds.bottom, 1);
        assertEquals(0, promptBackground.mBounds.left, 1);
        assertEquals(68, promptBackground.mBounds.top, 1);
        assertEquals(340, promptBackground.mBounds.right, 1);
        assertEquals(592, promptBackground.mBounds.bottom, 1);
        assertTrue(promptBackground.contains(180, 336));
        assertFalse(promptBackground.contains(600, 22));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ensor.robots.os.api;

/**
 *
 * @author jona
 */
public interface IDevice {
    public <T> T getDevice(Class<T> aClass);
}


text:
module Clearance
  module Test
    module Functional
      module PasswordsControllerTest

        def self.included(controller_test)
          controller_test.class_eval do

            should_route :get, '/users/1/password/edit',
              :action  => 'edit', :user_id => '1'

            context "a user with confirmed email" do
              setup do
                @user = Factory(:email_confirmed_user)
                @user.confirm_email!
              end

              context "on GET to #new" do
                setup { get :new, :user_id => @user.to_param }

                should_respond_with :success
                should_render_template "new"
              end

              context "on POST to #create" do
                context "with correct email address" do
                  setup do
                    ActionMailer::Base.deliveries.clear
                    post :create, :password => { :email => @user.email }
                  end

                  should "generate a token for the change your password email" do
                    assert_not_nil @user.reload.token
                  end

                  should "send the change your password email" do
                    assert_sent_email do |email|
                      email.subject =~ /change your password/i
                    end
                  end

                  should_set_the_flash_to /password/i
                  should_redirect_to_url_after_create
                end

                context "with incorrect email address" do
                  setup do
                    email = "user1@example.com"
                    assert ! User.exists?(['email = ?', email])
                    ActionMailer::Base.deliveries.clear
                    assert_nil @user.reload.token

                    post :create, :password => { :email => email }
                  end

                  should "not generate a token for the change your password email" do
                    assert_nil @user.reload.token
                  end

                  should "not send a password reminder email" do
                    assert ActionMailer::Base.deliveries.empty?
                  end

                  should "set a :notice flash" do
                    assert_not_nil flash.now[:notice]
                  end

                  should_render_template :new
                end
              end
            end

            context "a user with confirmed email and forgotten password" do
              setup do
                @user = Factory(:email_confirmed_user)
                @user.forgot_password!
              end

              context "on GET to #edit with correct id and token" do
                setup do
                  get :edit, :user_id => @user.to_param, :token => @user.token
                end

                should "find the user" do
                  assert_equal @user, assigns(:user)
                end

                should_respond_with :success
                should_render_template "edit"
                should_display_a_password_update_form
              end

              should_forbid "on GET to #edit with correct id but blank token" do
                get :edit, :user_id => @user.to_param, :token => ""
              end

              should_forbid "on GET to #edit with correct id but no token" do
                get :edit, :user_id => @user.to_param
              end

              context "on PUT to #update with matching password and password confirmation" do
                setup do
                  new_password = "new_password"
                  @encrypted_new_password = @user.encrypt(new_password)
                  assert_not_equal @encrypted_new_password, @user.encrypted_password

                  put(:update,
                      :user_id  => @user,
                      :token    => @user.token,
                      :user     => {
                        :password              => new_password,
                        :password_confirmation => new_password
                      })
                  @user.reload
                end

                should "update password" do
                  assert_equal @encrypted_new_password, @user.encrypted_password
                end

                should "clear token" do
                  assert_nil @user.token
                end

                should_be_signed_in_as { @user }
                should_redirect_to_url_after_update
              end

              context "on PUT to #update with password but blank password confirmation" do
                setup do
                  new_password = "new_password"
                  @encrypted_new_password = @user.encrypt(new_password)

                  put(:update,
                      :user_id => @user.to_param,
                      :token   => @user.token,
                      :user    => {
                        :password => new_password,
                        :password_confirmation => ''
                      })
                  @user.reload
                end

                should "not update password" do
                  assert_not_equal @encrypted_new_password, @user.encrypted_password
                end

                should "not clear token" do
                  assert_not_nil @user.token
                end

                should_not_be_signed_in
                should_respond_with    :success
                should_render_template :edit

                should_display_a_password_update_form
              end

              should_forbid "on PUT to #update with id but no token" do
                put :update, :user_id => @user.to_param, :token => ""
              end
            end

            context "given two users and user one signs in" do
              setup do
                @user_one = Factory(:user)
                @user_two = Factory(:user)
                sign_in_as @user_one
              end

              should_forbid "when user one tries to change user two's password on GET with no token" do
                get :edit, :user_id => @user_two.to_param
              end
            end
          end
        end

      end
    end
  end
end


text:
@implementation Position

@end


text:
package com.mocircle.flowsample.flows.order;

import com.mocircle.flow.model.Token;
import com.mocircle.flow.model.action.ActionNode;

public class CheckOutTask extends ActionNode {

    @Override
    public Token execute() {
        return new Token(Token.TYPE_SUCCESS);
    }
}


text:
package org.hibersap.mapping;

import org.hibersap.annotations.Bapi;
import org.hibersap.annotations.Import;
import org.hibersap.annotations.Parameter;
import org.hibersap.annotations.Table;
import org.hibersap.mapping.model.BapiMapping;
import org.hibersap.mapping.model.FieldMapping;
import org.hibersap.mapping.model.TableMapping;
import org.junit.Test;

import java.util.Set;

import static org.fest.assertions.Assertions.assertThat;

public class AnnotationBapiMapperTest {

    private final AnnotationBapiMapper mapper = new AnnotationBapiMapper();

    @Test
    public void mapsBapiStructureWithInheritedField() {
        final BapiMapping mapping = mapper.mapBapi( TestBapiClass.class );

        final TableMapping tableMapping = mapping.getTableParameters().iterator().next();
        final Set<FieldMapping> parameters = tableMapping.getComponentParameter().getParameters();

        assertThat( parameters ).hasSize( 2 )
                                .onProperty( "javaName" ).contains( "structureParamSubClass", "structureParamSuperClass" );
    }

    @Test
    public void mapsTable() {
        final BapiMapping mapping = mapper.mapBapi( TestBapiClass.class );

        final Set<TableMapping> tableParams = mapping.getTableParameters();
        assertThat( tableParams ).hasSize( 1 );

        final TableMapping tableMapping = tableParams.iterator().next();
        assertThat( tableMapping.getAssociatedType().getName() ).isEqualTo( TestBapiStructureSubClass.class.getName() );
    }

    @Bapi( "test" )
    private class TestBapiClass {

        @Import
        @Parameter( "ABAP_FIELD" )
        @SuppressWarnings( "unused" )
        private int intParam;

        @Table
        @Parameter( "ABAP_TABLE" )
        @SuppressWarnings( "unused" )
        private Set<TestBapiStructureSubClass> tableParam;
    }

    private class TestBapiStructureSubClass extends TestBapiStructureSuperClass {

        @Parameter( "ABAP_FIELD" )
        @SuppressWarnings( "unused" )
        private long structureParamSubClass;
    }

    private class TestBapiStructureSuperClass {

        @Parameter( "ABAP_FIELD" )
        @SuppressWarnings( "unused" )
        private String structureParamSuperClass;
    }
}


text:
using System.Net;

using Cosmos.IL2CPU.Plugs;

namespace Cosmos.System.Plugs.System.Net
{
    [Plug(Target = typeof(SocketAddress))]
    public static class SocketAddressImpl
    {
        public static string ToString(SocketAddress aThis)
        {
            return "<SocketAddress.ToString() not yet plugged correctly!>";
        }
    }
}


text:
source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh"
trap os::test::junit::reconcile_output EXIT

# Cleanup cluster resources created by this test
(
  set +e
  oc delete all,templates --all
  exit 0
) &>/dev/null

os::test::junit::declare_suite_start "cmd/builds/setbuildhook"
# Validate the set build-hook command
arg="-f test/testdata/test-bc.yaml"
os::cmd::expect_failure_and_text "oc set build-hook" "error: one or more build configs"
os::cmd::expect_failure_and_text "oc set build-hook ${arg}" "error: you must specify a type of hook"
os::cmd::expect_failure_and_text "oc set build-hook ${arg} --local --post-commit -o yaml -- echo 'hello world'" 'you must specify either a script or command for the build hook'
os::cmd::expect_success_and_text "oc set build-hook ${arg} --local --post-commit --command -o yaml -- echo 'hello world'" 'command:'
os::cmd::expect_success_and_text "oc set build-hook ${arg} --local --post-commit -o yaml --script='echo \"hello world\"'" 'script: echo \"hello world\"'
# Server object tests
os::cmd::expect_success "oc create -f test/testdata/test-bc.yaml"
# Must specify --command or --script
os::cmd::expect_failure_and_text "oc set build-hook bc/test-buildconfig --post-commit" "you must specify either a script or command"
# Setting args for the default entrypoint is not supported
os::cmd::expect_failure_and_text "oc set build-hook test-buildconfig --post-commit -- foo bar" "you must specify either a script or command for the build hook"
# Set a command + args on a specific build config
os::cmd::expect_success_and_text "oc set build-hook bc/test-buildconfig --post-commit --command -- /bin/bash -c \"echo 'test'\"" "updated"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "command:"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "args:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "script:"
# Set a script on a specific build config
os::cmd::expect_success_and_text "oc set build-hook bc/test-buildconfig --post-commit --script /bin/script.sh -- arg1 arg2" "updated"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "script:"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "args:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "command:"
# Remove the postcommit hook
os::cmd::expect_success_and_text "oc set build-hook bc/test-buildconfig --post-commit --remove" "updated"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "args:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "command:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "script:"
# Set a command + args on all build configs
os::cmd::expect_success_and_text "oc set build-hook --all --post-commit --command -- /bin/bash -c \"echo 'test'\"" "updated"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "command:"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "args:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "script:"
# Set a script on all build configs
os::cmd::expect_success_and_text "oc set build-hook --all --post-commit --script /bin/script.sh" "updated"
os::cmd::expect_success_and_text "oc get bc/test-buildconfig -o yaml" "script:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "args:"
os::cmd::expect_success_and_not_text "oc get bc/test-buildconfig -o yaml" "command:"

os::cmd::expect_success "oc delete bc/test-buildconfig"
# ensure command behaves as expected when an empty file is given
workingdir=$(mktemp -d)
touch "${workingdir}/emptyfile.json"
os::cmd::expect_failure_and_text "oc set build-hook -f ${workingdir}/emptyfile.json --post-commit=true --script=foo" "no resources found"
echo "set build-hook: ok"
os::test::junit::declare_suite_end


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

namespace Caliburn.Micro.BindableAppBar
{
    public class PanoramaSceen : Screen
    {
        public override bool Equals(object obj)
        {
            if ((obj != null) && (obj.GetType() == typeof(PanoramaItem)))
            {
                var thePanoItem = (PanoramaItem)obj;

                return base.Equals(thePanoItem.Header);
            }
            else
            {
                return base.Equals(obj);
            }
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}


text:
@extends('admin::admin.index')

@section('topmenu')

        @include('admin::common.topmenu.list', ['routePrefix'=>$routePrefix])
        @if (isset($entities))
            @$entities[0]->id]) !!}">
                 @lang('admin::admin.add')

        @endif

@endsection

@section('content')
    @include('admin::common.errors')
    @if (count($entities) > 0)

                    @lang('tree::admin.title_short')
                    @lang('tree::admin.slug_short')
                    Модуль
                    @lang('admin::fields.priority')
                    @lang('admin::admin.control')

            @foreach ($entities as $entity)

active) class="unpublished" @endif>

                        {!! str_repeat(' ', $entity->depth) !!}
                        isRoot())fa-cog @elseif(!$entity->isLeaf()) fa-folder @else fa-sticky-note-o @endif">
                        {{ $entity->title }}

                    {{ $entity->slug }}
                    {{ $entity->module?trans($entity->module."::admin.title"):null }}

                        @if (!$entity->isRoot())
                            @include ('admin::common.controls.priority', ['routePrefix'=>$routePrefix, 'entity'=>$entity])
                        @endif

                         $entity->id]) !!}">

                        @include('admin::common.controls.publish', ['routePrefix'=>$routePrefix, 'id'=>$entity->id])
                        @include('admin::common.controls.edit', ['routePrefix'=>$routePrefix, 'id'=>$entity->id])

                        @if (!$entity->isRoot())
                            @include('admin::common.controls.destroy', ['routePrefix'=>$routePrefix, 'id'=>$entity->id])
                        @endif

            @endforeach

        {!! $entities->appends(\Request::except('page'))->render() !!}
    @else

                @lang('tree::admin.create_root')

    @endif
@endsection


text:
package org.scalatest

import org.scalatest.events.Event

/**
 * Trait whose instances collect the results of a running
 * suite of tests and presents those results in some way to the user. Instances of this trait can
 * be called "report functions" or "reporters."
 *
 *

 * Reporters receive test results via fifteen events.
 * Each event is fired to pass a particular kind of information to
 * the reporter. The events are:
 *

 *
 *

 *
DiscoveryStarting

 *
DiscoveryCompleted

 *
RunStarting

 *
RunStopped

 *
RunAborted

 *
RunCompleted

 *
ScopeOpened

 *
ScopeClosed

 *
ScopePending

 *
TestStarting

 *
TestSucceeded

 *
TestFailed

 *
TestCanceled

 *
TestIgnored

 *
TestPending

 *
SuiteStarting

 *
SuiteCompleted

 *
SuiteAborted

 *
InfoProvided

 *
MarkupProvided

 *
AlertProvided

 *
NoteProvided

 *

 *
 *

 * Reporters may be implemented such that they only present some of the reported events to the user. For example, you could
 * define a reporter class that does nothing in response to SuiteStarting events.
 * Such a class would always ignore SuiteStarting events.
 *

 *
 *

 * The term test as used in the TestStarting, TestSucceeded,
 * and TestFailed event names
 * is defined abstractly to enable a wide range of test implementations.
 * ScalaTest's style traits (subclasse of trait Suite) fire
 * TestStarting to indicate they are about to invoke one
 * of their tests, TestSucceeded to indicate a test returned normally,
 * and TestFailed to indicate a test completed abruptly with an exception.
 * Although the execution of a Suite subclass's tests will likely be a common event
 * reported via the
 * TestStarting, TestSucceeded, and TestFailed events, because
 * of the abstract definition of “test” used by the
 * the event classes, these events are not limited to this use. Information about any conceptual test
 * may be reported via the TestStarting, TestSucceeded, and
 * TestFailed events.
 *
 *

 * Likewise, the term suite as used in the SuiteStarting, SuiteAborted,
 * and SuiteCompleted event names
 * is defined abstractly to enable a wide range of suite implementations.
 * Object Runner fires SuiteStarting to indicate it is about to invoke
 * run on a
 * Suite, SuiteCompleted to indicate a Suite's
 * run method returned normally,
 * and SuiteAborted to indicate a Suite's run
 * method completed abruptly with an exception.
 * Similarly, class Suite fires SuiteStarting to indicate it is about to invoke
 * run on a
 * nested Suite, SuiteCompleted to indicate a nested Suite's
 * run method returned normally,
 * and SuiteAborted to indicate a nested Suite's run
 * method completed abruptly with an exception.
 * Although the execution of a Suite's run method will likely be a
 * common event reported via the
 * SuiteStarting, SuiteAborted, and SuiteCompleted events, because
 * of the abstract definition of "suite" used by the
 * event classes, these events are not limited to this use. Information about any conceptual suite
 * may be reported via the SuiteStarting, SuiteAborted, and
 * SuiteCompleted events.
 *
 *
Extensibility

 *
 *

 * You can create classes that extend Reporter to report test results in custom ways, and to
 * report custom information passed as an event "payload."
 * Reporter classes can handle events in any manner, including doing nothing.
 *

 *
 * @author Bill Venners
 */
trait Reporter {

  /**
   * Invoked to report an event that subclasses may wish to report in some way to the user.
   *
   * @param event the event being reported
   */
  def apply(event: Event)
}

private[scalatest] object Reporter {

  private[scalatest] def indentStackTrace(stackTrace: String, level: Int): String = {
    val indentation = if (level > 0) "  " * level else ""
    val withTabsZapped = stackTrace.replaceAll("\t", "  ")
    val withInitialIndent = indentation + withTabsZapped
    withInitialIndent.replaceAll("\n", "\n" + indentation) // I wonder if I need to worry about alternate line endings. Probably.
  }

  // In the unlikely event that a message is blank, use the throwable's detail message
  private[scalatest] def messageOrThrowablesDetailMessage(message: String, throwable: Option[Throwable]): String = {
    val trimmedMessage = message.trim
    if (!trimmedMessage.isEmpty)
      trimmedMessage
    else
      throwable match {
        case Some(t) => t.getMessage.trim
        case None => ""
      }
  }
}

  /*
      case RunStarting(ordinal, testCount, formatter, payload, threadName, timeStamp) => runStarting(testCount)

      case TestStarting(ordinal, suiteName, suiteClassName, testName, formatter, rerunnable, payload, threadName, timeStamp) =>

      case TestSucceeded(ordinal, suiteName, suiteClassName, testName, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

      case TestFailed(ordinal, message, suiteName, suiteClassName, testName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

      case TestIgnored(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) =>

      case TestPending(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) =>

      case SuiteStarting(ordinal, suiteName, suiteClassName, formatter, rerunnable, payload, threadName, timeStamp) =>

      case SuiteCompleted(ordinal, suiteName, suiteClassName, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

      case SuiteAborted(ordinal, message, suiteName, suiteClassName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

      case InfoProvided(ordinal, message, nameInfo, throwable, formatter, payload, threadName, timeStamp) => {

      case RunStopped(ordinal, duration, summary, formatter, payload, threadName, timeStamp) => runStopped()

      case RunAborted(ordinal, message, throwable, duration, summary, formatter, payload, threadName, timeStamp) =>

      case RunCompleted(ordinal, duration, summary, formatter, payload, threadName, timeStamp) => runCompleted()
*/


text:
// $Id: LB_Pull_Handler.cpp 2179 2013-05-28 22:16:51Z mesnierp $

#include "orbsvcs/LoadBalancing/LB_Pull_Handler.h"
#include "orbsvcs/LoadBalancing/LB_LoadManager.h"

#include "tao/debug.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

TAO_LB_Pull_Handler::TAO_LB_Pull_Handler (void)
  : monitor_map_ (0),
    load_manager_ (0)
{
}

void
TAO_LB_Pull_Handler::initialize (TAO_LB_MonitorMap * monitor_map,
                                 TAO_LB_LoadManager * load_manager)
{
  this->monitor_map_ = monitor_map;
  this->load_manager_ = load_manager;
}

int
TAO_LB_Pull_Handler::handle_timeout (
  const ACE_Time_Value & /* current_time */,
  const void * /* arg */)
{
  // @todo Fix the race condtions in this method.

  TAO_LB_MonitorMap::iterator begin = this->monitor_map_->begin ();
  TAO_LB_MonitorMap::iterator end   = this->monitor_map_->end ();

  if (begin == end)
    return 0;       // No work to be done.

  try
    {
      // Iterate over all registered load monitors.
      //
      // @todo This could be potentially very slow.  Improve concurrent
      //       operation at some point in the near future.
      for (TAO_LB_MonitorMap::iterator i = begin; i != end; ++i)
        {
          const PortableGroup::Location & location = (*i).ext_id_;
          CosLoadBalancing::LoadMonitor_var & monitor = (*i).int_id_;

          // The load monitor reference should never be nil since the
          // LoadManager prevents nil load monitor references from
          // being registered.
          CosLoadBalancing::LoadList_var load_list =
            monitor->loads ();

          this->load_manager_->push_loads (location,
                                           load_list.in ());

//           ORBSVCS_DEBUG ((LM_DEBUG,
//                       "LOCATION = %s\tLOAD = %f\n",
//                       location[0].id.in (),
//                       load_list[0].value));
        }
    }
  catch (const CORBA::Exception& ex)
    {
      // Catch the exception and ignore it.

      if (TAO_debug_level > 0)
        ex._tao_print_exception ("(%P|%t) PullHandler::handle_timeout()\n");
    }

  return 0;
}

TAO_END_VERSIONED_NAMESPACE_DECL


text:
package com.novacloud.data.formula.impl.test;

import static org.junit.Assert.fail;

import com.novacloud.data.formula.ExpressionFactory;
import com.novacloud.data.formula.ExpressionSyntaxException;
import com.novacloud.data.formula.impl.ExpressionFactoryImpl;
import org.junit.Assert;
import org.junit.Test;

public class ValidExpresionTest {
	final ExpressionFactory expressionFactory = ExpressionFactoryImpl.getInstance();

	public void invalid(String el) {
		try {
			expressionFactory.create(el);
			expressionFactory.parse(el);
			Assert.fail("必须抛ExpressionSyntaxException异常");
		} catch (ExpressionSyntaxException ignored) {
		} catch (java.lang.AssertionError e) {
			throw e;
		} catch (Throwable e) {
			e.printStackTrace();
			Assert.fail("只能是抛ExpressionSyntaxException异常:"+e.getMessage());
		}
	}
	public void valid(String el) {
		try {
			expressionFactory.create(el);
			expressionFactory.parse(el);
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail("检查失败"+e.getMessage());
		}
	}
	public void testOptimizeELString() {
		expressionFactory.parse("''");
		expressionFactory.parse("'['");
		try{
			expressionFactory.parse("'''");
			fail("无效字符串状态");
		}catch (Exception ignored) {
		}

		try{
			expressionFactory.parse("[([)]]");
			fail("无效括弧状态");
		}catch (Exception ignored) {
		}
	}

	@Test
	public void testEL1() throws Exception {
		invalid("1+");
		invalid("1;+1");
	}
	@Test
	public void testEL2() throws Exception {
		valid("{}");
		valid("[{}]");
	}
}


text:
class VRPN_API vrpn_Auxiliary_Logger : public vrpn_BaseClass {
public:

  vrpn_Auxiliary_Logger(const char * name, vrpn_Connection * c);

protected:
  // Handle registration of all message types we're going to deal with.
  virtual int register_types(void);
  vrpn_int32 request_logging_m_id;   // ID of remote->server request message
  vrpn_int32 report_logging_m_id;    // ID of server->client response message
  vrpn_int32 request_logging_status_m_id; // ID of remote->server status-request message

  // Pack a log description into the message whose type is passed
  // as the parameter (this is used to pack both the request and
  // report messages.
  bool pack_log_message_of_type(vrpn_int32 type,
                               const char *local_in_logfile_name,
                               const char *local_out_logfile_name,
                               const char *remote_in_logfile_name,
                               const char *remote_out_logfile_name);

  // Unpack a log description from a message into the four strings that
  // were passed in (this is used to unpack both the request and the
  // report messages).
  // NOTE: This routine will allocate space for the strings.  The caller
  // must delete [] this space when they are done with it to avoid
  // memory leaks.
  bool unpack_log_message_from_buffer(const char *buf, vrpn_int32 buflen,
                               char **local_in_logfile_name,
                               char **local_out_logfile_name,
                               char **remote_in_logfile_name,
                               char **remote_out_logfile_name);
};

// Virtual base server class for an auxiliiary logger.  An implementation must
// implement the specified message-handling functions and must call the base-
// class constructor to set up the calling of them.

class VRPN_API vrpn_Auxiliary_Logger_Server : public vrpn_Auxiliary_Logger {
public:
  vrpn_Auxiliary_Logger_Server(const char * name, vrpn_Connection * c);

  // Required for servers.
  virtual void mainloop(void) { server_mainloop(); }

protected:
  // Handle a logging-request message.  The request contains four file
  // names, two for local (to the Auxiliary server itself) and two for
  // remote (the far side of its connection to the server).  It must
  // also respond to the client with a message saying what logging has
  // been set up (using the send_logging_response function).  Logging is
  // turned off on a particular file by sending an empty-string name ("").
  // The in/out local/remote are with respect to the connection that the
  // logging is to occur on, which may or may not be the same one that the
  // client has connected to the object on using the constructor above.
  // Make sure to send a response saying what you did.
  virtual void handle_request_logging(const char *local_in_logfile_name,
                                      const char *local_out_logfile_name,
                                      const char *remote_in_logfile_name,
                                      const char *remote_out_logfile_name) = 0;

  // Send a response to the client telling it what logging has been
  // established.
  bool send_report_logging(const char *local_in_logfile_name,
                           const char *local_out_logfile_name,
                           const char *remote_in_logfile_name,
                           const char *remote_out_logfile_name)
    { if (!d_connection) { return false; }
      return pack_log_message_of_type(report_logging_m_id,
        local_in_logfile_name, local_out_logfile_name,
        remote_in_logfile_name, remote_out_logfile_name);
    }

  // Handle dropped last connection on server object by turning off
  // logging.  The static method basically looks up the this
  // pointer and calls the virtual method.  A derived class should re-implement
  // the non-static method below if it doesn't want to drop all logging or if
  // it wants to do something else in addition.  The static method basically
  // just calls the non-static method.
  virtual void handle_dropped_last_connection(void);
  vrpn_int32 dropped_last_connection_m_id;    // ID of message that all connections dropped
  static int VRPN_CALLBACK static_handle_dropped_last_connection(void *userdata, vrpn_HANDLERPARAM p );

  // Static portion of handling (unpacking) the request_logging message.  It
  // then calls the non-static virtual method above.
  static int VRPN_CALLBACK static_handle_request_logging(void *userdata, vrpn_HANDLERPARAM p );

  // Handle request for logging status.
  virtual void handle_request_logging_status( ) = 0;
  static int VRPN_CALLBACK static_handle_request_logging_status( void* userdata, vrpn_HANDLERPARAM p );
};

// Generic server that will start auxiliary logs on the connection whose name
// is passed in (which can be the same as the name of the connection it is created
// on, but does not have to be).  The "local" in and out are with respect to the
// new connection that is made; the "remote" in and out are with respect to the
// named connection.  No logging is started in the constructor.

class VRPN_API vrpn_Auxiliary_Logger_Server_Generic : public vrpn_Auxiliary_Logger_Server {
public:
  // Does not start logging, just records what to log when it is started.
  vrpn_Auxiliary_Logger_Server_Generic(const char *logger_name, const char *connection_to_log,
                                        vrpn_Connection *c = NULL);
  ~vrpn_Auxiliary_Logger_Server_Generic();

  // Close an existing logging connection, then (if any of the file
  // names are non-empty) open a new logging connection to the
  // connection we are to log (even if this process already has a
  // connection to it) and then send back the report that we've started
  // logging if we are able.  If we cannot open it, then fill in all
  // blank names for the return report.
  virtual void handle_request_logging(const char *local_in_logfile_name,
                                      const char *local_out_logfile_name,
                                      const char *remote_in_logfile_name,
                                      const char *remote_out_logfile_name);

  virtual void handle_request_logging_status( );

  // If we have an active logging connection, mainloop it and save all of its
  // pending messages in addition to handling the base-class functions.
  // Then call the parent class mainloop().
  virtual void mainloop(void) {
    if (d_logging_connection) {
      d_logging_connection->mainloop();
      d_logging_connection->save_log_so_far();
    }
    vrpn_Auxiliary_Logger_Server::mainloop();
  }

protected:
  char              *d_connection_name;     // Name to connect to when logging.
  vrpn_Connection   *d_logging_connection;  // Connection to use for logging.
};

//-----------------------------------------------------------
//************** Client code uses the following *************

// Type of a client routine to request new logging and to handle a
// report of changed logging.  This callback is called when the
// logging server reports a new set of files, which should happen
// after each request is made.

typedef	struct _vrpn_AUXLOGGERCB {
  struct timeval	msg_time;	// Timestamp of new logging
  const char *local_in_logfile_name;    // Name of the incoming local log ("" if none).
  const char *local_out_logfile_name;
  const char *remote_in_logfile_name;
  const char *remote_out_logfile_name;
} vrpn_AUXLOGGERCB;

typedef void (VRPN_CALLBACK *vrpn_AUXLOGGERREPORTHANDLER) (void * userdata,
					  const vrpn_AUXLOGGERCB info);

class VRPN_API vrpn_Auxiliary_Logger_Remote : public vrpn_Auxiliary_Logger {
public:
  vrpn_Auxiliary_Logger_Remote(const char * name, vrpn_Connection * c = NULL);

  // Send a request to the server asking it to log the following.  Each of these
  // is with respect to the connection that the auxiliary logger server is
  // handling, which may or may not be the one that it is connected to to
  // receive this message; it refers to the other side of the new connection
  // that the server establishes to do its logging.  Passing a NULL or empty
  // string ("") to any of the entries disables that log.
  // WARNING: If the server is set to connect to its own connection and log
  // it, then you must explicitly request a set of empty log files to stop
  // it logging the last time because otherwise it never gets the message
  // that it dropped the last connection and will continue logging after the
  // object is destroyed.
  bool send_logging_request(const char *local_in_logfile_name,
                            const char *local_out_logfile_name = "",
                            const char *remote_in_logfile_name = "",
                            const char *remote_out_logfile_name = "")
    { if (!d_connection) { return false; }
      return pack_log_message_of_type(request_logging_m_id,
        local_in_logfile_name, local_out_logfile_name,
        remote_in_logfile_name, remote_out_logfile_name);
    }

  bool send_logging_status_request( )
  {
	  if( !d_connection ) {  return false;  }
	  return pack_log_message_of_type( request_logging_status_m_id, NULL, NULL, NULL, NULL );
  }

  // Register/unregister a callback handler for the logging response.
  virtual int register_report_handler(void *userdata,
	  vrpn_AUXLOGGERREPORTHANDLER handler) {
    return d_callback_list.register_handler(userdata, handler);
  };
  virtual int unregister_report_handler(void *userdata,
	  vrpn_AUXLOGGERREPORTHANDLER handler) {
    return d_callback_list.unregister_handler(userdata, handler);
  }

  // This routine calls the mainloop of the connection it's on
  virtual void mainloop(void);

protected:
  // Static handler for the logging report message.
  // Use the base-class unpack method to convert the data into strings.
  vrpn_Callback_List<vrpn_AUXLOGGERCB> d_callback_list;

  static int VRPN_CALLBACK handle_report_message(void *userdata, vrpn_HANDLERPARAM p);
};

#endif


text:
define(function (require) {
  var _ = require('underscore'),
    Backbone = require('backbone');

  var DocModel = Backbone.Model.extend({
    // Model to represent the current chosen document.
    // Constructs the url of the content using the content_url_format
    // from the endpoint config.

    initialize: function(attributes, options) {
      var t = this;
      t.content_url_template = Handlebars.compile(options.content_url_format);
    },

    get_content_url: function() {
      if (!_.isEmpty(this.attributes)) {
        return this.content_url_template(this.toJSON());
      }
    }

  });

  return DocModel;

});


text:
'use strict';

SwaggerUi.Views.ParameterContentTypeView = Backbone.View.extend({
  initialize: function  () {},

  render: function(){
    $(this.el).html(Handlebars.templates.parameter_content_type(this.model));

    $('label[for=parameterContentType]', $(this.el)).text('Parameter content type:');

    return this;
  }

});


text:
var debug = require('ghost-ignition').debug('channels:render-post'),
    formatResponse = require('./format-response'),
    renderer = require('./renderer');
/*
 * Sets the response context around an entry (post or page)
 * and renders it with the correct template.
 * Used by post preview and entry methods.
 * Returns a function that takes the entry to be rendered.
 */
module.exports = function renderEntry(req, res) {
    debug('renderEntry called');
    return function renderEntry(entry) {
        // Renderer begin
        // Format data 2 - 1 is in preview/entry
        var data = formatResponse.entry(entry);

        // Render Call
        return renderer(req, res, data);
    };
};


text:
package com.intellij.refactoring.actions;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiAnonymousClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiNewExpression;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.anonymousToInner.AnonymousToInnerHandler;
import org.jetbrains.annotations.NotNull;

public class AnonymousToInnerAction extends BaseJavaRefactoringAction {
  @Override
  public boolean isAvailableInEditorOnly() {
    return true;
  }

  @Override
  public boolean isEnabledOnElements(PsiElement @NotNull [] elements) {
    return false;
  }

  @Override
  protected boolean isAvailableOnElementInEditorAndFile(@NotNull final PsiElement element, @NotNull final Editor editor, @NotNull PsiFile file, @NotNull DataContext context) {
    final PsiElement targetElement = file.findElementAt(editor.getCaretModel().getOffset());
    if (PsiTreeUtil.getParentOfType(targetElement, PsiAnonymousClass.class) != null) {
      return true;
    }
    if (PsiTreeUtil.getParentOfType(element, PsiAnonymousClass.class) != null) {
      return true;
    }
    final PsiNewExpression newExpression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class);
    return newExpression != null && newExpression.getAnonymousClass() != null;
  }

  @Override
  public RefactoringActionHandler getHandler(@NotNull DataContext dataContext) {
    return new AnonymousToInnerHandler();
  }
}


text:
require 'net/http'

class ProjectsController < ApplicationController
  include ProjectsHelper

  before_filter :load_project, only: [:show, :edit, :update, :decide_tip_amounts]
  before_filter :redirect_to_pretty_url, only: [:show, :edit, :decide_tip_amounts]

  def index
    @projects = Project.order(projects_order).page(params[:page]).per(30)
  end

  def search
    if params[:query].present?
      if BLACKLIST.include?(params[:query])
        render :blacklisted and return
      elsif project = Project.find_by_url(params[:query])
        redirect_to pretty_project_path(project) and return
      end
    end

    @projects = Project.search(params[:query].to_s).order(projects_order).page(params[:page]).per(30)
    render :index
  end

  def show
    render :blacklisted and return if BLACKLIST.include? @project.github_url

    @project.update_bitcoin_address if @project.bitcoin_address.nil?

    @project_tips = @project.tips.with_address
    @recent_tips  = @project_tips.with_address.order(created_at: :desc).first(5)
  end

  def edit
    authorize! :update, @project
  end

  def update
    authorize! :update, @project
    @project.attributes = project_params
    if @project.tipping_policies_text.try(:text_changed?)
      @project.tipping_policies_text.user = current_user
    end
    if @project.save
      redirect_to project_path(@project), notice: I18n.t('notices.project_updated')
    else
      render 'edit'
    end
  end

  def decide_tip_amounts
    authorize! :decide_tip_amounts, @project
    if request.patch?
      @project.available_amount # preload anything required to get the amount, otherwise it's loaded during the assignation and there are undesirable consequences
      percentages = params[:project][:tips_attributes].values.map{|tip| tip['amount_percentage'].to_f}
      if percentages.sum > 100
        redirect_to decide_tip_amounts_project_path(@project), alert: I18n.t('errors.can_assign_more_tips')
        return
      end
      raise "wrong data" if percentages.min < 0
      @project.attributes = params.require(:project).permit(tips_attributes: [:id, :amount_percentage])
      if @project.save
        message = I18n.t('notices.tips_decided')
        if @project.has_undecided_tips?
          redirect_to decide_tip_amounts_project_path(@project), notice: message
        else
          redirect_to @project, notice: message
        end
      end
    end
  end

  private

  def load_project ; super params ; end ;

  def project_params
    params.require(:project).permit(:branch, :disable_notifications, :hold_tips, tipping_policies_text_attributes: [:text])
  end

  def projects_order
    {
      'balance'     => {available_amount_cache: :desc, watchers_count: :desc, full_name: :asc},
      'watchers'    => {watchers_count: :desc, available_amount_cache: :desc, full_name: :asc},
      'repository'  => {full_name: :asc, available_amount_cache: :desc, watchers_count: :desc},
      'description' => {description: :asc, available_amount_cache: :desc, watchers_count: :desc, full_name: :asc}
    }.[](params[:order] || 'balance')
  end

  def redirect_to_pretty_url
    return unless request.get? && params[:id].present?

    begin
      respond_to do |format|
        case action_name
        when 'show'
          path = pretty_project_path                    @project
        when 'edit'
          path = pretty_project_edit_path               @project
        when 'decide_tip_amounts'
          path = pretty_project_decide_tip_amounts_path @project
        end
        format.html { redirect_to path }
      end
    rescue ActionController::UnknownFormat
    end
  end
end


text:
set -e

git stash
git clean -fdx -e images/
git stash pop


text:
Create a Word Count Application in Java
===============================================

Coming Soon!


text:
exports.welcome = function(req,res){
	res.send({
		'message':'welcome to errand guy'
	});
}

exports.faq = function(req,res){
	res.render('faq');
};


text:
{% extends 'userena/base_userena.html' %}
{% load i18n %}

{% block title %}{% blocktrans with profile.user.username as username %}{{ username }}'s profile.{% endblocktrans %}{% endblock %}

{% block content %}

{% if profile.user.get_full_name %}{{ profile.user.get_full_name }} {% endif %}({{ profile.user.username }})

    {% block profile_navigation %}
      {% comment %}Dirty hack. Will use django-guardian in the future.{% endcomment %}
      {% if user.username == profile.user.username %}

          {% block profile_navigation_items %}

{% trans "Profil ansehen" %}

{% trans "Profil bearbeiten" %}

{% trans "Passwort ändern" %}

{% trans "Email-Adresse ändern" %}

          {% endblock %}

      {% endif %}
    {% endblock %}

      {% block profile_details %}

          {% block profile_definition_list %}
            {% if profile.user.get_full_name %}

Name

{{ profile.user.get_full_name }}

            {% endif %}
            {% if profile.user.email and not hide_email %}

{% trans "Email" %}

{{ profile.user.email }}

            {% endif %}
            {% if user.username == profile.user.username %}

Email-Benachrichtigung bei neuen Nachrichten

{% if profile.email_on_message %}Ja{% else %}Nein{% endif %}

Email-Benachrichtigung bei Antwort auf meine Kommentare

{% if profile.email_on_comment_answer %}Ja{% else %}Nein{% endif %}

            {% endif %}
            {% if profile.age %}

{% trans "Alter" %}

{{ profile.age }}

            {% endif %}
            {% if profile.website %}

{% trans "Webseite" %}

{{ profile.website|urlize }}

            {% endif %}
            {% if profile.location %}

{% trans "Ort" %}

{{ profile.location }}

            {% endif %}
            {% if profile.about_me %}

{% trans "Über mich" %}

{{ profile.about_me }}

            {% endif %}
          {% endblock %}

      {% endblock %}

{% endblock %}


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

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reporting
{
    public class Test
    {
        public IList<string> Categories { get; set; } = new List<string>();

        public string Name { get; set; }
        public Dictionary<string, string> AdditionalData { get; set; } = new Dictionary<string, string>();

        public IList<Counter> Counters { get; set; } = new List<Counter>();

        public void AddCounter(Counter counter)
        {
            if (counter.DefaultCounter && Counters.Any(c => c.DefaultCounter))
            {
                throw new Exception($"Duplicate default counter, name: ${counter.Name}");
            }

            if (Counters.Any(c => c.Name.Equals(counter.Name)))
            {
                throw new Exception($"Duplicate counter name, name: ${counter.Name}");
            }

            Counters.Add(counter);
        }

        public void AddCounter(IEnumerable<Counter> counters)
        {
            foreach (var counter in counters)
                AddCounter(counter);
        }
    }
}


text:
package chef

import (
	"fmt"
	"path"
	"strings"

	"github.com/hashicorp/terraform/communicator"
	"github.com/hashicorp/terraform/terraform"
)

const (
	installURL = "https://www.chef.io/chef/install.sh"
)

func (p *Provisioner) linuxInstallChefClient(
	o terraform.UIOutput,
	comm communicator.Communicator) error {

	// Build up the command prefix
	prefix := ""
	if p.HTTPProxy != "" {
		prefix += fmt.Sprintf("http_proxy='%s' ", p.HTTPProxy)
	}
	if p.HTTPSProxy != "" {
		prefix += fmt.Sprintf("https_proxy='%s' ", p.HTTPSProxy)
	}
	if p.NOProxy != nil {
		prefix += fmt.Sprintf("no_proxy='%s' ", strings.Join(p.NOProxy, ","))
	}

	// First download the install.sh script from Chef
	err := p.runCommand(o, comm, fmt.Sprintf("%scurl -LO %s", prefix, installURL))
	if err != nil {
		return err
	}

	// Then execute the install.sh scrip to download and install Chef Client
	err = p.runCommand(o, comm, fmt.Sprintf("%sbash ./install.sh -v %q", prefix, p.Version))
	if err != nil {
		return err
	}

	// And finally cleanup the install.sh script again
	return p.runCommand(o, comm, fmt.Sprintf("%srm -f install.sh", prefix))
}

func (p *Provisioner) linuxCreateConfigFiles(
	o terraform.UIOutput,
	comm communicator.Communicator) error {
	// Make sure the config directory exists
	if err := p.runCommand(o, comm, "mkdir -p "+linuxConfDir); err != nil {
		return err
	}

	// Make sure we have enough rights to upload the files if using sudo
	if p.useSudo {
		if err := p.runCommand(o, comm, "chmod 777 "+linuxConfDir); err != nil {
			return err
		}
	}

	if err := p.deployConfigFiles(o, comm, linuxConfDir); err != nil {
		return err
	}

	if len(p.OhaiHints) > 0 {
		// Make sure the hits directory exists
		hintsDir := path.Join(linuxConfDir, "ohai/hints")
		if err := p.runCommand(o, comm, "mkdir -p "+hintsDir); err != nil {
			return err
		}

		// Make sure we have enough rights to upload the hints if using sudo
		if p.useSudo {
			if err := p.runCommand(o, comm, "chmod 777 "+hintsDir); err != nil {
				return err
			}
		}

		if err := p.deployOhaiHints(o, comm, hintsDir); err != nil {
			return err
		}

		// When done copying the hints restore the rights and make sure root is owner
		if p.useSudo {
			if err := p.runCommand(o, comm, "chmod 755 "+hintsDir); err != nil {
				return err
			}
			if err := p.runCommand(o, comm, "chown -R root.root "+hintsDir); err != nil {
				return err
			}
		}
	}

	// When done copying all files restore the rights and make sure root is owner
	if p.useSudo {
		if err := p.runCommand(o, comm, "chmod 755 "+linuxConfDir); err != nil {
			return err
		}
		if err := p.runCommand(o, comm, "chown -R root.root "+linuxConfDir); err != nil {
			return err
		}
	}

	return nil
}


text:
package com.pineone.icbms.so.resources.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.pineone.icbms.so.resources.action.IGenericAction;
import com.pineone.icbms.so.resources.property.reference.IGenericOntologyReference;

/**
 * Activity default class.<BR/>
 * Created by Melvin on 2015. 11. 17..
 */
public class DefaultActivity extends AGenericActivity
{
	private static final long serialVersionUID = 3664754380402892048l;

	@Override
	protected List<IGenericAction> createActionList()
	{
		return new ArrayList<IGenericAction>();
	}

	@Override
	protected Map createStore()
	{
		return new ConcurrentHashMap<String, Object>();
	}
}