text:
Delete Account

You may delete your account at any time. However, this action is irreversible.

                <button class="btn btn-danger pointer del-button" data-toggle="modal" data-target="#deleting">I understand, delete my account</button>

                Unexpected Error

Delete Account

                <button type="button" class="close pointer" data-dismiss="modal" aria-label="Close">
            ×
          </button>

Did you think it all right?

                <button type="button" class="btn btn-danger pointer" data-dismiss="modal" (click)="accountDel()">Delete</button>
                <button type="button" class="btn btn-secondary pointer" data-dismiss="modal">Cancel</button>


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.IO;
using System.Runtime.InteropServices;
using System.Text.Formatting;

namespace System.Drawing.Graphics
{
    public static class Jpg
    {
        //add jpg specific method later
        public static Image Load(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(string.Format(Strings.MalformedFilePath, filePath));
            }
            else if (DLLImports.gdSupportsFileType(filePath, false))
            {
                Image img = new Image(DLLImports.gdImageCreateFromFile(filePath));

                if (!img.TrueColor)
                {
                    DLLImports.gdImagePaletteToTrueColor(img.gdImageStructPtr);
                }
                return img;
            }
            else
            {
                throw new FileLoadException(string.Format(Strings.FileTypeNotSupported, filePath));
            }
        }

        //add jpg specific method later
        public static void Write(Image img, string filePath)
        {
            DLLImports.gdImageSaveAlpha(img.gdImageStructPtr, 1);

            if (!DLLImports.gdSupportsFileType(filePath, true))
            {
                throw new InvalidOperationException(string.Format(Strings.FileTypeNotSupported, filePath));
            }
            else
            {
                if (!DLLImports.gdImageFile(img.gdImageStructPtr, filePath))
                {
                    throw new FileLoadException(string.Format(Strings.WriteToFileFailed, filePath));
                }
            }
        }

        public static Image Load(Stream stream)
        {
            if (stream != null)
            {
                unsafe
                {
                    IntPtr pNativeImage = IntPtr.Zero;
                    var wrapper = new gdStreamWrapper(stream);
                    pNativeImage = DLLImports.gdImageCreateFromJpegCtx(ref wrapper.IOCallbacks);
                    DLLImports.gdImageStruct* pStruct = (DLLImports.gdImageStruct*)pNativeImage;
                    Image toRet = Image.Create(pStruct->sx, pStruct->sx);
                    DLLImports.gdImageDestroy(toRet.gdImageStructPtr);
                    toRet.gdImageStructPtr = pNativeImage;
                    return toRet;
                }
            }
            else
            {
                throw new InvalidOperationException(Strings.NullStreamReferenced);
            }

        }

        public static void Write(Image bmp, Stream stream)
        {
            DLLImports.gdImageSaveAlpha(bmp.gdImageStructPtr, 1);

            //MARSHALLING?
            DLLImports.gdImageStruct gdImageStruct = Marshal.PtrToStructure<DLLImports.gdImageStruct>(bmp.gdImageStructPtr);
            var wrapper = new gdStreamWrapper(stream);
            DLLImports.gdImageJpegCtx(ref gdImageStruct, ref wrapper.IOCallbacks);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
function print_help() {
	echo "Usage: $0 {start | stop | restart | status}"
	exit 1
}

if [ $# != 1 ]
then
	print_help
fi

DIR=$(readlink -f $(dirname $0))

source ${DIR}/eagle-env.sh

JVM_OPTS="-server -Xms1024m -Xmx1024m -XX:MaxPermSize=1024m"

GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:${DIR}/../log/eagle-server-gc.log"

if [ ! -z "$EAGLE_SERVER_JMX_PORT" ]; then
    JMX_HOST=`hostname -f`
    JVM_OPTS="-Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=$EAGLE_SERVER_JMX_PORT \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    -Dcom.sun.management.jmxremote.local.only=false \
    -Djava.rmi.server.hostname=$JMX_HOST \
    -Dcom.sun.management.jmxremote.rmi.port=$EAGLE_SERVER_JMX_PORT \
    $JVM_OPTS"
fi

JVM_OPTS="-Dconfig.resource=eagle.conf $JVM_OPTS $GC_OPTS"

PIDFILE="${DIR}/../run/eagle-server.pid"

CONFIGURATION_YML="${DIR}/../conf/server.yml"

DEBUG_OPTIONS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"

PROGRAM="java $JVM_OPTS -cp $EAGLE_CLASSPATH org.apache.eagle.server.ServerMain server ${CONFIGURATION_YML}"

cd $DIR/../

if [ ! -e ${DIR}/../run ]; then
    mkdir ${DIR}/../run
fi

if [ ! -e ${DIR}/../log ]; then
    mkdir ${DIR}/../log
fi

start() {
    echo "Starting eagle service ..."
	echo ${PROGRAM}
	nohup ${PROGRAM} 1> ${DIR}/../log/eagle-server.out 2>&1 & echo $! > $PIDFILE
	if [ $? != 0 ];then
		echo "Error: failed starting"
		exit 1
	fi
}

stop() {
    echo "Stopping eagle service ..."
	if [[ ! -f $PIDFILE ]];then
	    echo "Eagle service is not running"
    	exit 1
    fi

    PID=`cat $PIDFILE`
	kill $PID
	if [ $? != 0 ];then
		echo "Error: failed stopping"
		rm -rf ${PIDFILE}
		exit 1
	fi

	rm ${PIDFILE}
	echo "Stopping is completed"
}

case $1 in
"start")
    start;
	;;
"stop")
    stop;
	;;
"restart")
	echo "Restarting eagle service ..."
    stop; sleep 1; start;
	echo "Restarting is completed "
	;;
"status")
	echo "Checking eagle service status ..."
	if [[ -e ${PIDFILE} ]]; then
	    PID=`cat $PIDFILE`
	fi
	if [[ -z ${PID} ]];then
	    echo "Error: Eagle service is not running (missing PID)"
	    exit 0
	elif ps -p ${PID} > /dev/null; then
	    echo "Eagle service is running with PID $PID"
	    exit 0
    else
        echo "Eagle service is not running (tested PID: ${PID})"
        exit 0
    fi
	;;
*)
	print_help
	;;
esac

if [ $? != 0 ]; then
	echo "Error: start failure"
	exit 1
fi

exit 0


text:
using System.Configuration;

namespace Wave.Transports.RabbitMQ.Configuration
{
    public class ConfigurationSettings
    {
        private bool autoDeleteQueues = false;
        private string connectionString = null;
        private string exchange = "Wave";

        public string ConnectionString
        {
            get
            {
                if (connectionString == null)
                {
                    // If not set, check to see if a connection string for "RabbitMQ"
                    // is defined.
                    if (ConfigurationManager.ConnectionStrings["RabbitMQ"] != null)
                    {
                        connectionString = ConfigurationManager.ConnectionStrings["RabbitMQ"].ConnectionString;
                    }
                    else
                    {
                        connectionString = "amqp://guest:guest@localhost:5672/";
                    }
                }

                return connectionString;
            }
        }

        public string Exchange
        {
            get
            {
                return this.exchange;
            }
        }

        public bool AutoDeleteQueues
        {
            get
            {
                return this.autoDeleteQueues;
            }
        }

        public ConfigurationSettings UseAutoDeleteQueues()
        {
            this.autoDeleteQueues = true;
            return this;
        }

        public ConfigurationSettings UseConnectionString(string connectionString)
        {
            this.connectionString = connectionString;
            return this;
        }

        public ConfigurationSettings UseExchange(string exchange)
        {
            this.exchange = exchange;
            return this;
        }
    }
}


text:
package com.ikeengine.core;

import com.ikeengine.audio.AudioManager;
import com.ikeengine.debug.Message;
import com.ikeengine.debug.MessageBus;
import com.ikeengine.input.CursorPosHandler;
import com.ikeengine.input.KeyboardHandler;
import com.ikeengine.input.MouseButtonHandler;
import com.ikeengine.input.ScrollWheelHandler;
import com.ikeengine.physics.CollisionWorld;
import com.ikeengine.physics.PhysicsWorld;
import com.ikeengine.render.Renderer;
import com.ikeengine.scene.SceneManager;
import com.ikeengine.util.Loader;
import static org.lwjgl.glfw.Callbacks.errorCallbackPrint;
import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE;
import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints;
import static org.lwjgl.glfw.GLFW.glfwDestroyWindow;
import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor;
import static org.lwjgl.glfw.GLFW.glfwGetVideoMode;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.glfw.GLFW.glfwPollEvents;
import static org.lwjgl.glfw.GLFW.glfwSetCursorPosCallback;
import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback;
import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback;
import static org.lwjgl.glfw.GLFW.glfwSetMouseButtonCallback;
import static org.lwjgl.glfw.GLFW.glfwSetWindowPos;
import static org.lwjgl.glfw.GLFW.glfwShowWindow;
import static org.lwjgl.glfw.GLFW.glfwSwapBuffers;
import static org.lwjgl.glfw.GLFW.glfwSwapInterval;
import static org.lwjgl.glfw.GLFW.glfwTerminate;
import static org.lwjgl.glfw.GLFW.glfwWindowHint;
import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_PROJECTION;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.opengl.GL11.GL_VERSION;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glGetString;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glMatrixMode;
import static org.lwjgl.opengl.GL11.glOrtho;
import static org.lwjgl.system.MemoryUtil.NULL;

import java.nio.ByteBuffer;
import org.joml.Vector2f;
import static org.lwjgl.glfw.GLFW.glfwSetScrollCallback;
import org.lwjgl.glfw.GLFWCursorPosCallback;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWMouseButtonCallback;
import org.lwjgl.glfw.GLFWScrollCallback;

import org.lwjgl.glfw.GLFWvidmode;
import org.lwjgl.opengl.GLContext;

/**
 *
 * @author Jonathan Elue
 */
public class Core implements Runnable {

    public static boolean running;
    private Thread thread;
    private String fpsString;
    private boolean firstSceneInit;

    private final ThreadPool pool;
    public final MessageBus bus;
    public final SceneManager s;

    private GLFWErrorCallback errorCallback;
    private GLFWKeyCallback keyCallback;
    private GLFWCursorPosCallback cursorPosCallback;
    private GLFWMouseButtonCallback mouseButtonCallback;
    private GLFWScrollCallback scrollCallback;

    private long window;
    public final String title;
    public final int width, height;
    public final Message dimensions;
    public final boolean debug;
    public final AbstractGame game;

    private final Loader loader;
    private final Renderer renderer;
    private AudioManager audio;
    private final CollisionWorld cworld;
    private final PhysicsWorld pworld;

    public Core(String title, int width, int height, int threadCount, boolean debug, AbstractGame game) {
        this.title = title;
        this.width = width;
        this.height = height;
        this.debug = debug;
        this.game = game;
        dimensions = new Message(-1, "Core").setMessage("GAME_DIMENSIONS", new Vector2f(width, height));
        thread = null;
        fpsString = "";
        firstSceneInit = false;

        bus = new MessageBus(title, debug);
        pool = new ThreadPool(threadCount, bus);
        s = new SceneManager(debug);
        loader = new Loader(width, height);
        renderer = new Renderer(width, height);
        cworld = new CollisionWorld();
        pworld = new PhysicsWorld();
    }

    /**
     * Starts Game
     */
    public void begin() {
        if (thread == null) {
            thread = new Thread(this);
            running = true;
            thread.start();
        }
    }

    private void init() {
        initGLFW();
        initOpenGL();
        initOpenAL();
    }

    private void initGLFW() {
        // Setup an error callback. The default implementation
        // will print the error message in System.err.
        glfwSetErrorCallback(errorCallback = errorCallbackPrint(System.err));

        if (glfwInit() != GL_TRUE) {
            // Throw an error.
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        // Configure our window
        glfwDefaultWindowHints(); // optional, the current window hints are
        // already the default
        glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden
        // aft
        glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Allows our window to not be
        // resizable (too
        // complicated)

        window = glfwCreateWindow(width, height, title, NULL, NULL);

        if (window == NULL) {
            // Throw an Error
            throw new RuntimeException("Failed to create the GLFW window");
        }

        glfwSetKeyCallback(window, keyCallback = new KeyboardHandler());
        glfwSetCursorPosCallback(window,
                cursorPosCallback = new CursorPosHandler());
        glfwSetMouseButtonCallback(window,
                mouseButtonCallback = new MouseButtonHandler());
        glfwSetScrollCallback(window,
                        scrollCallback = new ScrollWheelHandler());

        // Center window
        ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        int x = GLFWvidmode.width(vidmode);
        int y = GLFWvidmode.height(vidmode);
        int winposx = (int) ((x - width) / 2.0);
        int winposy = (int) ((y - height) / 2.0);
        glfwSetWindowPos(window, winposx, winposy);

        glfwMakeContextCurrent(window);

        GLContext.createFromCurrent();
        glfwSwapInterval(1);

        glfwShowWindow(window);
    }

    private void initOpenGL() {
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(0, width, 0, height, -1, 1);

        glMatrixMode(GL_MODELVIEW);

        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glEnable(GL_DEPTH_TEST);

        System.out.println("OpenGL: " + glGetString(GL_VERSION));
    }

    private void initOpenAL() {
        audio = new AudioManager();
    }

    @Override
    public void run() {
        init();
        game.init(loader, s, bus);

        double fps = 0;
        double fpsRefined = 0;

        double frameCap = 1.0f / 60.0f;

        double firstTime;
        double lastTime = System.nanoTime() / 1000000000.0;
        double passedTime;
        double unprocessedTime = 0;

        double frameTime = 0;
        int frames = 0;

        while (running) {

            boolean render = false;

            // Calculations for Delta Time and Loop
            firstTime = System.nanoTime() / 1000000000.0;
            passedTime = firstTime - lastTime;
            lastTime = firstTime;

            unprocessedTime += passedTime;

            frameTime += passedTime;

            while (unprocessedTime >= frameCap) {
                if(fps == 0)
                    fpsRefined = 0;
                else
                    fpsRefined = 1/fps;
                update(fpsRefined);
                unprocessedTime -= frameCap;
                render = true;

                if (frameTime >= 1) {
                    frameTime = 0;
                    fps = frames;
                    frames = 0;
                }
            }

            if (render) {
                render();
                if(debug)
                    fpsString = "FPS: " + fps + " Delta: " + fpsRefined;
                frames++;
            } else {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (glfwWindowShouldClose(window) == GL_TRUE)
                running = false;
        }

        dispose();
        System.exit(0);
    }

    private void input() {
        ((KeyboardHandler)keyCallback).update();
        ((MouseButtonHandler)mouseButtonCallback).update();

        glfwPollEvents();

        ((KeyboardHandler)keyCallback).getMessages(bus);
        ((MouseButtonHandler)mouseButtonCallback).getMessages(bus);
        ((CursorPosHandler)cursorPosCallback).sendCoords(bus);
        ((ScrollWheelHandler)scrollCallback).sendScroll(bus);
    }

    private void update(double delta) {
        if(!firstSceneInit) {
            bus.addMessage(new Message(-1, "Core").setMessage("init_scene", null));
            firstSceneInit = true;
        }
        bus.setDelta(delta);
        bus.addMessage(dimensions);
        input();
        cworld.update(bus);
        pworld.update(delta, bus);
        if(debug)
            bus.print(fpsString);
        updateScene();
    }

    private void updateScene() {
        pool.update(s);
        if(s.evalutateSwitchedScene(bus))
            bus.addMessage(new Message(-1, "Core").setMessage("init_scene", null));
    }

    private void render() {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        renderer.render(bus, loader);
	glfwSwapBuffers(window);
    }

    private void dispose() {

        if(audio != null)
            AudioManager.cleanUp();

        loader.dispose();

        glfwDestroyWindow(window);

        keyCallback.release();
        mouseButtonCallback.release();
        cursorPosCallback.release();

        // Final Cleanup
        pool.dispose();
        glfwTerminate();
        errorCallback.release();

        System.out.println("Cleaned Up!");
    }
}


text:
// TestSetConstraints.java, created Mon Jun 20 14:29:58 2005 by salcianu
// Copyright (C) 2005 Alexandru Salcianu <salcianu@alum.mit.edu>
// Licensed under the Modified BSD Licence; see COPYING for details.
package jpaul.Constraints.SetConstraints;

import java.util.Set;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.framework.Assert;

import jpaul.Constraints.ConstraintSystem;
import jpaul.Constraints.Constraint;
import jpaul.Constraints.SolReader;
import jpaul.Constraints.SolAccessor;
import jpaul.Constraints.Var;

import jpaul.Misc.Predicate;

/**
 * TestSetConstraints
 *
 * @author  Alexandru Salcianu - salcianu@alum.mit.edu
 * @version $Id: TestSetConstraints.java,v 1.6 2006/03/14 02:29:32 salcianu Exp $
 */
public class TestSetConstraints extends TestCase {

    public static Test suite() {
	ConstraintSystem.DEBUG = true;
	return new TestSuite(TestSetConstraints.class);
    }

    private static class FunnyIncrement extends Constraint<SVar<Integer>,Set<Integer>> {
	public FunnyIncrement(SVar<Integer> v) {
	    this.v   = v;
	    this.in  = Collections.<SVar<Integer>>singleton(v);
	    this.out = Collections.<SVar<Integer>>singleton(v);
	}

	public int cost() { return Constraint.HIGH_COST; }

	public final SVar<Integer> v;

	private final Collection<SVar<Integer>> in;
	private final Collection<SVar<Integer>> out;

	public Collection<SVar<Integer>> in()  { return this.in;  }
	public Collection<SVar<Integer>> out() { return this.out; }

	public void action(SolAccessor<SVar<Integer>,Set<Integer>> sa) {
	    Set<Integer> vi = sa.get(v);
	    if((vi == null) || vi.size() < 10) {
		int k = findMax(vi);
		sa.join(v, Collections.<Integer>singleton(new Integer(k+1)));
	    }
	}

	private int findMax(Set<Integer> si) {
	    if(si == null) return 0;
	    int max = 0;
	    for(Integer i : si) {
		if(i.intValue() > max) {
		    max = i.intValue();
		}
	    }
	    return max;
	}

	public String toString() {
	    return "funnyIncrement(" + v + ")";
	}
    }

    private static final SVar<Integer> si1 = new SVar<Integer>();
    private static final SVar<Integer> si2 = new SVar<Integer>();
    private static final SVar<Integer> si3 = new SVar<Integer>();
    private static final SVar<Integer> si4 = new SVar<Integer>();
    private static final SVar<Integer> si5 = new SVar<Integer>();
    private static final SVar<Integer> si6 = new SVar<Integer>();
    private static final SVar<Integer> si7 = new SVar<Integer>();

    public void test0() {
	SetConstraints<Integer> sc = new SetConstraints<Integer>();

	sc.addCtSource(Arrays.asList(new Integer(1), new Integer(2)), si1);
	sc.addInclusion(si1, si2);
	sc.addInclusion(si2, si3);
	sc.addInclusion(si3, si4);
	sc.addInclusion(si1, si3);
	sc.addInclusion(si1, si4);

	TestSetConstraints.<SVar<Integer>,Set<Integer>>solve(sc);
    }

    public void test1() {
	SetConstraints<Integer> sc = new SetConstraints<Integer>();

	sc.addCtSource(Arrays.asList(new Integer(1), new Integer(2)), si1);
	sc.addInclusion(si1, si2);
	sc.addInclusion(si2, si3);
	sc.addInclusion(si3, si4);
	sc.addInclusion(si4, si2);

	TestSetConstraints.<SVar<Integer>,Set<Integer>>solve(sc);
    }

    public void test2() {
	SetConstraints<Integer> sc = new SetConstraints<Integer>();

	sc.addCtSource(Arrays.asList(new Integer(1), new Integer(2)), si1);
	sc.addInclusion(si1, si2);
	sc.addInclusion(si2, si3);
	sc.addInclusion(si3, si4);
	sc.addInclusion(si4, si2);
	sc.addCtSource(Arrays.asList(new Integer(3)), si3);

	TestSetConstraints.<SVar<Integer>,Set<Integer>>solve(sc);
    }

    public void test3() {
	SetConstraints<Integer> sc = new SetConstraints<Integer>();

	sc.addCtSource(Arrays.asList(new Integer(1), new Integer(2)), si1);
	sc.addInclusion(si1, si2);
	sc.addInclusion(si2, si3);
	sc.addInclusion(si3, si4);
	sc.addInclusion(si4, si2);
	sc.addCtSource(Arrays.asList(new Integer(3)), si3);
	sc.add(new FunnyIncrement(si3));

	TestSetConstraints.<SVar<Integer>,Set<Integer>>solve(sc);
    }

    public void test4() {
	SetConstraints<Integer> sc = new SetConstraints<Integer>();

	sc.addCtSource(Arrays.asList(new Integer(1), new Integer(2)), si1);
	sc.addInclusion(si1, si2);
	sc.addInclusion(si2, si3);
	sc.addInclusion(si3, si4);
	sc.addInclusion(si4, si2);
	sc.addCtSource(Arrays.asList(new Integer(3)), si3);
	sc.add(new FunnyIncrement(si3));
	sc.add
	    (new FilterConstraint<Integer>
	     (si3,
	      new Predicate<Integer>() {
		public boolean check(Integer i) { return i.intValue() % 2 == 0; }
		public String toString() { return "even"; }
	      },
	      si5));
	sc.add
	    (new CtDiffConstraint<Integer>
	     (si3,
	      Arrays.asList(new Integer(0), new Integer(1), new Integer(2),
                      new Integer(3), new Integer(4)),
	      si5));
	sc.addCtSource(Arrays.asList(new Integer(0), new Integer(1),
                new Integer(2), new Integer(3)), si6);
	sc.add(new IntersectConstraint<Integer>(si5, si6, si7));

	TestSetConstraints.<SVar<Integer>,Set<Integer>>solve(sc);
    }

    private static <V extends Var<Info>, Info> void solve(Collection<Constraint<V,Info>> sc) {
	//System.out.println("Original constraints: " + sc);

	ConstraintSystem<V,Info> sys = new ConstraintSystem<V,Info>(sc);

	sys.debugPrintSolverStructs(System.out);

	SolReader<V,Info> sol = sys.solve();

	System.out.print("Solution:\n" + sol);

	SolAccessor<V,Info> ver = new SolVerifier<V,Info>(sol);
	for(Constraint<V,Info> c : sc) {
	    System.out.print("Verifying constraint " + c + " ... ");
	    c.action(ver);
	    System.out.println("ok!");
	}
	System.out.println("Solution seems to be correct!\n");
    }

    private static final class SolVerifier<V extends Var<Info>, Info> implements SolAccessor<V,Info> {
	public SolVerifier(SolReader<V,Info> sr) { this.sr = sr; }

	private SolReader<V,Info> sr;

	public Info get(V v) { return sr.get(v); }

	public void join(V v, Info delta) {
	    Info old = this.get(v);
	    // special case: no previous value for v
	    if(old == null) {
		if(delta == null) return;
	    }
	    else {
		if(!v.join(old, delta)) return;
	    }

	    // if this point is reached, a change was detected ...
	    Assert.assertTrue
		("wrong! action causes info to grow!",
		 false);
	}
    }

}


text:
if [ `uname -s` = 'SunOS' -a "${POSIX_SHELL}" != "true" ]; then
    POSIX_SHELL="true"
    export POSIX_SHELL
    # To support POSIX.2 compliant 'id' add /usr/xpg4/bin to path
    PATH=/usr/xpg4/bin:$PATH
    export PATH
    exec /usr/bin/ksh $0 "$@"
fi
unset POSIX_SHELL # clear it so if we invoke other scripts, they run as ksh as well

RUNNER_SCRIPT_DIR={{runner_script_dir}}
RUNNER_SCRIPT=${0##*/}

RUNNER_BASE_DIR={{runner_base_dir}}
RUNNER_ETC_DIR={{runner_etc_dir}}
RUNNER_LOG_DIR={{runner_log_dir}}
RUNNER_LIB_DIR={{runner_lib_dir}}
RUNNER_PATCH_DIR={{runner_patch_dir}}
PIPE_DIR={{pipe_dir}}
RUNNER_USER={{runner_user}}
APP_VERSION={{app_version}}

# Variables needed to support creation of .pid files
# PID directory and pid file name of this app
# ex: /var/run/riak & /var/run/riak/riak.pid
RUN_DIR="/var/run" # for now hard coded unless we find a platform that differs
PID_DIR=$RUN_DIR/$RUNNER_SCRIPT
PID_FILE=$PID_DIR/$RUNNER_SCRIPT.pid

# Threshold where users will be warned of low ulimit file settings
# default it if it is not set
ULIMIT_WARN={{runner_ulimit_warn}}
if [ -z "$ULIMIT_WARN" ]; then
    ULIMIT_WARN=4096
fi

# Registered process to wait for to consider start a success
WAIT_FOR_PROCESS={{runner_wait_process}}

WHOAMI=`id -un`

# erlexec requires HOME to be set. The username needs to be a
# unquoted literal because of the tilde expansion, hence the
# usage of eval.
if [ -z "$HOME" ]; then
    export HOME=`eval echo "~$WHOAMI"`
fi

# Echo to stderr on errors
echoerr() { echo "$@" 1>&2; }

# Extract the target node name from node.args
NAME_ARG=`egrep '^\-name' $RUNNER_ETC_DIR/vm.args 2> /dev/null`
if [ -z "$NAME_ARG" ]; then
    NODENAME=`egrep '^[ \t]*nodename[ \t]*=[ \t]*' $RUNNER_ETC_DIR/{{cuttlefish_conf}} 2> /dev/null | tail -1 | cut -d = -f 2`
    if [ -z "$NODENAME" ]; then
        echoerr "vm.args needs to have a -name parameter."
        echoerr "  -sname is not supported."
        exit 1
    else
        NAME_ARG="-name ${NODENAME# *}"
    fi
fi

# Learn how to specify node name for connection from remote nodes
NAME_PARAM="-name"
echo "$NAME_ARG" | grep '@.*' > /dev/null 2>&1
if [ "X$?" = "X0" ]; then
    NAME_HOST=`echo "${NAME_ARG}" | sed -e 's/.*\(@.*\)$/\1/'`
else
    NAME_HOST=""
fi

# Extract the target cookie
COOKIE_ARG=`grep '^\-setcookie' $RUNNER_ETC_DIR/vm.args 2> /dev/null`
if [ -z "$COOKIE_ARG" ]; then
    COOKIE=`egrep '^[ \t]*distributed_cookie[ \t]*=[ \t]*' $RUNNER_ETC_DIR/{{cuttlefish_conf}} 2> /dev/null | tail -1 | cut -d = -f 2`
    if [ -z "$COOKIE" ]; then
        echoerr "vm.args needs to have a -setcookie parameter."
        exit 1
    else
        COOKIE_ARG="-setcookie $COOKIE"
    fi
fi

# Extract the target net_ticktime
NET_TICKTIME_ARG=`grep '^\-kernel net_ticktime' $RUNNER_ETC_DIR/vm.args 2> /dev/null`
if [ -z "$NET_TICKTIME_ARG" ]; then
    NET_TICKTIME=`egrep '^[ \t]*erlang.distribution.net_ticktime[ \t]*=[ \t]*' $RUNNER_ETC_DIR/{{cuttlefish_conf}} 2> /dev/null | tail -1 | cut -d = -f 2`
    if [ -z "$NET_TICKTIME" ]; then
        NET_TICKTIME_ARG=""
    else
        NET_TICKTIME_ARG="-kernel net_ticktime $NET_TICKTIME"
    fi
fi

# Optionally specify a NUMA policy
NUMACTL_ARG="{{numactl_arg}}"
if [ -z "$NUMACTL_ARG" ]
then
    NUMACTL=""
# Confirms `numactl` is in the path and validates $NUMACTL_ARG
elif which numactl > /dev/null 2>&1 && numactl $NUMACTL_ARG ls /dev/null > /dev/null 2>&1
then
    NUMACTL="numactl $NUMACTL_ARG"
else
    echoerr "NUMACTL_ARG is specified in env.sh but numactl is not installed or NUMACTL_ARG is invalid."
    exit 1
fi

# Parse out release and erts info
START_ERL=`cat $RUNNER_BASE_DIR/releases/start_erl.data`
ERTS_VSN=${START_ERL% *}
APP_VSN=${START_ERL#* }

# Add ERTS bin dir to our path
ERTS_PATH=$RUNNER_BASE_DIR/erts-$ERTS_VSN/bin

# Setup command to control the node
NODETOOL="$ERTS_PATH/escript $ERTS_PATH/nodetool $NET_TICKTIME_ARG $NAME_ARG $COOKIE_ARG"
NODETOOL_LITE="$ERTS_PATH/escript $ERTS_PATH/nodetool"

## Are we using cuttlefish (http://github.com/basho/cuttlefish)
## for configuration. This needs to come after the $ERTS_PATH
## definition
CUTTLEFISH="{{cuttlefish}}"
if [ -z "$CUTTLEFISH" ]; then
    CUTTLEFISH_COMMAND_PREFIX=""
else
    CUTTLEFISH_COMMAND_PREFIX="$ERTS_PATH/escript $ERTS_PATH/cuttlefish -e $RUNNER_ETC_DIR -s $RUNNER_LIB_DIR -d {{platform_data_dir}}/generated.configs -c $RUNNER_ETC_DIR/{{cuttlefish_conf}}"
fi

# Ping node without stealing stdin
ping_node() {
    $NODETOOL ping < /dev/null
}

# Attempts to create a pid directory like /var/run/APPNAME and then
# changes the permissions on that directory so the $RUNNER_USER can
# read/write/delete .pid files during startup/shutdown
create_pid_dir() {
    # Validate RUNNER_USER is set and they have permissions to write to /var/run
    # Don't continue if we've already su'd to RUNNER_USER
    if ([ "$RUNNER_USER" ] && [ "x$WHOAMI" != "x$RUNNER_USER" ]); then
        if [ -w $RUN_DIR ]; then
            mkdir -p $PID_DIR
            ES=$?
            if [ "$ES" -ne 0 ]; then
                return 1
            else
                # Change permissions on $PID_DIR
                chown $RUNNER_USER $PID_DIR
                ES=$?
                if [ "$ES" -ne 0 ]; then
                    return 1
                else
                    return 0
                fi
            fi
        else
            # If we don't have permissions, fail
            return 1
        fi
    fi

    # If RUNNER_USER is not set this is probably a test setup (devrel) and does
    # not need a .pid file, so do not return error
    return 0
}

# Attempt to create a pid file for the process
# This function assumes the process is already up and running and can
#    respond to a getpid call.  It also assumes that two processes
#    with the same name will not be run on the machine
# Do not print any error messages as failure to create a pid file because
#    pid files are strictly optional
# This function should really only be called in a "start" function
#    you have been warned
create_pid_file() {
    # Validate a pid directory even exists
    if [ -w $PID_DIR ]; then
        # Grab the proper pid from getpid
        get_pid
        ES=$?
        if [ "$ES" -ne 0 ]; then
            return $ES
        else
            # Remove pid file if it already exists since we do not
            # plan for multiple identical runners on a single machine
            rm -f $PID_FILE
            echo $PID > $PID_FILE
            return 0
        fi
    else
        return 1
    fi
}

# Simple way to check the correct user and fail early
check_user_internal() {
    # Validate that the user running the script is the owner of the
    # RUN_DIR.
    if ([ "$RUNNER_USER" ] && [ "x$WHOAMI" != "x$RUNNER_USER" ]); then
        if [ "x$WHOAMI" != "xroot" ]; then
            echo "You need to be root or use sudo to run this command"
            exit 1
        fi
    fi
}

# Function to su into correct user that is poorly named for historical
# reasons (excuses)
# This also serves as an entry point to most functions
check_user() {
    check_user_internal

    # This call must be before the su call, when the user is dropped
    # optional config will be brought in if available
    load_default_os_config

    # do not su again if we are already the runner user
    if ([ "$RUNNER_USER" ] && [ "x$WHOAMI" != "x$RUNNER_USER" ]); then
        # Escape any double quotes that might be in the command line
        # args. Without this, passing something like JSON on the command
        # line will get stripped.
        #  Ex:
        #     riak-admin bucket-type create mytype '{"props": {"n_val": 4}}'
        #  would become
        #     riak-admin bucket-type create mytype {props: {n_val: 4}}
        #  after the arguments were passed into the new shell during exec su
        #
        # So this regex finds any '(', ')', "'" , '"', '{', or '}' and prepends with a '\'
        ESCAPED_ARGS=`echo "$@" | sed -e 's/\([\\\(\\\){}"\x27]\)/\\\\\1/g'`

        # This will drop priviledges into the runner user
        # It exec's in a new shell and the current shell will exit
        exec su - $RUNNER_USER -c "$RUNNER_SCRIPT_DIR/$RUNNER_SCRIPT $ESCAPED_ARGS"
    fi
}

# Function to load default config files based on OS
load_default_os_config() {
    # Only run this if we already dropped to the runner user
    if ([ "$RUNNER_USER" ] && [ "x$WHOAMI" = "x$RUNNER_USER" ]); then
        # Common config file on Debian-like systems
        [ -r /etc/default/$RUNNER_SCRIPT ] && . /etc/default/$RUNNER_SCRIPT

        # Common config file on RPM-like systems
        [ -r /etc/sysconfig/$RUNNER_SCRIPT ] && . /etc/sysconfig/$RUNNER_SCRIPT
    fi
}

# Function to validate the node is down
node_down_check() {
    MUTE=`ping_node 2> /dev/null`
    if [ "$?" -eq 0 ]; then
        echoerr "Node is already running!"
        exit 1
    fi
}

# Function to validate the node is up
node_up_check() {
    MUTE=`ping_node 2> /dev/null`
    if [ "$?" -ne 0 ]; then
        echoerr "Node did not respond to ping!"
        exit 1
    fi
}

# Function to check if the config file is valid
check_config() {
    if [ -z "$CUTTLEFISH" ]; then
        # Note: we have added a parameter '-vm_args' to this. It
        # appears redundant but it is not! the erlang vm allows us to
        # access all arguments to the erl command EXCEPT '-args_file',
        # so in order to get access to this file location from within
        # the vm, we need to pass it in twice.
        CONFIG_ARGS=" -config $RUNNER_ETC_DIR/app.config -args_file $RUNNER_ETC_DIR/vm.args -vm_args $RUNNER_ETC_DIR/vm.args "
    else
        CONFIG_ARGS=`$CUTTLEFISH_COMMAND_PREFIX generate`
        if [ "$?" -ne 0 ]; then
            echoerr "Error generating config with cuttlefish"
            echoerr "  run \`$RUNNER_SCRIPT config generate -l debug\` for more information."
            exit 1
        fi
    fi

    MUTE=`$NODETOOL_LITE chkconfig $CONFIG_ARGS`
    if [ "$?" -ne 0 ]; then
        echoerr "Error reading $CONFIG_ARGS"
        exit 1
    fi
    echo "config is OK"
    echo $CONFIG_ARGS
}

# Function to check if ulimit is properly set
check_ulimit() {

    # don't fail if this is unset
    if [ ! -z "$ULIMIT_WARN" ]; then
        ULIMIT_F=`ulimit -n`
        if [ "$ULIMIT_F" -lt $ULIMIT_WARN ]; then
            echo "!!!!"
            echo "!!!! WARNING: ulimit -n is ${ULIMIT_F}; ${ULIMIT_WARN} is the recommended minimum."
            echo "!!!!"
        fi
    fi
}

# Set the PID global variable, return 1 on error
get_pid() {
    PID=`$NODETOOL getpid < /dev/null`
    if [ "$?" -ne 0 ]; then
        echo "Node is not running!"
        return 1
    fi

    # don't allow empty or init pid's
    if [ -z $PID ] || [ "$PID" -le 1 ]; then
        return 1
    fi

    return 0
}


text:
package org.pentaho.di.trans.steps.mailvalidator;

public class MailValidationResult {

  private boolean isvalide;

  private String errMsg;

  public MailValidationResult() {
    this.isvalide = false;
    this.errMsg = null;
  }

  public boolean isValide() {
    return this.isvalide;
  }

  public void setValide( boolean valid ) {
    this.isvalide = valid;
  }

  public String getErrorMessage() {
    return this.errMsg;
  }

  public void setErrorMessage( String errMsg ) {
    this.errMsg = errMsg;
  }

}


text:
using System.Threading.Tasks;
using Box.V2.Managers;
using Box.V2.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Box.V2.Test
{
    [TestClass]
    public class BoxCollaborationsManagerTest : BoxResourceManagerTest
    {
        private readonly BoxCollaborationsManager _collaborationsManager;

        public BoxCollaborationsManagerTest()
        {
            _collaborationsManager = new BoxCollaborationsManager(Config.Object, Service, Converter, AuthRepository);
        }

        [TestMethod]
        public async Task AddCollaboration_ValidResponse_ValidCollaboration()
        {
            /*** Arrange ***/
            var responseString = "{\"type\":\"collaboration\",\"id\":\"791293\",\"created_by\":{\"type\":\"user\",\"id\":\"17738362\",\"name\":\"sean rose\",\"login\":\"sean@box.com\"},\"created_at\":\"2012-12-12T10:54:37-08:00\",\"modified_at\":\"2012-12-12T11:30:43-08:00\",\"expires_at\":null,\"status\":\"accepted\",\"accessible_by\":{\"type\":\"user\",\"id\":\"18203124\",\"name\":\"sean\",\"login\":\"sean+test@box.com\"},\"role\":\"editor\",\"acknowledged_at\":\"2012-12-12T11:30:43-08:00\",\"item\":{\"type\":\"folder\",\"id\":\"11446500\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"Shared Pictures\"}}";
            Handler.Setup(h => h.ExecuteAsync<BoxCollaboration>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollaboration>>(new BoxResponse<BoxCollaboration>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            /*** Act ***/
            var request = new BoxCollaborationRequest()
            {
                Item = new BoxRequestEntity()
                {
                    Id = "fakeId",
                    Type = BoxType.file
                },
                AccessibleBy = new BoxCollaborationUserRequest()
                {
                    Id = "fakeId",
                    Login = "fakeLogin"
                },
                Role = "fakeRole"
            };

            BoxCollaboration collab = await _collaborationsManager.AddCollaborationAsync(request);

            /*** Assert ***/
            Assert.AreEqual("791293", collab.Id);
            Assert.AreEqual("collaboration", collab.Type);
            Assert.AreEqual("user", collab.CreatedBy.Type);
            Assert.AreEqual("17738362", collab.CreatedBy.Id);
            Assert.AreEqual("sean@box.com", collab.CreatedBy.Login);
        }

        [TestMethod]
        public async Task EditCollaboration_ValidResponse_ValidCollaboration()
        {
            /*** Arrange ***/
            var responseString = "{\"type\":\"collaboration\",\"id\":\"791293\",\"created_by\":{\"type\":\"user\",\"id\":\"17738362\",\"name\":\"sean rose\",\"login\":\"sean@box.com\"},\"created_at\":\"2012-12-12T10:54:37-08:00\",\"modified_at\":\"2012-12-12T11:30:43-08:00\",\"expires_at\":null,\"status\":\"accepted\",\"accessible_by\":{\"type\":\"user\",\"id\":\"18203124\",\"name\":\"sean\",\"login\":\"sean+test@box.com\"},\"role\":\"viewer\",\"acknowledged_at\":\"2012-12-12T11:30:43-08:00\",\"item\":{\"type\":\"folder\",\"id\":\"11446500\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"Shared Pictures\"}}";
            Handler.Setup(h => h.ExecuteAsync<BoxCollaboration>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollaboration>>(new BoxResponse<BoxCollaboration>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            /*** Act ***/
            var request = new BoxCollaborationRequest()
            {
                Id = "fakeId"
            };

            BoxCollaboration collab = await _collaborationsManager.EditCollaborationAsync(request);

            /*** Assert ***/
            Assert.AreEqual("791293", collab.Id);
            Assert.AreEqual("collaboration", collab.Type);
            Assert.AreEqual("user", collab.CreatedBy.Type);
            Assert.AreEqual("17738362", collab.CreatedBy.Id);
            Assert.AreEqual("sean@box.com", collab.CreatedBy.Login);
        }

        [TestMethod]
        public async Task GetCollaboration_ValidResponse_ValidCollaboration()
        {
            /*** Arrange ***/
            var responseString = "{\"type\":\"collaboration\",\"id\":\"791293\",\"created_by\":{\"type\":\"user\",\"id\":\"17738362\",\"name\":\"sean rose\",\"login\":\"sean@box.com\"},\"created_at\":\"2012-12-12T10:54:37-08:00\",\"modified_at\":\"2012-12-12T11:30:43-08:00\",\"expires_at\":null,\"status\":\"accepted\",\"accessible_by\":{\"type\":\"user\",\"id\":\"18203124\",\"name\":\"sean\",\"login\":\"sean+test@box.com\"},\"role\":\"editor\",\"acknowledged_at\":\"2012-12-12T11:30:43-08:00\",\"item\":{\"type\":\"folder\",\"id\":\"11446500\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"Shared Pictures\"}}";
            Handler.Setup(h => h.ExecuteAsync<BoxCollaboration>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollaboration>>(new BoxResponse<BoxCollaboration>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            /*** Act ***/
            BoxCollaboration collab = await _collaborationsManager.GetCollaborationAsync("fakeId");

            /*** Assert ***/
            Assert.AreEqual("791293", collab.Id);
            Assert.AreEqual("collaboration", collab.Type);
            Assert.AreEqual("user", collab.CreatedBy.Type);
            Assert.AreEqual("17738362", collab.CreatedBy.Id);
            Assert.AreEqual("sean@box.com", collab.CreatedBy.Login);
        }

        [TestMethod]
        public async Task GetPendingCollaboration_ValidResponse_ValidEntries()
        {
            /*** Arrange ***/
            var responseString = @"{
                    ""total_count"": 1,
                    ""entries"": [
                        {
                            ""type"": ""collaboration"",
                            ""id"": ""27513888"",
                            ""created_by"": {
                                ""type"": ""user"",
                                ""id"": ""11993747"",
                                ""name"": ""sean"",
                                ""login"": ""sean@box.com""
                            },
                            ""created_at"": ""2012-10-17T23:14:42-07:00"",
                            ""modified_at"": ""2012-10-17T23:14:42-07:00"",
                            ""expires_at"": null,
                            ""status"": ""Pending"",
                            ""accessible_by"": {
                                ""type"": ""user"",
                                ""id"": ""181216415"",
                                ""name"": ""sean rose"",
                                ""login"": ""sean+awesome@box.com""
                            },
                            ""role"": ""Editor"",
                            ""acknowledged_at"": null,
                            ""invite_email"": ""collab@example.com"",
                            ""item"": null
                        }
                    ]
                }";

            IBoxRequest boxRequest = null;
            Handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxCollaboration>>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollection<BoxCollaboration>>>(new BoxResponse<BoxCollection<BoxCollaboration>>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }))
                .Callback<IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            BoxCollection<BoxCollaboration> collaborations = await _collaborationsManager.GetPendingCollaborationAsync();

            /*** Assert ***/
            Assert.AreEqual(1, collaborations.TotalCount);
            Assert.AreEqual("27513888", collaborations.Entries[0].Id);
            Assert.AreEqual("collaboration", collaborations.Entries[0].Type);
            Assert.AreEqual("user", collaborations.Entries[0].AccessibleBy.Type);
            Assert.AreEqual("181216415", collaborations.Entries[0].AccessibleBy.Id);
            Assert.AreEqual("collab@example.com", collaborations.Entries[0].InviteEmail);
        }

        [TestMethod]
        public async Task DeleteCollaboration_ValidResponse_CollaborationDeleted()
        {
            /*** Arrange ***/
            var responseString = "";
            Handler.Setup(h => h.ExecuteAsync<BoxCollaboration>(It.IsAny<IBoxRequest>()))
                .Returns(Task.FromResult<IBoxResponse<BoxCollaboration>>(new BoxResponse<BoxCollaboration>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = responseString
                }));

            /*** Act ***/
            var result = await _collaborationsManager.RemoveCollaborationAsync("34122832467");

            /*** Assert ***/

            Assert.AreEqual(true, result);
        }

    }

}


text:
package net.mcft.copy.core.tweak;

import net.mcft.copy.core.util.StackUtils;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;

/** Auto replaces used-up stacks and broken items in a player's inventory,
 *  if items of the same type exist in the same column above the item. <br>
 *  This tweak only works server-side. */
public final class TweakAutoReplace extends Tweak {

	public static final TweakAutoReplace instance = new TweakAutoReplace();

	private TweakAutoReplace() {  }

	@Override
	protected void enable() {
		MinecraftForge.EVENT_BUS.register(this);
	}

	@Override
	protected void disable() {
		MinecraftForge.EVENT_BUS.unregister(this);
	}

	@SubscribeEvent
	public void onPlayerDestroyItem(PlayerDestroyItemEvent event) {

		if (!(event.entity instanceof EntityPlayerMP) ||
		    event.entity.worldObj.isRemote) return;

		EntityPlayerMP player = (EntityPlayerMP)event.entityPlayer;
		InventoryPlayer inv = player.inventory;

		ItemStack currentItem = inv.getCurrentItem();
		if ((currentItem != null) &&
		    (currentItem != event.original)) return;

		int row;
		for (row = 2; row >= 0; row--) {
			int slot = inv.currentItem + row * 9 + 9;
			ItemStack stackAbove = inv.getStackInSlot(slot);
			if (!canReplace(stackAbove, event.original)) break;
			int targetSlot = ((slot < 27) ? (slot + 9) : (slot - 27));
			inv.setInventorySlotContents(targetSlot, stackAbove);
			inv.setInventorySlotContents(slot, null);
			player.playerNetServerHandler.sendPacket(
					new S2FPacketSetSlot(0, slot + 9, stackAbove));
		}

		if (row < 2)
			player.playerNetServerHandler.sendPacket(
					new S2FPacketSetSlot(0, inv.currentItem + row * 9 + 18, null));

	}

	/** Returns if the destroyed item can be replaced with this item. */
	private static boolean canReplace(ItemStack replacement, ItemStack destroyed) {
		// TODO: Allow tools of the same type to act as replacement?
		// Also, maybe allow the same item with different NBT data (enchantments)?
		return StackUtils.equals(replacement, destroyed, false, true, !destroyed.getItem().isDamageable());
	}

}


text:
.. _tutorial-manipulation:

==================================
 Advanced Expression Manipulation
==================================

In this section, we discuss some ways that we can perform advanced
manipulation of expressions.

Understanding Expression Trees
==============================

.. sidebar :: Quick Tip

   To play with the ``srepr`` form of expressions in the SymPy Live shell,
   change the output format to ``Repr`` in the settings.

Before we can do this, we need to understand how expressions are represented
in SymPy.  A mathematical expression is represented as a tree.  Let us take
the expression `2^x + xy`, i.e., ``2**x + x*y``.  We can see what this
expression looks like internally by using ``srepr``

    >>> from sympy import *
    >>> x, y, z = symbols('x y z')

    >>> expr = 2**x + x*y
    >>> srepr(expr)
    "Add(Pow(Integer(2), Symbol('x')), Mul(Symbol('x'), Symbol('y')))"

The easiest way to tear this apart is to look at a diagram of the expression
tree:

.. This comes from dotprint(2**x + x*y, labelfunc=srepr)

.. graphviz::

    digraph{

    # Graph style
    "rankdir"="TD"

    #########
    # Nodes #
    #########

    "Symbol(x)_(0, 0)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Integer(2)_(1, 1)" ["color"="black", "label"="Integer(2)", "shape"="ellipse"];
    "Symbol(y)_(0, 1)" ["color"="black", "label"="Symbol('y')", "shape"="ellipse"];
    "Symbol(x)_(1, 0)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Mul(Symbol(x), Symbol(y))_(0,)" ["color"="black", "label"="Mul", "shape"="ellipse"];
    "Pow(Symbol(x), Integer(2))_(1,)" ["color"="black", "label"="Pow", "shape"="ellipse"];
    "Add(Mul(Symbol(x), Symbol(y)), Pow(Symbol(x), Integer(2)))_()" ["color"="black", "label"="Add", "shape"="ellipse"];

    #########
    # Edges #
    #########

    "Mul(Symbol(x), Symbol(y))_(0,)" -> "Symbol(x)_(0, 0)";
    "Mul(Symbol(x), Symbol(y))_(0,)" -> "Symbol(y)_(0, 1)";
    "Pow(Symbol(x), Integer(2))_(1,)" -> "Symbol(x)_(1, 0)";
    "Pow(Symbol(x), Integer(2))_(1,)" -> "Integer(2)_(1, 1)";
    "Add(Mul(Symbol(x), Symbol(y)), Pow(Symbol(x), Integer(2)))_()" -> "Mul(Symbol(x), Symbol(y))_(0,)";
    "Add(Mul(Symbol(x), Symbol(y)), Pow(Symbol(x), Integer(2)))_()" -> "Pow(Symbol(x), Integer(2))_(1,)";
    }

.. note::

   The above diagram was made using `Graphviz <http://www.graphviz.org/>`_ and
   the :py:meth:`dotprint <sympy.printing.dot.dotprint>` function.

First, let's look at the leaves of this tree.  Symbols are instances of the
class Symbol.  While we have been doing

    >>> x = symbols('x')

we could have also done

    >>> x = Symbol('x')

Either way, we get a Symbol with the name "x" [#symbols-fn]_.  For the number in the
expression, 2, we got ``Integer(2)``.  ``Integer`` is the SymPy class for
integers.  It is similar to the Python built-in type ``int``, except that
``Integer`` plays nicely with other SymPy types.

When we write ``2**x``, this creates a ``Pow`` object.  ``Pow`` is short for
"power".

    >>> srepr(2**x)
    "Pow(Integer(2), Symbol('x'))"

We could have created the same object by calling ``Pow(2, x)``

    >>> Pow(2, x)
    2**x

Note that in the ``srepr`` output, we see ``Integer(2)``, the SymPy version of
integers, even though technically, we input ``2``, a Python int.  In general,
whenever you combine a SymPy object with a non-SymPy object via some function
or operation, the non-SymPy object will be converted into a SymPy object.  The
function that does this is ``sympify`` [#sympify-fn]_.

    >>> type(2)
    <... 'int'>
    >>> type(sympify(2))
    <class 'sympy.core.numbers.Integer'>

We have seen that ``2**x`` is represented as ``Pow(2, x)``.  What about
``x*y``?  As we might expect, this is the multiplication of ``x`` and ``y``.
The SymPy class for multiplication is ``Mul``.

    >>> srepr(x*y)
    "Mul(Symbol('x'), Symbol('y'))"

Thus, we could have created the same object by writing ``Mul(x, y)``.

    >>> Mul(x, y)
    x*y

Now we get to our final expression, ``2**x + x*y``.  This is the addition of
our last two objects, ``Pow(2, x)``, and ``Mul(x, y)``.  The SymPy class for
addition is ``Add``, so, as you might expect, to create this object, we use
``Add(Pow(2, x), Mul(x, y))``.

    >>> Add(Pow(2, x), Mul(x, y))
    2**x + x*y

SymPy expression trees can have many branches, and can be quite deep or quite
broad.  Here is a more complicated example

    >>> expr = sin(x*y)/2 - x**2 + 1/y
    >>> srepr(expr)
    "Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2),
    sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"

Here is a diagram

.. dotprint(sin(x*y)/2 - x**2 + 1/y, labelfunc=srepr)

.. graphviz::

    digraph{

    # Graph style
    "rankdir"="TD"

    #########
    # Nodes #
    #########

    "Half()_(0, 0)" ["color"="black", "label"="Rational(1, 2)", "shape"="ellipse"];
    "Symbol(y)_(2, 0)" ["color"="black", "label"="Symbol('y')", "shape"="ellipse"];
    "Symbol(x)_(1, 1, 0)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Integer(2)_(1, 1, 1)" ["color"="black", "label"="Integer(2)", "shape"="ellipse"];
    "NegativeOne()_(2, 1)" ["color"="black", "label"="Integer(-1)", "shape"="ellipse"];
    "NegativeOne()_(1, 0)" ["color"="black", "label"="Integer(-1)", "shape"="ellipse"];
    "Symbol(y)_(0, 1, 0, 1)" ["color"="black", "label"="Symbol('y')", "shape"="ellipse"];
    "Symbol(x)_(0, 1, 0, 0)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Pow(Symbol(x), Integer(2))_(1, 1)" ["color"="black", "label"="Pow", "shape"="ellipse"];
    "Pow(Symbol(y), NegativeOne())_(2,)" ["color"="black", "label"="Pow", "shape"="ellipse"];
    "Mul(Symbol(x), Symbol(y))_(0, 1, 0)" ["color"="black", "label"="Mul", "shape"="ellipse"];
    "sin(Mul(Symbol(x), Symbol(y)))_(0, 1)" ["color"="black", "label"="sin", "shape"="ellipse"];
    "Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)" ["color"="black", "label"="Mul", "shape"="ellipse"];
    "Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)" ["color"="black", "label"="Mul", "shape"="ellipse"];
    "Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()" ["color"="black", "label"="Add", "shape"="ellipse"];

    #########
    # Edges #
    #########

    "Pow(Symbol(y), NegativeOne())_(2,)" -> "Symbol(y)_(2, 0)";
    "Pow(Symbol(x), Integer(2))_(1, 1)" -> "Symbol(x)_(1, 1, 0)";
    "Pow(Symbol(x), Integer(2))_(1, 1)" -> "Integer(2)_(1, 1, 1)";
    "Pow(Symbol(y), NegativeOne())_(2,)" -> "NegativeOne()_(2, 1)";
    "Mul(Symbol(x), Symbol(y))_(0, 1, 0)" -> "Symbol(x)_(0, 1, 0, 0)";
    "Mul(Symbol(x), Symbol(y))_(0, 1, 0)" -> "Symbol(y)_(0, 1, 0, 1)";
    "Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)" -> "Half()_(0, 0)";
    "Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)" -> "NegativeOne()_(1, 0)";
    "sin(Mul(Symbol(x), Symbol(y)))_(0, 1)" -> "Mul(Symbol(x), Symbol(y))_(0, 1, 0)";
    "Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)" -> "Pow(Symbol(x), Integer(2))_(1, 1)";
    "Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)" -> "sin(Mul(Symbol(x), Symbol(y)))_(0, 1)";
    "Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()" -> "Pow(Symbol(y), NegativeOne())_(2,)";
    "Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()" -> "Mul(Half(), sin(Mul(Symbol(x), Symbol(y))))_(0,)";
    "Add(Mul(Half(), sin(Mul(Symbol(x), Symbol(y)))), Mul(NegativeOne(), Pow(Symbol(x), Integer(2))), Pow(Symbol(y), NegativeOne()))_()" -> "Mul(NegativeOne(), Pow(Symbol(x), Integer(2)))_(1,)";
    }

This expression reveals some interesting things about SymPy expression
trees. Let's go through them one by one.

Let's first look at the term ``x**2``.  As we expected, we see ``Pow(x, 2)``.
One level up, we see we have ``Mul(-1, Pow(x, 2))``.  There is no subtraction
class in SymPy.  ``x - y`` is represented as ``x + -y``, or, more completely,
``x + -1*y``, i.e., ``Add(x, Mul(-1, y))``.

    >>> expr = x - y
    >>> srepr(x - y)
    "Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))"

.. dotprint(x - y, labelfunc=srepr)

.. graphviz::

    digraph{

    # Graph style
    "rankdir"="TD"

    #########
    # Nodes #
    #########

    "Symbol(x)_(1,)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Symbol(y)_(0, 1)" ["color"="black", "label"="Symbol('y')", "shape"="ellipse"];
    "NegativeOne()_(0, 0)" ["color"="black", "label"="Integer(-1)", "shape"="ellipse"];
    "Mul(NegativeOne(), Symbol(y))_(0,)" ["color"="black", "label"="Mul", "shape"="ellipse"];
    "Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()" ["color"="black", "label"="Add", "shape"="ellipse"];

    #########
    # Edges #
    #########

    "Mul(NegativeOne(), Symbol(y))_(0,)" -> "Symbol(y)_(0, 1)";
    "Mul(NegativeOne(), Symbol(y))_(0,)" -> "NegativeOne()_(0, 0)";
    "Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()" -> "Symbol(x)_(1,)";
    "Add(Mul(NegativeOne(), Symbol(y)), Symbol(x))_()" -> "Mul(NegativeOne(), Symbol(y))_(0,)";
    }

Next, look at ``1/y``.  We might expect to see something like ``Div(1, y)``,
but similar to subtraction, there is no class in SymPy for division.  Rather,
division is represented by a power of -1.  Hence, we have ``Pow(y, -1)``.
What if we had divided something other than 1 by ``y``, like ``x/y``?  Let's
see.

    >>> expr = x/y
    >>> srepr(expr)
    "Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))"

.. dotprint(x/y, labelfunc=srepr)

.. graphviz::

    digraph{

    # Graph style
    "rankdir"="TD"

    #########
    # Nodes #
    #########

    "Symbol(x)_(0,)" ["color"="black", "label"="Symbol('x')", "shape"="ellipse"];
    "Symbol(y)_(1, 0)" ["color"="black", "label"="Symbol('y')", "shape"="ellipse"];
    "NegativeOne()_(1, 1)" ["color"="black", "label"="Integer(-1)", "shape"="ellipse"];
    "Pow(Symbol(y), NegativeOne())_(1,)" ["color"="black", "label"="Pow", "shape"="ellipse"];
    "Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()" ["color"="black", "label"="Mul", "shape"="ellipse"];

    #########
    # Edges #
    #########

    "Pow(Symbol(y), NegativeOne())_(1,)" -> "Symbol(y)_(1, 0)";
    "Pow(Symbol(y), NegativeOne())_(1,)" -> "NegativeOne()_(1, 1)";
    "Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()" -> "Symbol(x)_(0,)";
    "Mul(Symbol(x), Pow(Symbol(y), NegativeOne()))_()" -> "Pow(Symbol(y), NegativeOne())_(1,)";
    }

We see that ``x/y`` is represented as ``x*y**-1``, i.e., ``Mul(x, Pow(y,
-1))``.

Finally, let's look at the ``sin(x*y)/2`` term.  Following the pattern of the
previous example, we might expect to see ``Mul(sin(x*y), Pow(Integer(2),
-1))``.  But instead, we have ``Mul(Rational(1, 2), sin(x*y))``.  Rational
numbers are always combined into a single term in a multiplication, so that
when we divide by 2, it is represented as multiplying by 1/2.

Finally, one last note.  You may have noticed that the order we entered our
expression and the order that it came out from ``srepr`` or in the graph were
different.  You may have also noticed this phenonemon earlier in the
tutorial.  For example

     >>> 1 + x
     x + 1

This because in SymPy, the arguments of the commutative operations ``Add`` and
``Mul`` are stored in an arbitrary (but consistent!) order, which is
independent of the order inputted (if you're worried about noncommutative
multiplication, don't be.  In SymPy, you can create noncommutative Symbols
using ``Symbol('A', commutative=False)``, and the order of multiplication for
noncommutative Symbols is kept the same as the input).  Furthermore, as we
shall see in the next section, the printing order and the order in which
things are stored internally need not be the same either.

.. sidebar:: Quick Tip

   The way an expression is represented internally and the way it is printed
   are often not the same.

In general, an important thing to keep in mind when working with SymPy expression
trees is this:  the internal representation of an expression and the way it is
printed need not be the same.  The same is true for the input form.   If some
expression manipulation algorithm is not working in the way you expected it
to, chances are, the internal representation of the object is different from
what you thought it was.

Recursing through an Expression Tree
====================================

Now that you know how expression trees work in SymPy, let's look at how to dig
our way through an expression tree.  Every object in SymPy has two very
important attributes, ``func``, and ``args``.

func
----

``func`` is the head of the object. For example, ``(x*y).func`` is ``Mul``.
Usually it is the same as the class of the object (though there are exceptions
to this rule).

Two notes about ``func``.  First, the class of an object need not be the same
as the one used to create it.  For example

    >>> expr = Add(x, x)
    >>> expr.func
    <class 'sympy.core.mul.Mul'>

We created ``Add(x, x)``, so we might expect ``expr.func`` to be ``Add``, but
instead we got ``Mul``.  Why is that?  Let's take a closer look at ``expr``.

    >>> expr
    2*x

``Add(x, x)``, i.e., ``x + x``, was automatically converted into ``Mul(2,
x)``, i.e., ``2*x``, which is a ``Mul``.   SymPy classes make heavy use of the
``__new__`` class constructor, which, unlike ``__init__``, allows a different
class to be returned from the constructor.

Second, some classes are special-cased, usually for efficiency reasons
[#singleton-fn]_.

    >>> Integer(2).func
    <class 'sympy.core.numbers.Integer'>
    >>> Integer(0).func
    <class 'sympy.core.numbers.Zero'>
    >>> Integer(-1).func
    <class 'sympy.core.numbers.NegativeOne'>

For the most part, these issues will not bother us.  The special classes
``Zero``, ``One``, ``NegativeOne``, and so on are subclasses of ``Integer``,
so as long as you use ``isinstance``, it will not be an issue.

args
----

``args`` are the top-level arguments of the object.  ``(x*y).args`` would be
``(x, y)``.  Let's look at some examples

    >>> expr = 3*y**2*x
    >>> expr.func
    <class 'sympy.core.mul.Mul'>
    >>> expr.args
    (3, x, y**2)

From this, we can see that ``expr == Mul(3, y**2, x)``.  In fact, we can see
that we can completely reconstruct ``expr`` from its ``func`` and its
``args``.

    >>> expr.func(*expr.args)
    3*x*y**2
    >>> expr == expr.func(*expr.args)
    True

Note that although we entered ``3*y**2*x``, the ``args`` are ``(3, x, y**2)``.
In a ``Mul``, the Rational coefficient will come first in the ``args``, but
other than that, the order of everything else follows no special pattern.  To
be sure, though, there is an order.

    >>> expr = y**2*3*x
    >>> expr.args
    (3, x, y**2)

Mul's ``args`` are sorted, so that the same ``Mul`` will have the same
``args``.  But the sorting is based on some criteria designed to make the
sorting unique and efficient that has no mathematical significance.

The ``srepr`` form of our ``expr`` is ``Mul(3, x, Pow(y, 2))``.  What if we
want to get at the ``args`` of ``Pow(y, 2)``.  Notice that the ``y**2`` is in
the third slot of ``expr.args``, i.e., ``expr.args[2]``.

    >>> expr.args[2]
    y**2

So to get the ``args`` of this, we call ``expr.args[2].args``.

    >>> expr.args[2].args
    (y, 2)

Now what if we try to go deeper.  What are the args of ``y``.  Or ``2``.
Let's see.

    >>> y.args
    ()
    >>> Integer(2).args
    ()

They both have empty ``args``.  In SymPy, empty ``args`` signal that we have
hit a leaf of the expression tree.

So there are two possibilities for a SymPy expression. Either it has empty
``args``, in which case it is a leaf node in any expression tree, or it has
``args``, in which case, it is a branch node of any expression tree.  When it
has ``args``, it can be completely rebuilt from its ``func`` and its ``args``.
This is expressed in the key invariant.

.. topic:: Key Invariant

   Every well-formed SymPy expression must either have empty ``args`` or
   satisfy ``expr == expr.func(*expr.args)``.

(Recall that in Python if ``a`` is a tuple, then ``f(*a)`` means to call ``f``
with arguments from the elements of ``a``, e.g., ``f(*(1, 2, 3))`` is the same
as ``f(1, 2, 3)``.)

This key invariant allows us to write simple algorithms that walk expression
trees, change them, and rebuild them into new expressions.

Walking the Tree
----------------

With this knowledge, let's look at how we can recurse through an expression
tree.  The nested nature of ``args`` is a perfect fit for recursive functions.
The base case will be empty ``args``.  Let's write a simple function that goes
through an expression and prints all the ``args`` at each level.

    >>> def pre(expr):
    ...     print(expr)
    ...     for arg in expr.args:
    ...         pre(arg)

See how nice it is that ``()`` signals leaves in the expression tree.  We
don't even have to write a base case for our recursion; it is handled
automatically by the for loop.

Let's test our function.

    >>> expr = x*y + 1
    >>> pre(expr)
    x*y + 1
    1
    x*y
    x
    y

Can you guess why we called our function ``pre``?  We just wrote a pre-order
traversal function for our expression tree.   See if you can write a
post-order traversal function.

Such traversals are so common in SymPy that the generator functions
``preorder_traversal`` and ``postorder_traversal`` are provided to make such
traversals easy.  We could have also written our algorithm as

    >>> for arg in preorder_traversal(expr):
    ...     print(arg)
    x*y + 1
    1
    x*y
    x
    y

.. rubric:: Footnotes

.. [#symbols-fn] We have been using ``symbols`` instead of ``Symbol`` because it
  automatically splits apart strings into multiple ``Symbol``\ s.
  ``symbols('x y z')`` returns a tuple of three ``Symbol``\ s.  ``Symbol('x y
  z')`` returns a single ``Symbol`` called ``x y z``.
.. [#sympify-fn] Technically, it is an internal function called ``_sympify``,
  which differs from ``sympify`` in that it does not convert strings.  ``x +
  '2'`` is not allowed.
.. [#singleton-fn] Classes like ``One`` and ``Zero`` are singletonized, meaning
  that only one object is ever created, no matter how many times the class is
  called.  This is done for space efficiency, as these classes are very
  common.  For example, ``Zero`` might occur very often in a sparse matrix
  represented densely.  As we have seen, ``NegativeOne`` occurs any time we
  have ``-x`` or ``1/x``.  It is also done for speed efficiency because
  singletonized objects can be compared by ``is``.  The unique objects for
  each singletonized class can be accessed from the ``S`` object.


text:
namespace TableDescriptor.Tests.Models
{
    public class HasTransient
    {
        public int Id { get; set; }
        public string Email { get; set; }

        [Transient]
        public string EmailTrimmed
        {
            get { return Email.Trim(); }
        }
    }

    public class MultipleKeysButIdentityForced
    {
        [Identity]
        public int ThisId { get; set; }
        public int ThatId { get; set; }
    }
}


text:
<!doctype html>
<html lang="zh-cmn-hans">
	<head>
		<mate charset="utf-8">
		<mate name="author" content="lyle">
		<title>Test-frameset</title>
		<link rel="stylesheet" href="css/Nreset.css"/>
		<link rel="stylesheet" href="css/public.css"/>
		<link rel="stylesheet" href="css/Test-frameset"/>
	</head>
	<frameset cols="20%,*" >
		<frame noresize="noresize" src="https://lyle19.github.io/Study-Web/%E5%9E%82%E7%9B%B4%E5%AF%BC%E8%88%AA%E6%A0%8F.html" scrolling="no" frameborder="0" name="fra">
		<frame noresize="noresize" src="https://lyle19.github.io/HTML-CSS/task1_5" frameborder="0" scrolling="yes" name="frame">
	</frameset>
	<body>
	</body>
</html>


text:
package resources

import "github.com/cloudfoundry/cli/cf/models"

type PaginatedServiceInstanceResources struct {
	TotalResults int `json:"total_results"`
	Resources    []ServiceInstanceResource
}

type ServiceInstanceResource struct {
	Resource
	Entity ServiceInstanceEntity
}

type LastOperation struct {
	Type        string `json:"type"`
	State       string `json:"state"`
	Description string `json:"description"`
}

type ServiceInstanceEntity struct {
	Name            string
	DashboardUrl    string                   `json:"dashboard_url"`
	ServiceBindings []ServiceBindingResource `json:"service_bindings"`
	ServicePlan     ServicePlanResource      `json:"service_plan"`
	LastOperation   LastOperation            `json:"last_operation"`
}

func (resource ServiceInstanceResource) ToFields() models.ServiceInstanceFields {
	return models.ServiceInstanceFields{
		Guid:         resource.Metadata.Guid,
		Name:         resource.Entity.Name,
		DashboardUrl: resource.Entity.DashboardUrl,
		LastOperation: models.LastOperationFields{
			Type:        resource.Entity.LastOperation.Type,
			State:       resource.Entity.LastOperation.State,
			Description: resource.Entity.LastOperation.Description,
		},
	}
}

func (resource ServiceInstanceResource) ToModel() (instance models.ServiceInstance) {
	instance.ServiceInstanceFields = resource.ToFields()
	instance.ServicePlan = resource.Entity.ServicePlan.ToFields()

	instance.ServiceBindings = []models.ServiceBindingFields{}
	for _, bindingResource := range resource.Entity.ServiceBindings {
		instance.ServiceBindings = append(instance.ServiceBindings, bindingResource.ToFields())
	}
	return
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
--><!DOCTYPE test SYSTEM "dom1.dtd">

<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="documentgetdoctype">
<metadata>
<title>documentGetDocType</title>
<creator>NIST</creator>
<description>
    The "getDoctype()" method returns the Document
   Type Declaration associated with this document.
   Retrieve the entire DOM document and invoke its
   "getDoctype()" method.  The name of the document
   type should be returned.  The "getName()" method
   should be equal to "staff" or "svg".
</description>
<contributor>Mary Brady</contributor>
<date qualifier="created">2001-08-17</date>
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-B63ED1A31"/>
<!--   Node.nodeValue   -->
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-F68D080"/>
<subject resource="http://www.w3.org/Bugs/Public/show_bug.cgi?id=249"/>
</metadata>
<var name="doc" type="Document"/>
<var name="docType" type="DocumentType"/>
<var name="docTypeName" type="DOMString"/>
<var name="nodeValue" type="DOMString"/>
<load var="doc" href="staff" willBeModified="false"/>
<doctype obj="doc" var="docType"/>
<assertNotNull actual="docType" id="docTypeNotNull"/>
<name interface="DocumentType" obj="docType" var="docTypeName"/>
<if><contentType type="image/svg+xml"/>
	<assertEquals actual="docTypeName" expected='"svg"' id="doctypeNameSVG" ignoreCase="false"/>
	<else>
		<assertEquals actual="docTypeName" expected='"staff"' id="doctypeName" ignoreCase="false"/>
	</else>
</if>
<nodeValue obj="docType" var="nodeValue"/>
<assertNull actual="nodeValue" id="initiallyNull"/>
</test>


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=8, path_list=[
		[TestAction.create_vm, 'vm1', ],
		[TestAction.create_volume, 'volume1', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume1'],
		[TestAction.create_volume, 'volume2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume, 'volume3', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume3'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot1'],
		[TestAction.clone_vm, 'vm1', 'vm2'],
		[TestAction.detach_volume, 'volume3'],
		[TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot5'],
		[TestAction.stop_vm, 'vm2'],
		[TestAction.ps_migrate_vm, 'vm2'],
		[TestAction.start_vm, 'vm2'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot6'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.ps_migrate_vm, 'vm1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.attach_volume, 'vm2', 'volume3'],
		[TestAction.create_vm_backup, 'vm1', 'vm1-backup1'],
		[TestAction.delete_vm_snapshot, 'vm2-snapshot5'],
])

'''
The final status:
Running:['vm2', 'vm1']
Stopped:[]
Enadbled:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1', 'vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'vm1-backup1', 'volume1-backup1', 'volume2-backup1']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:['vm2-snapshot5']
Expunged:[]
Ha:[]
Group:
	vm_snap3:['vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6']---vm1volume1_volume2
	vm_snap1:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1']---vm1volume1_volume2_volume3
	vm_backup1:['vm1-backup1', 'volume1-backup1', 'volume2-backup1']---vm1_volume1_volume2
'''


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [("hordak", "0016_check_account_type")]

    operations = [
        migrations.AlterModelOptions(
            name="transaction", options={"get_latest_by": "date"}
        )
    ]


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>imn-backgammon</groupId>
	<artifactId>extension-games</artifactId>
	<version>0.0.40-SNAPSHOT</version>
	<name>imn-backgammon-extension-games</name>
	<description>ichmags.net Backgammon Extension Games</description>
	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>1.7.13</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>imn-backgammon</groupId>
			<artifactId>engine-impl</artifactId>
			<version>0.0.40-SNAPSHOT</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.4</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<phase>verify</phase>
						<goals>
							<goal>jar-no-fork</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.3</version>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package sample.controller;

import java.util.*;

import org.springframework.web.bind.annotation.*;

import lombok.*;
import sample.ValidationException;
import sample.ValidationException.ErrorKeys;
import sample.context.actor.Actor;
import sample.context.security.*;
import sample.context.security.SecurityActorFinder.ActorDetails;

/**
 * 口座に関わる顧客のUI要求を処理します。
 */
@RestController
@RequestMapping("/api/account")
public class AccountController {

    private final SecurityProperties securityProps;

    public AccountController(SecurityProperties securityProps) {
        this.securityProps = securityProps;
    }

    /** ログイン状態を確認します。 */
    @GetMapping("/loginStatus")
    public boolean loginStatus() {
        return true;
    }

    /** 口座ログイン情報を取得します。 */
    @GetMapping("/loginAccount")
    public LoginAccount loadLoginAccount() {
        if (securityProps.auth().isEnabled()) {
            ActorDetails actorDetails = SecurityActorFinder.actorDetails()
                    .orElseThrow(() -> new ValidationException(ErrorKeys.Authentication));
            Actor actor = actorDetails.actor();
            return new LoginAccount(actor.getId(), actor.getName(), actorDetails.getAuthorityIds());
        } else { // for dummy login
            return new LoginAccount("sample", "sample", new ArrayList<>());
        }
    }

    /** クライアント利用用途に絞ったパラメタ */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class LoginAccount {
        private String id;
        private String name;
        private Collection<String> authorities;
    }

}


text:
#include <stdio.h>
#include <fcntl.h>
#ifdef __UC_LIBC__
#include <unistd.h>
#else
#include <crypt.h>
#endif
#include <syslog.h>
#include "md5.h"
#include "boa.h"
#ifdef SHADOW_AUTH
#include <shadow.h>
#endif
#ifdef OLD_CONFIG_PASSWORDS
#include <crypt_old.h>
#endif
#ifdef EMBED
#include <sys/types.h>
#include <pwd.h>
#include <config/autoconf.h>
#endif

#ifdef CONFIG_AMAZON
#include "../../login/logcnt.c"
#endif

#ifdef USE_AUTH

struct _auth_dir_ {
	char *directory;
	FILE *authfile;
	int dir_len;
	struct _auth_dir_ *next;
};

typedef struct _auth_dir_ auth_dir;

static auth_dir *auth_hashtable [AUTH_HASHTABLE_SIZE];
#ifdef OLD_CONFIG_PASSWORDS
char auth_old_password[16];
#endif

/*
 * Name: get_auth_hash_value
 *
 * Description: adds the ASCII values of the file letters
 * and mods by the hashtable size to get the hash value
 */
inline int get_auth_hash_value(char *dir)
{
#ifdef EMBED
	return 0;
#else
	unsigned int hash = 0;
	unsigned int index = 0;
	unsigned char c;

	hash = dir[index++];
	while ((c = dir[index++]) && c != '/')
		hash += (unsigned int) c;

	return hash % AUTH_HASHTABLE_SIZE;
#endif
}

/*
 * Name: auth_add
 *
 * Description: adds
 */
void auth_add(char *directory,char *file)
{
	auth_dir *new_a,*old;

	old = auth_hashtable [get_auth_hash_value(directory)];
	while (old)
	{
		if (!strcmp(directory,old->directory))
			return;
		old = old->next;
	}

	new_a = (auth_dir *)malloc(sizeof(auth_dir));
	/* success of this call will be checked later... */
	new_a->authfile = fopen(file,"rt");
	new_a->directory = strdup(directory);
	new_a->dir_len = strlen(directory);
	new_a->next = auth_hashtable [get_auth_hash_value(directory)];
	auth_hashtable [get_auth_hash_value(directory)] = new_a;
}

void auth_check()
{
	int hash;
	auth_dir *cur;

	for (hash=0;hash<AUTH_HASHTABLE_SIZE;hash++)
	{
  	cur = auth_hashtable [hash];
	  while (cur)
		{
			if (!cur->authfile)
			{
				log_error_time();
				fprintf(stderr,"Authentication password file for %s not found!\n",
						cur->directory);
			}
			cur = cur->next;
		}
	}
}

#ifdef LDAP_HACK
#include <lber.h>
#include <ldap.h>
#include <sg_configdd.h>
#include <sg_confighelper.h>
#include <sg_users.h>

/* Return a positive, negative or not possible result to the LDAP auth for
 * the specified user.
 */
static int ldap_auth(const char *const user, const char *const pswd) {
	static time_t last;
	static char *prev_user;
	LDAP *ld;
	int ldap_ver, r;
	char f[256];
	ConfigHandleType *c = config_load(amazon_ldap_config_dd);

	/* Don't repeat query too often if the user name hasn't changed */
	if (last && prev_user &&
			time(NULL) < (last + config_get_int(c, AMAZON_LDAP_CACHET)) &&
			strcmp(prev_user, user) == 0) {
		config_free(c);
		last = time(NULL);
		return 1;
	}
	if (prev_user != NULL)   { free(prev_user);	prev_user = NULL;   }
	last = 0;

	if ((ld = ldap_init(config_get_string(c, AMAZON_LDAP_HOST),
			config_get_int(c, AMAZON_LDAP_PORT))) == NULL) {
		syslog(LOG_ERR, "unable to initialise LDAP");
		config_free(c);
		return 0;
	}
	if (ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF) != LDAP_SUCCESS) {
		syslog(LOG_ERR, "unable to set LDAP referrals off");
		config_free(c);
		ldap_unbind(ld);
		return 0;
	}
	ldap_ver = config_get_int(c, AMAZON_LDAP_VERSION);
	if (ldap_ver > 0 && ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_ver) != LDAP_SUCCESS) {
		syslog(LOG_ERR, "unable to set LDAP version %d", ldap_ver);
		config_free(c);
		ldap_unbind(ld);
		return 0;
	}
	snprintf(f, sizeof f, config_get_string(c, AMAZON_LDAP_BIND_DN), user);
	r = ldap_simple_bind_s(ld, f, pswd);
	if (r != LDAP_SUCCESS) {
		syslog(LOG_ERR, "unable to connect to LDAP (%s)", ldap_err2string(r));
		config_free(c);
		ldap_unbind(ld);
		return (r==LDAP_INVALID_CREDENTIALS)?-1:0;
	}
	config_free(c);
	ldap_unbind(ld);
	/* Caching timing details for next time through */
	prev_user = strdup(user);
	last = time(NULL);
	return 1;
}
static unsigned char ldap_succ;
#endif

/*
 * Name: auth_check_userpass
 *
 * Description: Checks user's password. Returns 0 when sucessful and password
 * 	is ok, else returns nonzero; As one-way function is used RSA's MD5 w/
 *  BASE64 encoding.
#ifdef EMBED
 * On embedded environments we use crypt(), instead of MD5.
#endif
 */
int auth_check_userpass(char *user,char *pass,FILE *authfile)
{
#ifdef LDAP_HACK
	/* Yeah, code before declarations will fail on older compilers... */
	switch (ldap_auth(user, pass)) {
	case -1:	ldap_succ = 0;				return 1;
	case 0:		ldap_succ = strcmp(user, "root")?0:1;	break;
	case 1:
		ldap_succ = 1;
		if (start_user_update(0) == 0)
			done_user_update(set_user_password(user, pass, 0)==0?1:0);
		return 0;
	}
#endif
#ifdef SHADOW_AUTH
	struct spwd *sp;

	sp = getspnam(user);
	if (!sp)
		return 2;

	if (!strcmp(crypt(pass, sp->sp_pwdp), sp->sp_pwdp))
		return 0;

#else

#ifndef EMBED
	char temps[0x100],*pwd;
	struct MD5Context mc;
 	unsigned char final[16];
	char encoded_passwd[0x40];
  /* Encode password ('pass') using one-way function and then use base64
		 encoding. */
	MD5Init(&mc);
	MD5Update(&mc, pass, strlen(pass));
	MD5Final(final, &mc);
	strcpy(encoded_passwd,"$1$");
	base64encode(final, encoded_passwd+3, 16);

	DBG(printf("auth_check_userpass(%s,%s,...);\n",user,pass);)

	fseek(authfile,0,SEEK_SET);
	while (fgets(temps,0x100,authfile))
	{
		if (temps[strlen(temps)-1]=='\n')
			temps[strlen(temps)-1] = 0;
		pwd = strchr(temps,':');
		if (pwd)
		{
			*pwd++=0;
			if (!strcmp(temps,user))
			{
				if (!strcmp(pwd,encoded_passwd))
					return 0;
			} else
				return 2;
		}
	}
#else
	struct passwd *pwp;

	pwp = getpwnam(user);
	if (pwp != NULL) {
		if (strcmp(crypt(pass, pwp->pw_passwd), pwp->pw_passwd) == 0)
			return 0;
	} else
#ifdef OLD_CONFIG_PASSWORDS
	/* For backwards compatibility we allow the global root password to work too */
	if ((auth_old_password[0] != '\0') &&
			((*user == '\0') || (strcmp(user, "root") == 0))) {
		if (strcmp(crypt_old(pass,auth_old_password),auth_old_password) == 0 ||
				strcmp(crypt(pass,auth_old_password),auth_old_password) == 0) {
			strcpy(user, "root");
			return 0;
		}
	} else
#endif	/* OLD_CONFIG_PASSWORDS */
		return 2;

#endif	/* ! EMBED */
#endif	/* SHADOW_AUTH */
	return 1;
}

int auth_authorize(request * req)
{
	auth_dir *current;
  int hash;
	char *pwd;
	static char current_client[20];
	char auth_userpass[0x80];

  DBG(printf("auth_authorize\n");)

	hash = get_auth_hash_value(req->request_uri);
  current = auth_hashtable[hash];

  while (current) {
		if (!memcmp(req->request_uri, current->directory,
								current->dir_len)) {
			if (current->directory[current->dir_len - 1] != '/' &&
				        req->request_uri[current->dir_len] != '/' &&
								req->request_uri[current->dir_len] != '\0') {
				break;
			}
			if (req->authorization)
			{
				int denied = 1;
				if (current->authfile==0)
				{
					send_r_error(req);
					return 0;
				}
				if (strncasecmp(req->authorization,"Basic ",6))
				{
					syslog(LOG_ERR, "Can only handle Basic auth\n");
					send_r_bad_request(req);
					return 0;
				}

				base64decode(auth_userpass,req->authorization+6,sizeof(auth_userpass));

				if ( (pwd = strchr(auth_userpass,':')) == 0 )
				{
					syslog(LOG_ERR, "No user:pass in Basic auth\n");
					send_r_bad_request(req);
					return 0;
				}

				*pwd++=0;

				denied = auth_check_userpass(auth_userpass,pwd,current->authfile);
#ifdef CONFIG_AMAZON
				if (strncmp(get_mime_type(req->request_uri),"image/",6))
					access__attempted(denied, auth_userpass);
#endif
				if (denied) {
					switch (denied) {
						case 1:
							syslog(LOG_ERR, "Authentication attempt failed for %s from %s because: Bad Password\n",
									auth_userpass, req->remote_ip_addr);
							break;
						case 2:
							syslog(LOG_ERR, "Authentication attempt failed for %s from %s because: Invalid Username\n",
									auth_userpass, req->remote_ip_addr);
					}
					bzero(current_client, sizeof(current_client));
					send_r_unauthorized(req,server_name);
					return 0;
				}
				if (strcmp(current_client, req->remote_ip_addr) != 0) {
					strncpy(current_client, req->remote_ip_addr, sizeof(current_client));
					syslog(LOG_INFO, "Authentication successful for %s from %s\n", auth_userpass, req->remote_ip_addr);
				}
				/* Copy user's name to request structure */
#ifdef LDAP_HACK
				if (!ldap_succ) {
					strcpy(req->user, "noldap");
					syslog(LOG_INFO, "Access granted as noldap");
				} else
#endif
				strncpy(req->user, auth_userpass, 15);
				req->user[15] = '\0';
				return 1;
			}else
			{
				/* No credentials were supplied. Tell them that some are required */
				send_r_unauthorized(req,server_name);
				return 0;
			}
		}
	  current = current->next;
  }

	return 1;
}

void dump_auth(void)
{
	int i;
	auth_dir *temp;

	for (i = 0; i < AUTH_HASHTABLE_SIZE; ++i) {
		if (auth_hashtable[i]) {
			temp = auth_hashtable[i];
			while (temp) {
				auth_dir *temp_next;

				if (temp->directory)
					free(temp->directory);
				if (temp->authfile)
					fclose(temp->authfile);
				temp_next = temp->next;
				free(temp);
				temp = temp_next;
			}
			auth_hashtable[i] = NULL;
		}
	}
}

#endif


text:
package org.cradle.platform.vertx.httpgateway;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.commons.io.IOUtils;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.streams.ReadStream;

/**
 * Created by clement on 08/08/2014.
 */
public class AsyncInputStream implements ReadStream<AsyncInputStream> {

	public static final int STATUS_PAUSED = 0, STATUS_ACTIVE = 1, STATUS_CLOSED = 2;
	static final int DEFAULT_CHUNK_SIZE = 8192;

	private final Executor executor;
	private final PushbackInputStream in;
	private final int chunkSize;

	private int status = STATUS_ACTIVE;

	private Handler<Void> closeHandler;
	private Handler<Buffer> dataHandler;
	private Handler<Throwable> failureHandler;

	private int offset;

	public AsyncInputStream(InputStream in) {
		this(in, DEFAULT_CHUNK_SIZE);
	}

	public AsyncInputStream(InputStream in, int chunkSize) {
		if (in == null) {
			throw new NullPointerException("in");
		}
		if (chunkSize <= 0) {
			throw new IllegalArgumentException(
					"chunkSize: " + chunkSize +
					" (expected: a positive integer)");
		}

		if (in instanceof PushbackInputStream) {
			this.in = (PushbackInputStream) in;
		} else {
			this.in = new PushbackInputStream(in);
		}
		this.chunkSize = chunkSize;
		this.executor = Executors.newFixedThreadPool(10);
	}

	public int getStatus() {
		return status;
	}

	@Override
	public AsyncInputStream endHandler(Handler<Void> endHandler) {
		this.closeHandler = endHandler;
		return this;
	}

	@Override
	public AsyncInputStream dataHandler(Handler<Buffer> handler) {
		if (handler == null) {
			throw new UnsupportedOperationException("not implemented");
		}
		this.dataHandler = handler;
		doRead();
		return this;
	}

	private void doRead() {
		if (status == STATUS_ACTIVE) {
			final Handler<Buffer> dataHandler = this.dataHandler;
			final Handler<Void> closeHandler = this.closeHandler;
			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						final byte[] bytes = readChunk();

						if (bytes == null  || bytes.length == 0) {
							status = STATUS_CLOSED;
							closeHandler.handle(null);
						} else {

							dataHandler.handle(new Buffer(bytes));
							doRead();

						}
					} catch (final Exception e) {
						status = STATUS_CLOSED;
						IOUtils.closeQuietly(in);
						failureHandler.handle(e);
					}
				}
			});
		}
	}

	@Override
	public AsyncInputStream pause() {
		if (status == STATUS_ACTIVE) {
			status = STATUS_PAUSED;
		}
		return this;
	}

	@Override
	public AsyncInputStream resume() {
		switch (status) {
		case STATUS_CLOSED:
			throw new IllegalStateException();
		case STATUS_PAUSED:
			status = STATUS_ACTIVE;
			doRead();
		}
		return this;
	}

	@Override
	public AsyncInputStream exceptionHandler(Handler<Throwable> handler) {
		this.failureHandler = handler;
		return this;
	}

	public long transferredBytes() {
		return offset;
	}

	public boolean isClosed() {
		return status == STATUS_CLOSED;
	}

	public boolean isEndOfInput() throws Exception {
		int b = in.read();
		if (b < 0) {
			return true;
		} else {
			in.unread(b);
			return false;
		}
	}

	public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

	private byte[] readChunk() throws Exception {
		if (isEndOfInput()) {
			return EMPTY_BYTE_ARRAY;
		}

		final int availableBytes = in.available();

		final int chunkSize;
		if (availableBytes <= 0) {
			chunkSize = this.chunkSize;
		} else {
			chunkSize = Math.min(this.chunkSize, in.available());
		}

		byte[] buffer;
		try {
			// transfer to buffer
			byte[] tmp = new byte[chunkSize];
			int readBytes = in.read(tmp);
			if (readBytes <= 0) {
				return null;
			}
			buffer = tmp;
			offset += tmp.length;
			return buffer;
		} catch (IOException e) {
			IOUtils.closeQuietly(in);
			return null;
		}
	}
}


text:
imageFlipper
============

jQuery plug-in for changing image in an element by moving the mose