text:
package com.badlogic.gdx.backends.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Handler;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnGenericMotionListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.badlogic.gdx.AbstractInput;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20;
import com.badlogic.gdx.utils.Pool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/** An implementation of the {@link Input} interface for Android.
 *
 * @author mzechner */
/** @author jshapcot */
public class DefaultAndroidInput extends AbstractInput implements AndroidInput {

	static class KeyEvent {
		static final int KEY_DOWN = 0;
		static final int KEY_UP = 1;
		static final int KEY_TYPED = 2;

		long timeStamp;
		int type;
		int keyCode;
		char keyChar;
	}

	static class TouchEvent {
		static final int TOUCH_DOWN = 0;
		static final int TOUCH_UP = 1;
		static final int TOUCH_DRAGGED = 2;
		static final int TOUCH_SCROLLED = 3;
		static final int TOUCH_MOVED = 4;
		static final int TOUCH_CANCELLED = 5;

		long timeStamp;
		int type;
		int x;
		int y;
		int scrollAmountX;
		int scrollAmountY;
		int button;
		int pointer;
	}

	Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
		protected KeyEvent newObject () {
			return new KeyEvent();
		}
	};

	Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
		protected TouchEvent newObject () {
			return new TouchEvent();
		}
	};

	public static final int NUM_TOUCHES = 20;

	ArrayList<OnKeyListener> keyListeners = new ArrayList();
	ArrayList<KeyEvent> keyEvents = new ArrayList();
	ArrayList<TouchEvent> touchEvents = new ArrayList();
	int[] touchX = new int[NUM_TOUCHES];
	int[] touchY = new int[NUM_TOUCHES];
	int[] deltaX = new int[NUM_TOUCHES];
	int[] deltaY = new int[NUM_TOUCHES];
	boolean[] touched = new boolean[NUM_TOUCHES];
	int[] button = new int[NUM_TOUCHES];
	int[] realId = new int[NUM_TOUCHES];
	float[] pressure = new float[NUM_TOUCHES];
	final boolean hasMultitouch;
	private boolean[] justPressedButtons = new boolean[NUM_TOUCHES];
	private SensorManager manager;
	public boolean accelerometerAvailable = false;
	protected final float[] accelerometerValues = new float[3];
	public boolean gyroscopeAvailable = false;
	protected final float[] gyroscopeValues = new float[3];
	private Handler handle;
	final Application app;
	final Context context;
	protected final AndroidTouchHandler touchHandler;
	private int sleepTime = 0;
	protected final AndroidHaptics haptics;
	private boolean compassAvailable = false;
	private boolean rotationVectorAvailable = false;
	boolean keyboardAvailable;
	protected final float[] magneticFieldValues = new float[3];
	protected final float[] rotationVectorValues = new float[3];
	private float azimuth = 0;
	private float pitch = 0;
	private float roll = 0;
	private boolean justTouched = false;
	private InputProcessor processor;
	private final AndroidApplicationConfiguration config;
	protected final Orientation nativeOrientation;
	private long currentEventTimeStamp = 0;

	private SensorEventListener accelerometerListener;
	private SensorEventListener gyroscopeListener;
	private SensorEventListener compassListener;
	private SensorEventListener rotationVectorListener;

	private final ArrayList<OnGenericMotionListener> genericMotionListeners = new ArrayList();
	private final AndroidMouseHandler mouseHandler;

	public DefaultAndroidInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
		// we hook into View, for LWPs we call onTouch below directly from
		// within the AndroidLivewallpaperEngine#onTouchEvent() method.
		if (view instanceof View) {
			View v = (View)view;
			v.setOnKeyListener(this);
			v.setOnTouchListener(this);
			v.setFocusable(true);
			v.setFocusableInTouchMode(true);
			v.requestFocus();
			v.setOnGenericMotionListener(this);
		}
		this.config = config;
		this.mouseHandler = new AndroidMouseHandler();

		for (int i = 0; i < realId.length; i++)
			realId[i] = -1;
		handle = new Handler();
		this.app = activity;
		this.context = context;
		this.sleepTime = config.touchSleepTime;
		touchHandler = new AndroidTouchHandler();
		hasMultitouch = touchHandler.supportsMultitouch(context);

		haptics = new AndroidHaptics(context);

		int rotation = getRotation();
		DisplayMode mode = app.getGraphics().getDisplayMode();
		if (((rotation == 0 || rotation == 180) && (mode.width >= mode.height))
			|| ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) {
			nativeOrientation = Orientation.Landscape;
		} else {
			nativeOrientation = Orientation.Portrait;
		}

		// this is for backward compatibility: libGDX always caught the circle button, original comment:
		// circle button on Xperia Play shouldn't need catchBack == true
		setCatchKey(Keys.BUTTON_CIRCLE, true);
	}

	@Override
	public float getAccelerometerX () {
		return accelerometerValues[0];
	}

	@Override
	public float getAccelerometerY () {
		return accelerometerValues[1];
	}

	@Override
	public float getAccelerometerZ () {
		return accelerometerValues[2];
	}

	@Override
	public float getGyroscopeX () {
		return gyroscopeValues[0];
	}

	@Override
	public float getGyroscopeY () {
		return gyroscopeValues[1];
	}

	@Override
	public float getGyroscopeZ () {
		return gyroscopeValues[2];
	}

	@Override
	public void getTextInput (TextInputListener listener, String title, String text, String hint) {
		getTextInput(listener, title, text, hint, OnscreenKeyboardType.Default);
	}

	@Override
	public void getTextInput (final TextInputListener listener, final String title, final String text, final String hint,
		final OnscreenKeyboardType keyboardType) {
		handle.post(new Runnable() {
			public void run () {
				AlertDialog.Builder alert = new AlertDialog.Builder(context);
				alert.setTitle(title);
				final EditText input = new EditText(context);
				if (keyboardType != OnscreenKeyboardType.Default) {
					input.setInputType(getAndroidInputType(keyboardType));
				}
				input.setHint(hint);
				input.setText(text);
				input.setSingleLine();
				if (keyboardType == OnscreenKeyboardType.Password) {
					input.setTransformationMethod(new PasswordTransformationMethod());
				}
				alert.setView(input);
				alert.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
					public void onClick (DialogInterface dialog, int whichButton) {
						Gdx.app.postRunnable(new Runnable() {
							@Override
							public void run () {
								listener.input(input.getText().toString());
							}
						});
					}
				});
				alert.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
					public void onClick (DialogInterface dialog, int whichButton) {
						Gdx.app.postRunnable(new Runnable() {
							@Override
							public void run () {
								listener.canceled();
							}
						});
					}
				});
				alert.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel (DialogInterface arg0) {
						Gdx.app.postRunnable(new Runnable() {
							@Override
							public void run () {
								listener.canceled();
							}
						});
					}
				});
				alert.show();
			}
		});
	}

	public static int getAndroidInputType (OnscreenKeyboardType type) {
		int inputType;
		switch (type) {
		case NumberPad:
			inputType = InputType.TYPE_CLASS_NUMBER;
			break;
		case PhonePad:
			inputType = InputType.TYPE_CLASS_PHONE;
			break;
		case Email:
			inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
			break;
		case Password:
			inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
			break;
		case URI:
			inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
			break;
		default:
			inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
			break;
		}
		return inputType;
	}

	@Override
	public int getMaxPointers () {
		return NUM_TOUCHES;
	}

	@Override
	public int getX () {
		synchronized (this) {
			return touchX[0];
		}
	}

	@Override
	public int getY () {
		synchronized (this) {
			return touchY[0];
		}
	}

	@Override
	public int getX (int pointer) {
		synchronized (this) {
			return touchX[pointer];
		}
	}

	@Override
	public int getY (int pointer) {
		synchronized (this) {
			return touchY[pointer];
		}
	}

	public boolean isTouched (int pointer) {
		synchronized (this) {
			return touched[pointer];
		}
	}

	@Override
	public float getPressure () {
		return getPressure(0);
	}

	@Override
	public float getPressure (int pointer) {
		return pressure[pointer];
	}

	@Override
	public void setKeyboardAvailable (boolean available) {
		this.keyboardAvailable = available;
	}

	@Override
	public boolean isTouched () {
		synchronized (this) {
			if (hasMultitouch) {
				for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
					if (touched[pointer]) {
						return true;
					}
				}
			}
			return touched[0];
		}
	}

	public void setInputProcessor (InputProcessor processor) {
		synchronized (this) {
			this.processor = processor;
		}
	}

	@Override
	public void processEvents () {
		synchronized (this) {
			if (justTouched) {
				justTouched = false;
				for (int i = 0; i < justPressedButtons.length; i++) {
					justPressedButtons[i] = false;
				}
			}
			if (keyJustPressed) {
				keyJustPressed = false;
				for (int i = 0; i < justPressedKeys.length; i++) {
					justPressedKeys[i] = false;
				}
			}

			if (!isCursorCatched()) {
				deltaX[0] = 0;
				deltaY[0] = 0;
			}

			if (processor != null) {
				final InputProcessor processor = this.processor;

				int len = keyEvents.size();
				for (int i = 0; i < len; i++) {
					KeyEvent e = keyEvents.get(i);
					currentEventTimeStamp = e.timeStamp;
					switch (e.type) {
					case KeyEvent.KEY_DOWN:
						// Catching the cursor causes it to send D-pad events. Ignore them.
						if (!isCursorCatched() || !(e.keyCode >= Keys.UP && e.keyCode <= Keys.CENTER)) {
							processor.keyDown(e.keyCode);
							keyJustPressed = true;
							justPressedKeys[e.keyCode] = true;
						}
						break;
					case KeyEvent.KEY_UP:
						if (!isCursorCatched() || !(e.keyCode >= Keys.UP && e.keyCode <= Keys.CENTER)) {
							processor.keyUp(e.keyCode);
						}
						break;
					case KeyEvent.KEY_TYPED:
						if (!isCursorCatched() || e.keyChar != Keys.UNKNOWN) {
							processor.keyTyped(e.keyChar);
						}
					}
					usedKeyEvents.free(e);
				}

				len = touchEvents.size();
				for (int i = 0; i < len; i++) {
					TouchEvent e = touchEvents.get(i);
					currentEventTimeStamp = e.timeStamp;
					switch (e.type) {
					case TouchEvent.TOUCH_DOWN:
						processor.touchDown(e.x, e.y, e.pointer, e.button);
						justTouched = true;
						justPressedButtons[e.button] = true;
						break;
					case TouchEvent.TOUCH_UP:
						processor.touchUp(e.x, e.y, e.pointer, e.button);
						break;
					case TouchEvent.TOUCH_DRAGGED:
						processor.touchDragged(e.x, e.y, e.pointer);
						break;
					case TouchEvent.TOUCH_CANCELLED:
						processor.touchCancelled(e.x, e.y, e.pointer, e.button);
						break;
					case TouchEvent.TOUCH_MOVED:
						processor.mouseMoved(e.x, e.y);
						break;
					case TouchEvent.TOUCH_SCROLLED:
						processor.scrolled(e.scrollAmountX, e.scrollAmountY);
					}
					usedTouchEvents.free(e);
				}
			} else {
				int len = touchEvents.size();
				for (int i = 0; i < len; i++) {
					TouchEvent e = touchEvents.get(i);
					if (e.type == TouchEvent.TOUCH_DOWN) justTouched = true;
					usedTouchEvents.free(e);
				}

				len = keyEvents.size();
				for (int i = 0; i < len; i++) {
					usedKeyEvents.free(keyEvents.get(i));
				}
			}

			keyEvents.clear();
			touchEvents.clear();
		}
	}

	boolean requestFocus = true;

	@Override
	public boolean onTouch (View view, MotionEvent event) {
		if (requestFocus && view != null) {
			view.setFocusableInTouchMode(true);
			view.requestFocus();
			requestFocus = false;
		}

		// synchronized in handler.postTouchEvent()
		touchHandler.onTouch(event, this);

		if (sleepTime != 0) {
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
			}
		}
		return true;
	}

// TODO Seems unused. Delete when confirmed.
// /** Called in {@link AndroidLiveWallpaperService} on tap
// * @param x
// * @param y */
// public void onTap (int x, int y) {
// postTap(x, y);
// }
//
// /** Called in {@link AndroidLiveWallpaperService} on drop
// * @param x
// * @param y */
// public void onDrop (int x, int y) {
// postTap(x, y);
// }
//
// protected void postTap (int x, int y) {
// synchronized (this) {
// TouchEvent event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_DOWN;
// touchEvents.add(event);
//
// event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_UP;
// touchEvents.add(event);
// }
// Gdx.app.getGraphics().requestRendering();
// }

	@Override
	public boolean onKey (View v, int keyCode, android.view.KeyEvent e) {
		for (int i = 0, n = keyListeners.size(); i < n; i++)
			if (keyListeners.get(i).onKey(v, keyCode, e)) return true;

		// If the key is held sufficiently long that it repeats, then the initial down is followed
		// additional key events with ACTION_DOWN and a non-zero value for getRepeatCount().
		// We are only interested in the first key down event here and must ignore all others
		if (e.getAction() == android.view.KeyEvent.ACTION_DOWN && e.getRepeatCount() > 0) return isCatchKey(keyCode);

		synchronized (this) {
			KeyEvent event = null;

			if (e.getKeyCode() == android.view.KeyEvent.KEYCODE_UNKNOWN && e.getAction() == android.view.KeyEvent.ACTION_MULTIPLE) {
				String chars = e.getCharacters();
				for (int i = 0; i < chars.length(); i++) {
					event = usedKeyEvents.obtain();
					event.timeStamp = System.nanoTime();
					event.keyCode = 0;
					event.keyChar = chars.charAt(i);
					event.type = KeyEvent.KEY_TYPED;
					keyEvents.add(event);
				}
				return false;
			}

			char character = (char)e.getUnicodeChar();
			// Android doesn't report a unicode char for back space. hrm...
			if (keyCode == 67) character = '\b';
			if (e.getKeyCode() < 0 || e.getKeyCode() > Keys.MAX_KEYCODE) {
				return false;
			}

			switch (e.getAction()) {
			case android.view.KeyEvent.ACTION_DOWN:
				event = usedKeyEvents.obtain();
				event.timeStamp = System.nanoTime();
				event.keyChar = 0;
				event.keyCode = e.getKeyCode();
				event.type = KeyEvent.KEY_DOWN;

				// Xperia hack for circle key. gah...
				if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
					keyCode = Keys.BUTTON_CIRCLE;
					event.keyCode = keyCode;
				}

				keyEvents.add(event);
				if (!pressedKeys[event.keyCode]) {
					pressedKeyCount++;
					pressedKeys[event.keyCode] = true;
				}
				break;
			case android.view.KeyEvent.ACTION_UP:
				long timeStamp = System.nanoTime();
				event = usedKeyEvents.obtain();
				event.timeStamp = timeStamp;
				event.keyChar = 0;
				event.keyCode = e.getKeyCode();
				event.type = KeyEvent.KEY_UP;
				// Xperia hack for circle key. gah...
				if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
					keyCode = Keys.BUTTON_CIRCLE;
					event.keyCode = keyCode;
				}
				keyEvents.add(event);

				event = usedKeyEvents.obtain();
				event.timeStamp = timeStamp;
				event.keyChar = character;
				event.keyCode = 0;
				event.type = KeyEvent.KEY_TYPED;
				keyEvents.add(event);

				if (keyCode == Keys.BUTTON_CIRCLE) {
					if (pressedKeys[Keys.BUTTON_CIRCLE]) {
						pressedKeyCount--;
						pressedKeys[Keys.BUTTON_CIRCLE] = false;
					}
				} else {
					if (pressedKeys[e.getKeyCode()]) {
						pressedKeyCount--;
						pressedKeys[e.getKeyCode()] = false;
					}
				}
			}
			app.getGraphics().requestRendering();
		}

		return isCatchKey(keyCode);
	}

	@Override
	public void setOnscreenKeyboardVisible (final boolean visible) {
		setOnscreenKeyboardVisible(visible, OnscreenKeyboardType.Default);
	}

	@Override
	public void setOnscreenKeyboardVisible (final boolean visible, final OnscreenKeyboardType type) {
		handle.post(new Runnable() {
			public void run () {
				InputMethodManager manager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (visible) {
					View view = ((AndroidGraphics)app.getGraphics()).getView();
					OnscreenKeyboardType tmp = type == null ? OnscreenKeyboardType.Default : type;
					if (((GLSurfaceView20)view).onscreenKeyboardType != tmp) {
						((GLSurfaceView20)view).onscreenKeyboardType = tmp;
						manager.restartInput(view);
					}

					view.setFocusable(true);
					view.setFocusableInTouchMode(true);
					manager.showSoftInput(((AndroidGraphics)app.getGraphics()).getView(), 0);
				} else {
					manager.hideSoftInputFromWindow(((AndroidGraphics)app.getGraphics()).getView().getWindowToken(), 0);
				}
			}
		});
	}

	@Override
	public void vibrate (int milliseconds) {
		haptics.vibrate(milliseconds);
	}

	@Override
	public void vibrate (int milliseconds, boolean fallback) {
		haptics.vibrate(milliseconds);
	}

	@Override
	public void vibrate (int milliseconds, int amplitude, boolean fallback) {
		haptics.vibrate(milliseconds, amplitude, fallback);
	}

	@Override
	public void vibrate (VibrationType vibrationType) {
		haptics.vibrate(vibrationType);
	}

	@Override
	public boolean justTouched () {
		return justTouched;
	}

	@Override
	public boolean isButtonPressed (int button) {
		synchronized (this) {
			if (hasMultitouch) {
				for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
					if (touched[pointer] && (this.button[pointer] == button)) {
						return true;
					}
				}
			}
			return (touched[0] && (this.button[0] == button));
		}
	}

	@Override
	public boolean isButtonJustPressed (int button) {
		if (button < 0 || button > NUM_TOUCHES) return false;
		return justPressedButtons[button];
	}

	final float[] R = new float[9];
	final float[] orientation = new float[3];

	private void updateOrientation () {
		if (rotationVectorAvailable) {
			SensorManager.getRotationMatrixFromVector(R, rotationVectorValues);
		} else if (!SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues)) {
			return; // compass + accelerometer in free fall
		}
		SensorManager.getOrientation(R, orientation);
		azimuth = (float)Math.toDegrees(orientation[0]);
		pitch = (float)Math.toDegrees(orientation[1]);
		roll = (float)Math.toDegrees(orientation[2]);
	}

	/** Returns the rotation matrix describing the devices rotation as per
	 * SensorManager#getRotationMatrix(float[], float[], float[], float[]). Does not manipulate the matrix
	 * if the platform does not have an accelerometer and compass, or a rotation vector sensor.
	 * @param matrix */
	public void getRotationMatrix (float[] matrix) {
		if (rotationVectorAvailable)
			SensorManager.getRotationMatrixFromVector(matrix, rotationVectorValues);
		else // compass + accelerometer
			SensorManager.getRotationMatrix(matrix, null, accelerometerValues, magneticFieldValues);
	}

	@Override
	public float getAzimuth () {
		if (!compassAvailable && !rotationVectorAvailable) return 0;

		updateOrientation();
		return azimuth;
	}

	@Override
	public float getPitch () {
		if (!compassAvailable && !rotationVectorAvailable) return 0;

		updateOrientation();
		return pitch;
	}

	@Override
	public float getRoll () {
		if (!compassAvailable && !rotationVectorAvailable) return 0;

		updateOrientation();
		return roll;
	}

	void registerSensorListeners () {
		if (config.useAccelerometer) {
			manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
			if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty()) {
				accelerometerAvailable = false;
			} else {
				Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
				accelerometerListener = new SensorListener();
				accelerometerAvailable = manager.registerListener(accelerometerListener, accelerometer, config.sensorDelay);
			}
		} else
			accelerometerAvailable = false;

		if (config.useGyroscope) {
			manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
			if (manager.getSensorList(Sensor.TYPE_GYROSCOPE).isEmpty()) {
				gyroscopeAvailable = false;
			} else {
				Sensor gyroscope = manager.getSensorList(Sensor.TYPE_GYROSCOPE).get(0);
				gyroscopeListener = new SensorListener();
				gyroscopeAvailable = manager.registerListener(gyroscopeListener, gyroscope, config.sensorDelay);
			}
		} else
			gyroscopeAvailable = false;

		rotationVectorAvailable = false;
		if (config.useRotationVectorSensor) {
			if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
			List<Sensor> rotationVectorSensors = manager.getSensorList(Sensor.TYPE_ROTATION_VECTOR);
			if (!rotationVectorSensors.isEmpty()) {
				rotationVectorListener = new SensorListener();
				for (Sensor sensor : rotationVectorSensors) { // favor AOSP sensor
					if (sensor.getVendor().equals("Google Inc.") && sensor.getVersion() == 3) {
						rotationVectorAvailable = manager.registerListener(rotationVectorListener, sensor, config.sensorDelay);
						break;
					}
				}
				if (!rotationVectorAvailable) rotationVectorAvailable = manager.registerListener(rotationVectorListener,
					rotationVectorSensors.get(0), config.sensorDelay);
			}
		}

		if (config.useCompass && !rotationVectorAvailable) {
			if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
			Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
			if (sensor != null) {
				compassAvailable = accelerometerAvailable;
				if (compassAvailable) {
					compassListener = new SensorListener();
					compassAvailable = manager.registerListener(compassListener, sensor, config.sensorDelay);
				}
			} else {
				compassAvailable = false;
			}
		} else
			compassAvailable = false;
		Gdx.app.log("AndroidInput", "sensor listener setup");
	}

	void unregisterSensorListeners () {
		if (manager != null) {
			if (accelerometerListener != null) {
				manager.unregisterListener(accelerometerListener);
				accelerometerListener = null;
			}
			if (gyroscopeListener != null) {
				manager.unregisterListener(gyroscopeListener);
				gyroscopeListener = null;
			}
			if (rotationVectorListener != null) {
				manager.unregisterListener(rotationVectorListener);
				rotationVectorListener = null;
			}
			if (compassListener != null) {
				manager.unregisterListener(compassListener);
				compassListener = null;
			}
			manager = null;
		}
		Gdx.app.log("AndroidInput", "sensor listener tear down");
	}

	@Override
	public InputProcessor getInputProcessor () {
		return this.processor;
	}

	@Override
	public boolean isPeripheralAvailable (Peripheral peripheral) {
		if (peripheral == Peripheral.Accelerometer) return accelerometerAvailable;
		if (peripheral == Peripheral.Gyroscope) return gyroscopeAvailable;
		if (peripheral == Peripheral.Compass) return compassAvailable;
		if (peripheral == Peripheral.HardwareKeyboard) return keyboardAvailable;
		if (peripheral == Peripheral.OnscreenKeyboard) return true;
		if (peripheral == Peripheral.Vibrator) return haptics.hasVibratorAvailable();
		if (peripheral == Peripheral.HapticFeedback) return haptics.hasHapticsSupport();
		if (peripheral == Peripheral.MultitouchScreen) return hasMultitouch;
		if (peripheral == Peripheral.RotationVector) return rotationVectorAvailable;
		if (peripheral == Peripheral.Pressure) return true;
		return false;
	}

	public int getFreePointerIndex () {
		int len = realId.length;
		for (int i = 0; i < len; i++) {
			if (realId[i] == -1) return i;
		}

		pressure = resize(pressure);
		realId = resize(realId);
		touchX = resize(touchX);
		touchY = resize(touchY);
		deltaX = resize(deltaX);
		deltaY = resize(deltaY);
		touched = resize(touched);
		button = resize(button);

		return len;
	}

	private int[] resize (int[] orig) {
		int[] tmp = new int[orig.length + 2];
		System.arraycopy(orig, 0, tmp, 0, orig.length);
		return tmp;
	}

	private boolean[] resize (boolean[] orig) {
		boolean[] tmp = new boolean[orig.length + 2];
		System.arraycopy(orig, 0, tmp, 0, orig.length);
		return tmp;
	}

	private float[] resize (float[] orig) {
		float[] tmp = new float[orig.length + 2];
		System.arraycopy(orig, 0, tmp, 0, orig.length);
		return tmp;
	}

	public int lookUpPointerIndex (int pointerId) {
		int len = realId.length;
		for (int i = 0; i < len; i++) {
			if (realId[i] == pointerId) return i;
		}

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i++) {
			sb.append(i + ":" + realId[i] + " ");
		}
		Gdx.app.log("AndroidInput", "Pointer ID lookup failed: " + pointerId + ", " + sb.toString());
		return -1;
	}

	@Override
	public int getRotation () {
		int orientation = 0;

		if (context instanceof Activity) {
			orientation = ((Activity)context).getWindowManager().getDefaultDisplay().getRotation();
		} else {
			orientation = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
		}

		switch (orientation) {
		case Surface.ROTATION_0:
			return 0;
		case Surface.ROTATION_90:
			return 90;
		case Surface.ROTATION_180:
			return 180;
		case Surface.ROTATION_270:
			return 270;
		default:
			return 0;
		}
	}

	@Override
	public Orientation getNativeOrientation () {
		return nativeOrientation;
	}

	@Override
	public void setCursorCatched (boolean catched) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			View view = ((AndroidGraphics)app.getGraphics()).getView();
			if (catched) {
				view.requestPointerCapture();
				view.setOnCapturedPointerListener(new View.OnCapturedPointerListener() {
					@Override
					public boolean onCapturedPointer (View view, MotionEvent motionEvent) {
						deltaX[0] = (int)motionEvent.getX();
						deltaY[0] = (int)motionEvent.getY();
						return false;
					}
				});
			} else {
				view.releasePointerCapture();
			}
		}
	}

	@Override
	public boolean isCursorCatched () {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			View view = ((AndroidGraphics)app.getGraphics()).getView();
			return view.hasPointerCapture();
		}
		return false;
	}

	@Override
	public int getDeltaX () {
		return deltaX[0];
	}

	@Override
	public int getDeltaX (int pointer) {
		return deltaX[pointer];
	}

	@Override
	public int getDeltaY () {
		return deltaY[0];
	}

	@Override
	public int getDeltaY (int pointer) {
		return deltaY[pointer];
	}

	@Override
	public void setCursorPosition (int x, int y) {
	}

	@Override
	public long getCurrentEventTime () {
		return currentEventTimeStamp;
	}

	@Override
	public void addKeyListener (OnKeyListener listener) {
		keyListeners.add(listener);
	}

	@Override
	public boolean onGenericMotion (View view, MotionEvent event) {
		if (mouseHandler.onGenericMotion(event, this)) return true;
		for (int i = 0, n = genericMotionListeners.size(); i < n; i++)
			if (genericMotionListeners.get(i).onGenericMotion(view, event)) return true;
		return false;
	}

	@Override
	public void addGenericMotionListener (OnGenericMotionListener listener) {
		genericMotionListeners.add(listener);
	}

	@Override
	public void onPause () {
		unregisterSensorListeners();
	}

	@Override
	public void onResume () {
		registerSensorListeners();
	}

	@Override
	public void onDreamingStarted () {
		registerSensorListeners();
	}

	@Override
	public void onDreamingStopped () {
		unregisterSensorListeners();
		// erase pointer ids. this sucks donkeyballs...
		Arrays.fill(realId, -1);
		// erase touched state. this also sucks donkeyballs...
		Arrays.fill(touched, false);
	}

	/** Our implementation of SensorEventListener. Because Android doesn't like it when we register more than one Sensor to a
	 * single SensorEventListener, we add one of these for each Sensor. Could use an anonymous class, but I don't see any harm in
	 * explicitly defining it here. Correct me if I am wrong. */
	private class SensorListener implements SensorEventListener {

		public SensorListener () {

		}

		@Override
		public void onAccuracyChanged (Sensor arg0, int arg1) {

		}

		@Override
		public void onSensorChanged (SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
				if (nativeOrientation == Orientation.Portrait) {
					System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length);
				} else {
					accelerometerValues[0] = event.values[1];
					accelerometerValues[1] = -event.values[0];
					accelerometerValues[2] = event.values[2];
				}
			}
			if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
				System.arraycopy(event.values, 0, magneticFieldValues, 0, magneticFieldValues.length);
			}
			if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
				if (nativeOrientation == Orientation.Portrait) {
					System.arraycopy(event.values, 0, gyroscopeValues, 0, gyroscopeValues.length);
				} else {
					gyroscopeValues[0] = event.values[1];
					gyroscopeValues[1] = -event.values[0];
					gyroscopeValues[2] = event.values[2];
				}
			}
			if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
				if (nativeOrientation == Orientation.Portrait) {
					System.arraycopy(event.values, 0, rotationVectorValues, 0, rotationVectorValues.length);
				} else {
					rotationVectorValues[0] = event.values[1];
					rotationVectorValues[1] = -event.values[0];
					rotationVectorValues[2] = event.values[2];
				}
			}
		}
	}
}


text:
textarea, input, select {
  width: 100%; /* extend the width of the grid item */
  box-sizing: border-box; /* including padding / border in width */
}

.sheet-wrapper {
  display: grid;
  grid-template-columns:  fit-content(50%) fit-content(50%);
  gap: 10px;
  justify-content: center;
  padding: 5px;
  grid-auto-rows: minmax(50px, auto);
}

.sheet-itemheader{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:22px;
  border-radius: 15px;
  grid-column: 1 / span 2;
  grid-row: 1 / span 1;
  text-align: center;
}

.sheet-itemcallsign {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 2 / span 1;
}

.sheet-itempilot {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 2 / span 1;
}

.sheet-itemchassis {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 3 / span 1;
}

.sheet-itemlevel {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 3 / span 1;
}

.sheet-itemapmax {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 4 / span 1;
}

.sheet-itemhpmax {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 4 / span 1;
}

.sheet-itemapcur {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 5 / span 1;
}

.sheet-itemhpcur {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 5 / span 1;
}

.sheet-itemdamage {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 6 / span 1;
}

.sheet-itemreactor {
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 6 / span 1;
}

.sheet-itempower{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:22px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 7 / span 2;
}

.sheet-itempilotability{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 7 / span 2;
}

.sheet-itemmobility{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:22px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 9 / span 2;
}

.sheet-itemchassisability{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 9 / span 2;
}

.sheet-itemsystem{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:22px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 11 / span 2;
}

.sheet-itemequipment{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 11 / span 2;
}

.sheet-itempresence{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:22px;
  border-radius: 15px;
  grid-column: 1 ;
  grid-row: 13 / span 2;
}

.sheet-itemmodules{
  border: 3px solid silver;
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 2 ;
  grid-row: 13 / span 2;
}

.sheet-itemimage{
  padding: 5px;
  font-family:Impact, sans-serif;font-size:14px;
  border-radius: 15px;
  grid-column: 1 / span 2 ;
  grid-row: 15 / span 1;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>
<title>Elements respect click in progress flag</title>
<link rel="author" title="jeffcarp" href="mailto:gcarpenterv@gmail.com">
<link rel="help" href="https://html.spec.whatwg.org/#run-synthetic-click-activation-steps">

<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<script>
"use strict";

test(() => {
  const div = document.createElement("div");
  document.body.appendChild(div);
  const events = [];
  let depth = 0;

  div.addEventListener("click", e => {
    events.push("click");
    // This prevents an infinite loop if not implemented
    if (depth++ === 0) {
      e.target.click();
    }
  });

  div.click();

  // elements do not allow recursive synthetic clicks
  assert_array_equals(events, ["click"]);

}, "elements respect 'click in progress' flag");
</script>


text:
/* Name: Pranish Dutt
 * Date: 11/10/20113
 * Purpose: Assignment 4 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace program_4
{
    /// <summary>
    /// Interaction logic for AboutBox.xaml
    /// </summary>
    public partial class AboutBox : Window
    {
        public AboutBox()
        {
            InitializeComponent();
            this.Topmost = true;
            this.ShowInTaskbar = false;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}


text:
package org.activiti.standalone.cfg;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Select;

public interface MyTestMapper {

  @Select("SELECT ID_ as id, NAME_ as name, CREATE_TIME_ as createTime FROM ACT_RU_TASK")
  List<Map<String, Object>> selectTasks();

  @Select({ "SELECT task.ID_ as taskId, variable.LONG_ as variableValue FROM ACT_RU_VARIABLE variable", "inner join ACT_RU_TASK task on variable.TASK_ID_ = task.ID_",
      "where variable.NAME_ = #{variableName}" })
  List<Map<String, Object>> selectTaskWithSpecificVariable(String variableName);

}


text:
namespace android_webview {

// Stores pictures received from diferent renderers and associates them by
// renderer id. Will only work in single process mode.
class RendererPictureMap {
 public:
  static void CreateInstance();
  static RendererPictureMap* GetInstance();

  skia::RefPtr<SkPicture> GetRendererPicture(int id);
  void SetRendererPicture(int id, skia::RefPtr<SkPicture> picture);
  void ClearRendererPicture(int id);

 private:
  RendererPictureMap();
  ~RendererPictureMap();

  typedef std::map<int, skia::RefPtr<SkPicture> > PictureMap;
  PictureMap picture_map_;
  base::Lock lock_;
};

}  // android_webview

#endif  // ANDROID_WEBVIEW_COMMON_RENDERER_PICTURE_MAP_H_


text:
<dom-module id="sample-content">
  <template>

  </template>
</polymer-element>


text:
import { Index, Datastore } from "../src";
import { MockStorageDriver} from "./example/exampleStorageDriver";
import * as fs from "fs";

describe("testing indices storage and fetching functionality", () => {
    const CWD = process.cwd();
    const nonUIndexStorage = new MockStorageDriver("nonUIndexTests");
    const nonUIndexStore = new Datastore({storage: nonUIndexStorage});
    const UIndexStorage = new MockStorageDriver("UIndexTests");
    const UIndexStore = new Datastore({storage: UIndexStorage});
    const uniqDocs = [
        {type: 0},
        {type: 1},
        {type: 2},
    ];
    const nonUniqDocs = [
        {type: 0, t: 0},
        {type: 0, t: 1},
        {type: 1, t: 2},
        {type: 1, t: 3},
    ];

    let objNonUIndexTests: any[];
    let objUIndexTests: any[];

    test("ensuring index", () => {
        expect.assertions(2);
        return nonUIndexStore.ensureIndex({fieldName: "type", unique: false})
            .then((res) => {
                const promises: Array<Promise<any>> = [];
                nonUniqDocs.forEach((doc) => promises.push(nonUIndexStore.insert(doc)));
                return Promise.all(promises);
            })
            .then((res) => {
                expect(res.length).toEqual(4);
                return UIndexStore.ensureIndex({fieldName: "type", unique: true});
            })
            .then((res) => {
                const promises: Array<Promise<any>> = [];
                uniqDocs.forEach((doc) => promises.push(UIndexStore.insert(doc)));
                return Promise.all(promises);
            })
            .then((res) => {
                expect(res.length).toEqual(3);
            });
    });

    test("saving indices", () => {
        expect.assertions(12);
        return nonUIndexStore.getIndices()
            .then((res) => {
                const promises: Array<Promise<null>> = [];
                res.forEach((v: Index, k: string) => promises.push(nonUIndexStore.saveIndex(k)));
                return Promise.all(promises);
            })
            .then(() => {
                return nonUIndexStorage.fetchIndex("type");
            })
            .then((res) => {
                objNonUIndexTests = res;
                expect(res.length).toEqual(2);
                expect(res[0].key).toEqual(0);
                expect(res[0].value.length).toEqual(2);
                expect(res[1].key).toEqual(1);
                expect(res[1].value.length).toEqual(2);
                return UIndexStore.getIndices();
            })
            .then((res) => {
                const promises: Array<Promise<null>> = [];
                res.forEach((v: Index, k: string) => promises.push(UIndexStore.saveIndex(k)));
                return Promise.all(promises);
            })
            .then(() => {
                return UIndexStorage.fetchIndex("type");
            })
            .then((res) => {
                objUIndexTests = res;
                expect(res.length).toEqual(3);
                expect(res[0].key).toEqual(1);
                expect(res[1].key).toEqual(0);
                expect(res[2].key).toEqual(2);
                expect(res[0].value.length).toEqual(1);
                expect(res[1].value.length).toEqual(1);
                expect(res[2].value.length).toEqual(1);
            });
    });

    test("removing all indices", () => {
        expect.assertions(2);
        const promises: Array<Promise<any>> = [];
        uniqDocs.forEach((doc) => promises.push(UIndexStore.remove({type: doc.type})));
        return Promise.all(promises)
            .then((res) => {
                expect(res).toEqual(expect.arrayContaining([1, 1, 1]));
                const NonPromises: Array<Promise<any>> = [];
                NonPromises.push(nonUIndexStore.remove({type: 0}));
                NonPromises.push(nonUIndexStore.remove({type: 1}));

                return Promise.all(NonPromises);
            })
            .then((res) => {
                expect(res).toEqual(expect.arrayContaining([2, 2]));
            });
    });

    test("loading indices back into database", () => {
        expect.assertions(12);
        return nonUIndexStorage.fetchIndex("type")
            .then((res) => {
                return nonUIndexStore.insertIndex("type", res);
            })
            .then(() => {
                return nonUIndexStore.getIndices();
            })
            .then((res) => {
                const ind: Index = res.get("type");
                if (ind) {
                    return ind.toJSON();
                }
            })
            .then((res) => {
                const rezult: any = JSON.parse(res);
                expect(rezult.length).toEqual(2);
                expect(rezult[0].key).toEqual(0);
                expect(rezult[0].value.length).toEqual(2);
                expect(rezult[1].key).toEqual(1);
                expect(rezult[1].value.length).toEqual(2);
                return UIndexStorage.fetchIndex("type");
            })
            .then((res) => {
                return UIndexStore.insertIndex("type", res);
            })
            .then(() => {
                return UIndexStore.getIndices();
            })
            .then((res) => {
                const ind: Index = res.get("type");
                if (ind) {
                    return ind.toJSON();
                }
            })
            .then((res) => {
                    const rezult: any = JSON.parse(res);
                    expect(rezult.length).toEqual(3);
                    expect(rezult[0].key).toEqual(1);
                    expect(rezult[0].value.length).toEqual(1);
                    expect(rezult[1].key).toEqual(0);
                    expect(rezult[1].value.length).toEqual(1);
                    expect(rezult[2].key).toEqual(2);
                    expect(rezult[2].value.length).toEqual(1);
            });
    });

    test("clearing", () => {
        expect.assertions(2);
        return nonUIndexStorage.clear()
            .then(() => {
                const exists = fs.existsSync(`${CWD}/spec/example/db/nonUIndexTests`);
                expect(exists).toBe(false);
                return UIndexStorage.clear();
            })
            .then(() => {
                const exists = fs.existsSync(`${CWD}/spec/example/db/UIndexTests`);
                expect(exists).toBe(false);
            });
    });

});


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: let P be the empty string if pattern is undefined
es5id: 15.10.4.1_A3_T5
description: RegExp is new RegExp((function(){})())
---*/

__re = new RegExp((function(){})());

//CHECK#2
if (__re.multiline !== false) {
  $ERROR('#2: __re = new RegExp((function(){})()); __re.multiline === false. Actual: ' + (__re.multiline));
}

//CHECK#3
if (__re.global !== false) {
  $ERROR('#3: __re = new RegExp((function(){})()); __re.global === false. Actual: ' + (__re.global));
}

//CHECK#4
if (__re.ignoreCase !== false) {
  $ERROR('#4: __re = new RegExp((function(){})()); __re.ignoreCase === false. Actual: ' + (__re.ignoreCase));
}


text:
.class public interface abstract Lcom/android/internal/policy/impl/keyguard/KeyguardSecurityView;
.super Ljava/lang/Object;
.source "KeyguardSecurityView.java"

# static fields
.field public static final SCREEN_ON:I = 0x1

.field public static final VIEW_REVEALED:I = 0x2

# virtual methods
.method public abstract getCallback()Lcom/android/internal/policy/impl/keyguard/KeyguardSecurityCallback;
.end method

.method public abstract hideBouncer(I)V
.end method

.method public abstract needsInput()Z
.end method

.method public abstract onPause()V
.end method

.method public abstract onResume(I)V
.end method

.method public abstract reset()V
.end method

.method public abstract setKeyguardCallback(Lcom/android/internal/policy/impl/keyguard/KeyguardSecurityCallback;)V
.end method

.method public abstract setLockPatternUtils(Lcom/android/internal/widget/LockPatternUtils;)V
.end method

.method public abstract showBouncer(I)V
.end method

.method public abstract showUsabilityHint()V
.end method


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_UTIL_CONSTRAINTS_TYPERESTRICTION_H_
#define _BLAZE_UTIL_CONSTRAINTS_TYPERESTRICTION_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/util/constraints/ConstraintTest.h>
#include <blaze/util/Suffix.h>
#include <blaze/util/TypeList.h>

namespace blaze {

//=================================================================================================
//
//  SOFT_TYPE_RESTRICTION CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Compile time constraint.
// \ingroup constraints
//
// Helper template class for the compile time constraint enforcement. Based on the compile time
// constant expression used for the template instantiation, either the undefined basic template
// or the specialization is selected. If the undefined basic template is selected, a compilation
// error is created.
*/
template< bool > struct CONSTRAINT_SOFT_TYPE_RESTRICTION_FAILED;
template<> struct CONSTRAINT_SOFT_TYPE_RESTRICTION_FAILED<true> { enum { value = 1 }; };
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given type list \a TYPELIST does not contain a type related to \a T, a compilation
// error is created.
*/
#define BLAZE_CONSTRAINT_SOFT_TYPE_RESTRICTION(T,TYPELIST) \
   typedef \
      ::blaze::CONSTRAINT_TEST< \
         ::blaze::CONSTRAINT_SOFT_TYPE_RESTRICTION_FAILED< ::blaze::ContainsRelated<TYPELIST,T>::value >::value > \
      BLAZE_JOIN( CONSTRAINT_SOFT_TYPE_RESTRICTION_TYPEDEF, __LINE__ )
//*************************************************************************************************

//=================================================================================================
//
//  TYPE_RESTRICTION CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Compile time constraint.
// \ingroup constraints
//
// Helper template class for the compile time constraint enforcement. Based on the compile time
// constant expression used for the template instantiation, either the undefined basic template
// or the specialization is selected. If the undefined basic template is selected, a compilation
// error is created.
*/
template< bool > struct CONSTRAINT_TYPE_RESTRICTION_FAILED;
template<> struct CONSTRAINT_TYPE_RESTRICTION_FAILED<true> { enum { value = 1 }; };
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given type list \a TYPELIST does not contain the data type \a T, a compilation
// error is created.
*/
#define BLAZE_CONSTRAINT_TYPE_RESTRICTION(T,TYPELIST) \
   typedef \
      ::blaze::CONSTRAINT_TEST< \
         ::blaze::CONSTRAINT_TYPE_RESTRICTION_FAILED< ::blaze::Contains<TYPELIST,T>::value >::value > \
      BLAZE_JOIN( CONSTRAINT_TYPE_RESTRICTION_TYPEDEF, __LINE__ )
//*************************************************************************************************

} // namespace blaze

#endif


text:
package com.cloud.storage.template;

import com.cloud.storage.Storage;

public class UploadEntity {
    public static long s_maxTemplateSize = 50L * 1024L * 1024L * 1024L;
    private long downloadedsize;
    private String filename;
    private String installPathPrefix;
    private String templatePath;
    private boolean isHvm;
    private Storage.ImageFormat format;
    private String uuid;
    private long entityId;
    private String chksum;
    private long physicalSize;
    private int maxSizeInGB;
    private String description;
    private long contentLength;
    private Status uploadState;
    private String errorMessage = null;
    private ResourceType resourceType;
    private long virtualSize;
    private boolean isMetaDataPopulated;

    public UploadEntity(final String uuid, final long entityId, final Status status, final String filename, final String installPathPrefix) {
        this.uuid = uuid;
        this.uploadState = status;
        this.downloadedsize = 0l;
        this.filename = filename;
        this.installPathPrefix = installPathPrefix;
        this.entityId = entityId;
    }

    public UploadEntity() {

    }

    public void setStatus(final Status status) {
        this.uploadState = status;
    }

    public long getDownloadedsize() {
        return downloadedsize;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

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

    public Status getUploadState() {
        return uploadState;
    }

    public void incremetByteCount(final long numberOfBytes) {
        this.downloadedsize += numberOfBytes;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(final String filename) {
        this.filename = filename;
    }

    public String getInstallPathPrefix() {
        return installPathPrefix;
    }

    public void setInstallPathPrefix(final String absoluteFilePath) {
        this.installPathPrefix = absoluteFilePath;
    }

    public String getTmpltPath() {
        return templatePath;
    }

    public void setTemplatePath(final String templatePath) {
        this.templatePath = templatePath;
    }

    public ResourceType getResourceType() {
        return resourceType;
    }

    public void setResourceType(final ResourceType resourceType) {
        this.resourceType = resourceType;
    }

    public boolean isHvm() {
        return isHvm;
    }

    public void setHvm(final boolean isHvm) {
        this.isHvm = isHvm;
    }

    public Storage.ImageFormat getFormat() {
        return format;
    }

    public void setFormat(final Storage.ImageFormat format) {
        this.format = format;
    }

    public String getUuid() {
        return uuid;
    }

    public long getEntityId() {
        return entityId;
    }

    public String getChksum() {
        return chksum;
    }

    public void setChksum(final String chksum) {
        this.chksum = chksum;
    }

    public long getVirtualSize() {
        return virtualSize;
    }

    public void setVirtualSize(final long virtualSize) {
        this.virtualSize = virtualSize;
    }

    public boolean isMetaDataPopulated() {
        return isMetaDataPopulated;
    }

    public void setMetaDataPopulated(final boolean isMetaDataPopulated) {
        this.isMetaDataPopulated = isMetaDataPopulated;
    }

    public long getPhysicalSize() {
        return physicalSize;
    }

    public void setPhysicalSize(final long physicalSize) {
        this.physicalSize = physicalSize;
    }

    public int getMaxSizeInGB() {
        return maxSizeInGB;
    }

    public void setMaxSizeInGB(final int maxSizeInGB) {
        this.maxSizeInGB = maxSizeInGB;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public long getContentLength() {
        return contentLength;
    }

    public void setContentLength(final long contentLength) {
        this.contentLength = contentLength;
    }

    public static enum ResourceType {
        VOLUME, TEMPLATE
    }

    public static enum Status {
        UNKNOWN, IN_PROGRESS, COMPLETED, ERROR
    }
}


text:
require 'rvg/rvg'

Magick::RVG.dpi = 90

rvg = Magick::RVG.new(10.cm, 3.cm).viewbox(0, 0, 1000, 300) do |canvas|
  canvas.background_fill = 'white'
  canvas.desc = 'Example tspan01 - using tspan to change visual attributes'
  canvas.g.styles(font_family: 'Verdana', font_size: 45) do |grp|
    grp.text(200, 150, 'You are').styles(fill: 'blue') do |txt|
      txt.tspan(' not').styles(font_weight: 'bold', fill: 'red')
      txt.tspan(' a banana')
    end
  end
  canvas.rect(997, 297).styles(fill: 'none', stroke: 'blue')
end

rvg.draw.write('tspan01.gif')


text:
var express = require('express'),
    busboy = require('connect-busboy');

// Configuration for express server
module.exports = function(app, config) {
  app.configure(function () {
    app.use(express.compress());
    app.use(express.static(config.root + '/public'));
    app.set('port', config.port);
    app.set('views', config.root + '/app/views');
    //Using jade templating
    app.set('view engine', 'jade');
    app.use(busboy());
    app.use(express.logger('dev'));
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(app.router);
    app.use(function(req, res) {
      res.status(404).render('404', { title: '404' });
    });
  });
};


text:
const set = require('regenerate')();
set.addRange(0x10AC0, 0x10AE6).addRange(0x10AEB, 0x10AF6);
exports.characters = set;


text:
import functools as fu
import sublime
import sublime_plugin

# Handling the different imports in Sublime
if sublime.version() < '3000':
    # we are on ST2 and Python 2.X
    _ST3 = False
    import jove
else:
    _ST3 = True
    from . import jove

class SbpRectangleDelete(jove.SbpTextCommand):
  """
  Deletes the content of a given rectangle, content is not saved to kill ring
  and cannot be pasted
  """
  def run_cmd(self, jove, **args):
    region = jove.get_encompassing_region()

    if not region:
        return

    # get the beginning and end of the region
    b_row, b_col = self.view.rowcol(region.begin())
    e_row, e_col = self.view.rowcol(region.end())

    # Create rectangle
    top = b_row
    left = min(b_col, e_col)

    bot = e_row
    right = max(b_col, e_col)

    current_edit = jove.edit
    for l in range(top, bot + 1):
        r = sublime.Region(self.view.text_point(l, left), self.view.text_point(l, right))
        if not r.empty():
            self.view.erase(current_edit, r)

    self.view.end_edit(jove.edit)

class SbpRectangleInsertHandler(jove.SbpTextCommand):
  """
  executes the actual insert from the rectangle
  """

  def run_cmd(self, jove, content):
    region = jove.get_encompassing_region()
    if not region:
        return

    # get the beginning and end of the region
    b_row, b_col = self.view.rowcol(region.begin())
    e_row, e_col = self.view.rowcol(region.end())

    # Create rectangle
    top = b_row
    left = min(b_col, e_col)

    bot = e_row
    right = max(b_col, e_col)

    # For each line in the region, replace the contents by what we
    # gathered from the overlay
    current_edit = jove.edit
    for l in range(top, bot + 1):
      r = sublime.Region(self.view.text_point(l, left), self.view.text_point(l, right))
      if not r.empty():
        self.view.erase(current_edit, r)
      self.view.insert(current_edit, self.view.text_point(l, left), content)
    self.view.end_edit(jove.edit)

class SbpRectangleInsert(jove.SbpTextCommand):
  """
  Given a rectangle insert the text at points
  """
  def run_cmd(self, jove, **args):
    self.jove = jove
    self.view.window().show_input_panel("Content:", "", self.replace, None, None)

  def replace(self, content):
    self.jove.view.run_command("sbp_rectangle_insert_handler", {"content": content})


text:
<?php

declare(strict_types=1);

namespace Chubbyphp\Validation;

interface ValidatorContextBuilderInterface
{
    public static function create(): self;

    /**
     * @param array<int, string> $groups
     */
    public function setGroups(array $groups): self;

    public function getContext(): ValidatorContextInterface;
}


text:
Scan Management
===============

.. autoclass:: nessus.Scan
    :members:


text:
package skinny.controller.feature

import skinny.micro.async.AsyncBeforeAfterDsl
import skinny.micro._

/**
  * beforeAction/afterAction support.
  *
  * @see http://guides.rubyonrails.org/action_controller_overview.html
  */
trait AsyncBeforeAfterActionFeature extends SkinnyMicroBase with AsyncBeforeAfterDsl {

  self: Handler with ActionDefinitionFeature =>

  /**
    * Collection of beforeAction functions.
    */
  private[this] val skinnyBeforeActions = new scala.collection.mutable.ListBuffer[(Context) => Any]

  /**
    * Collection of afterAction functions.
    */
  private[this] val skinnyAfterActions = new scala.collection.mutable.ListBuffer[(Context) => Any]

  /**
    * If you prefer #beforeFilter than #beforeAction, keep going!
    */
  def beforeFilter(only: Seq[String] = Nil, except: Seq[String] = Nil)(action: (Context) => Any): Unit = {
    beforeAction(only, except)(action)
  }

  /**
    * Registers beforeAction to this controller.
    *
    * @param only this action should be applied only for these action methods
    * @param except this action should not be applied for these action methods
    * @param action action
    */
  def beforeAction(only: Seq[String] = Nil, except: Seq[String] = Nil)(action: (Context) => Any): Unit = {
    skinnyBeforeActions += (
        (ctx) => {
          currentActionName.map { name =>
            // current path should not be excluded
            if (!except.exists(_ == name)) {
              // all actions should be included or this action should be included
              if (only.isEmpty || only.exists(_ == name)) {
                action(ctx)
              }
            }
          } getOrElse ().asInstanceOf[Any]
        }
    )
  }

  /**
    * If you prefer #afterFilter than #afterAction, keep going!
    */
  def afterFilter(only: Seq[String] = Nil, except: Seq[String] = Nil)(action: (Context) => Any): Unit = {
    afterAction(only, except)(action)
  }

  /**
    * Registers afterAction to this controller.
    *
    * @param only this action should be applied only for these action methods
    * @param except this action should not be applied for these action methods
    * @param action action
    */
  def afterAction(only: Seq[String] = Nil, except: Seq[String] = Nil)(action: (Context) => Any): Unit = {
    skinnyAfterActions += (
        (ctx) => {
          currentActionName.map { name =>
            // current path should not be excluded
            if (!except.exists(_ == name)) {
              // all actions should be included or this action should be included
              if (only.isEmpty || only.exists(_ == name)) {
                action(ctx)
              }
            }
          } getOrElse ().asInstanceOf[Any]
        }
    )
  }

  // executing actions in this controller

  before() { (ctx) =>
    skinnyBeforeActions.foreach(_.apply(ctx))
  }

  after() { (ctx) =>
    skinnyAfterActions.foreach(_.apply(ctx))
  }

}


text:
<?php

namespace Google\AdsApi\Dfp\v201702;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class WorkflowRequestType
{
    const WORKFLOW_APPROVAL_REQUEST = 'WORKFLOW_APPROVAL_REQUEST';
    const WORKFLOW_EXTERNAL_CONDITION_REQUEST = 'WORKFLOW_EXTERNAL_CONDITION_REQUEST';
    const UNKNOWN = 'UNKNOWN';

}


text:
class Scanner {
public:
  explicit Scanner(const Token* tok)
      : Scanner(&tok->str_, tok->loc_) {}
  Scanner(const std::string* text, const SourceLocation& loc)
      : Scanner(text, loc.filename_, loc.line_, loc.column_) {}
  explicit Scanner(const std::string* text,
                   const std::string* filename=nullptr,
                   unsigned line=1, unsigned column=1)
      : text_(text), tok_(Token::END) {
    // TODO(wgtdkp): initialization
    p_ = &(*text_)[0];
    loc_ = {filename, p_, line, 1};
  }

  virtual ~Scanner() {}
  Scanner(const Scanner& other) = delete;
  Scanner& operator=(const Scanner& other) = delete;

  // Scan plain text and generate tokens in ts.
  // The param 'ts' need not be empty, if so, the tokens
  // are inserted at the *header* of 'ts'.
  // The param 'ws' tells if there is leading white space
  // before this token, it is only SkipComment() that will
  // set this param.
  Token* Scan(bool ws=false);
  void Tokenize(TokenSequence& ts);
  static std::string ScanHeadName(const Token* lhs, const Token* rhs);
  Encoding ScanCharacter(int& val);
  Encoding ScanLiteral(std::string& val);
  std::string ScanIdentifier();

private:
  Token* SkipIdentifier();
  Token* SkipNumber();
  Token* SkipLiteral();
  Token* SkipCharacter();
  Token* MakeToken(int tag);
  Token* MakeNewLine();
  Encoding ScanEncoding(int c);
  int ScanEscaped();
  int ScanHexEscaped();
  int ScanOctEscaped(int c);
  int ScanUCN(int len);
  void SkipWhiteSpace();
  void SkipComment();
  bool IsUCN(int c) { return c == '\\' && (Test('u') || Test('U')); }
  bool IsOctal(int c) { return '0' <= c && c <= '7'; }
  int XDigit(int c);
  bool Empty() const { return *p_ == 0; }
  int Peek();
  bool Test(int c) { return Peek() == c; };
  int Next();
  void PutBack();
  bool Try(int c) {
    if (Peek() == c) {
      Next();
      return true;
    }
    return false;
  };
  void Mark() { tok_.loc_ = loc_; };

  const std::string* text_;
  SourceLocation loc_;
  Token tok_;
  const char* p_;
};

std::string* ReadFile(const std::string& filename);

#endif


text:
package ca.riftekit.photofly;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.MediaColumns;
import android.database.Cursor;
import android.content.ClipData;

public class MyJavaClass
{
    private static int RESULT_LOAD_IMAGE = 1;

    public MyJavaClass(){
    }

    public static Intent getOpenCameraIntent(){
	Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
	return intent;
    }

    public static Intent getIntent(){
//	ACTION_GET_CONTENT
//	ACTION_PICK
    // Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Intent pickIntent = new Intent();
        // pickIntent.setAction(Intent.ACTION_PICK);
        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
	pickIntent.setType("image/*");
	pickIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
	pickIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
	return pickIntent;
    }

    public static String[] handleResult(Intent imageReturnedIntent, Activity curActivity){

	ClipData clipData = imageReturnedIntent.getClipData();
	String[] ret;
	if (clipData == null){
	    ret = new String[1];
	    ret[0] = getStringPathFromImageUri(imageReturnedIntent.getData(), curActivity);
	    return ret;
	}

	ret = new String[ clipData.getItemCount()];
	for (int i = 0; i < clipData.getItemCount(); i++)
	{
	    Uri selectedImage = clipData.getItemAt(i).getUri();
//	    String[] filePathColumn = {MediaStore.Images.Media.DATA};

//	    Cursor cursor = curActivity.getContentResolver().query(
//		selectedImage, filePathColumn, null, null, null);
//	    cursor.moveToFirst();

//	    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//	    String filePath = cursor.getString(columnIndex);
//	    cursor.close();
	    ret[i] = getStringPathFromImageUri(selectedImage, curActivity);
	}

	return ret;
    }

    public static String[] handleResult_v2(Intent imageReturnedIntent, Activity curActivity) {
    	String[] filePathColumn = { MediaStore.Images.Media.DATA };
    	String[] ret;

    	ClipData clipData = imageReturnedIntent.getClipData();
    	if (clipData != null) {
    		ret = new String[clipData.getItemCount()];
    		for (int i = 0; i < clipData.getItemCount(); i++) {
    			Uri selectedImage = clipData.getItemAt(i).getUri();
    			ret[i] = getStringPathFromImageUri(selectedImage, curActivity);
    		}
        	return ret;
    	}

    	Uri intentData = imageReturnedIntent.getData();
    	if (intentData != null) {
    		ret = new String[1];
    		ret[0] = getStringPathFromImageUri(intentData, curActivity);
    		return ret;
    	}

    	return new String[0];
    }

    private static String getStringPathFromImageUri(Uri imUri, Activity curActivity){
	String[] filePathColumn = {MediaStore.Images.Media.DATA};

	Cursor cursor = curActivity.getContentResolver().query(
	    imUri, filePathColumn, null, null, null);
	cursor.moveToFirst();

	int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	String filePath = cursor.getString(columnIndex);
	cursor.close();
	return filePath;
    }

}


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'ralphs-little-helpers'
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">通信录管理系统</string>
    <string name="action_settings">Settings</string>

</resources>


text:
/* vim: set ft=objc fenc=utf-8 sw=2 ts=2 et: */
/*
 *  DOUAudioStreamer - A Core Audio based streaming audio player for iOS/Mac:
 *
 *      https://github.com/douban/DOUAudioStreamer
 *
 *  Copyright 2013-2016 Douban Inc.  All rights reserved.
 *
 *  Use and distribution licensed under the BSD license.  See
 *  the LICENSE file for full text.
 *
 *  Authors:
 *      Chongyu Zhu <i@lembacon.com>
 *
 */

#import <Foundation/Foundation.h>
#import "DOUAudioStreamer.h"

#include <Python.h>
#include <structmember.h>

typedef struct {
  PyObject_HEAD
  PyObject *url;
  CFTypeRef streamer;
} Streamer;

@interface AudioStreamer : DOUAudioStreamer <DOUAudioFile> {
@private
  NSURL *_url;
}
- (instancetype)initWithURL:(NSString *)url;
@end

@implementation AudioStreamer
- (instancetype)initWithURL:(NSString *)url
{
  if (url == nil ||
      (_url = [NSURL URLWithString:url]) == nil) {
    return nil;
  }

  self = [super initWithAudioFile:self];
  if (self) {
  }

  return self;
}

- (NSURL *)audioFileURL
{
  return _url;
}
@end

static void
Streamer_dealloc(Streamer *self)
{
  Py_XDECREF(self->url);
  if (self->streamer != NULL) {
    @autoreleasepool {
      CFBridgingRelease(self->streamer);
    }
  }
  self->ob_type->tp_free((PyObject *)self);
}

static PyObject *
Streamer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  Streamer *self;

  self = (Streamer *)type->tp_alloc(type, 0);
  if (self != NULL) {
    self->url = PyString_FromString("");
    if (self->url == NULL) {
      Py_DECREF(self);
      return NULL;
    }

    self->streamer = NULL;
  }

  return (PyObject *)self;
}

static int
Streamer_init(Streamer *self, PyObject *args, PyObject *kwds)
{
  static char *kwlist[] = { "url", NULL };

  const char *url = NULL;
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &url)) {
    return -1;
  }

  Py_XDECREF(self->url);
  self->url = PyString_FromString(url);

  @autoreleasepool {
    NSString *nsurl = @(url);
    AudioStreamer *s = [[AudioStreamer alloc] initWithURL:nsurl];
    self->streamer = CFBridgingRetain(s);
  }

  if (self->streamer == NULL) {
    PyErr_SetString(PyExc_AttributeError, "url");
    return -1;
  }

  return 0;
}

static PyMemberDef Streamer_members[] = {
  { "url", T_OBJECT, offsetof(Streamer, url), 0, NULL },
  { NULL, 0, 0, 0, NULL }
};

static PyObject *
Streamer_status(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      switch ([(__bridge AudioStreamer *)self->streamer status]) {
      case DOUAudioStreamerPlaying:
        return PyString_FromString("playing");

      case DOUAudioStreamerPaused:
        return PyString_FromString("paused");

      case DOUAudioStreamerFinished:
        return PyString_FromString("finished");

      case DOUAudioStreamerBuffering:
        return PyString_FromString("buffering");

      default:
        return PyString_FromString("unknown");
      }
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_error(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      NSError *error = [(__bridge AudioStreamer *)self->streamer error];
      if (error != nil) {
        return PyString_FromString([[error description] UTF8String]);
      }
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_volume(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      return PyFloat_FromDouble([(__bridge AudioStreamer *)self->streamer volume]);
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_set_volume(Streamer *self, PyObject *args)
{
  double volume = 0.0;
  if (!PyArg_ParseTuple(args, "d", &volume)) {
    return NULL;
  }

  if (self->streamer != NULL) {
    @autoreleasepool {
      [(__bridge AudioStreamer *)self->streamer setVolume:volume];
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_duration(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      return PyFloat_FromDouble([(__bridge AudioStreamer *)self->streamer duration]);
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_current_time(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      return PyFloat_FromDouble([(__bridge AudioStreamer *)self->streamer currentTime]);
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_download_speed(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      return PyLong_FromUnsignedLong([(__bridge AudioStreamer *)self->streamer downloadSpeed]);
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_play(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      [(__bridge AudioStreamer *)self->streamer play];
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_pause(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      [(__bridge AudioStreamer *)self->streamer pause];
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
Streamer_stop(Streamer *self)
{
  if (self->streamer != NULL) {
    @autoreleasepool {
      [(__bridge AudioStreamer *)self->streamer stop];
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

static PyMethodDef Streamer_methods[] = {
  { "status", (PyCFunction)Streamer_status, METH_NOARGS, "" },
  { "error", (PyCFunction)Streamer_error, METH_NOARGS, "" },
  { "volume", (PyCFunction)Streamer_volume, METH_NOARGS, "" },
  { "set_volume", (PyCFunction)Streamer_set_volume, METH_VARARGS, "" },
  { "duration", (PyCFunction)Streamer_duration, METH_NOARGS, "" },
  { "current_time", (PyCFunction)Streamer_current_time, METH_NOARGS, "" },
  { "download_speed", (PyCFunction)Streamer_download_speed, METH_NOARGS, "" },
  { "play", (PyCFunction)Streamer_play, METH_NOARGS, "" },
  { "pause", (PyCFunction)Streamer_pause, METH_NOARGS, "" },
  { "stop", (PyCFunction)Streamer_stop, METH_NOARGS, "" },
  { NULL, NULL, 0, NULL }
};

static PyTypeObject StreamerType = {
  PyObject_HEAD_INIT(NULL)
  0,                         /*ob_size*/
  "douas.Streamer",          /*tp_name*/
  sizeof(Streamer),          /*tp_basicsize*/
  0,                         /*tp_itemsize*/
  (destructor)Streamer_dealloc, /*tp_dealloc*/
  0,                         /*tp_print*/
  0,                         /*tp_getattr*/
  0,                         /*tp_setattr*/
  0,                         /*tp_compare*/
  0,                         /*tp_repr*/
  0,                         /*tp_as_number*/
  0,                         /*tp_as_sequence*/
  0,                         /*tp_as_mapping*/
  0,                         /*tp_hash */
  0,                         /*tp_call*/
  0,                         /*tp_str*/
  0,                         /*tp_getattro*/
  0,                         /*tp_setattro*/
  0,                         /*tp_as_buffer*/
  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
  "Streamer objects",        /* tp_doc */
  0,		                     /* tp_traverse */
  0,		                     /* tp_clear */
  0,		                     /* tp_richcompare */
  0,		                     /* tp_weaklistoffset */
  0,		                     /* tp_iter */
  0,                         /* tp_iternext */
  Streamer_methods,          /* tp_methods */
  Streamer_members,          /* tp_members */
  0,                         /* tp_getset */
  0,                         /* tp_base */
  0,                         /* tp_dict */
  0,                         /* tp_descr_get */
  0,                         /* tp_descr_set */
  0,                         /* tp_dictoffset */
  (initproc)Streamer_init,   /* tp_init */
  0,                         /* tp_alloc */
  Streamer_new,              /* tp_new */
};

static PyMethodDef module_methods[] = {
  { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC
initdouas(void)
{
  PyObject *module;

  StreamerType.tp_new = PyType_GenericNew;
  if (PyType_Ready(&StreamerType) < 0) {
    return;
  }

  module = Py_InitModule("douas", module_methods);

  Py_INCREF(&StreamerType);
  PyModule_AddObject(module, "Streamer", (PyObject *)&StreamerType);
}


text:
#include "battery.h"
#include "mock/tcpci_i2c_mock.h"
#include "task.h"
#include "driver/tcpm/tcpci.h"
#include "test_util.h"
#include "timer.h"
#include "usb_tcpmv2_compliance.h"
#include "usb_tc_sm.h"

#define BUFFER_SIZE 100

#define HEADER_BYTE_OFFSET 1
#define HEADER_BYTE_CNT 2
#define SRC_CAP_EXT_NUM_BATTERY_OFFSET 22

#define EXT_MSG_CHUNKED BIT(15)
#define EXT_MSG_DATA_SIZE_1 1
#define GBSDB_FIXED_BATTERY_0 (0 << 16)

static int number_of_fixed_batteries(void)
{
	return CONFIG_NUM_FIXED_BATTERIES;
}

static int number_of_swappable_batteries(void)
{
	return 0;
}

/*****************************************************************************
 * TD.PD.SRC3.E7 Battery Status sent timely
 *
 * Description:
 *	As Consumer (UFP), the Tester verifies that the UUT replies
 *	Get_Battery_Status message with a Battery_Status message timely.
 */
int test_td_pd_src3_e7(void)
{
	int msg_len;
	uint8_t data[BUFFER_SIZE];
	uint32_t ext_msg;

	int found_index;
	struct possible_tx possible[2];

	TEST_EQ(tcpci_startup(), EC_SUCCESS, "%d");

	/*
	 * a) Run PROC.PD.E1 Bring-up according to the UUT role.
	 */
	TEST_EQ(proc_pd_e1(PD_ROLE_DFP, INITIAL_AND_ALREADY_ATTACHED),
		EC_SUCCESS, "%d");

	/*
	 * b) The Tester waits until it can start an AMS (Run PROC.PD.E3) and
	 *    sends a Get_Source_Cap_Extended message to the UUT.
	 */
	TEST_EQ(proc_pd_e3(), EC_SUCCESS, "%d");

	partner_send_msg(TCPCI_MSG_SOP, PD_CTRL_GET_SOURCE_CAP_EXT, 0, 0, NULL);

	/*
	 * c) If a Not_Supported message is received, and Num_Fixed_Batteries
	 *    and Num_Swappable_Battery_Slots in the VIF are 0, the test
	 *    passes and stops here.
	 */
	possible[0].tx_type = TCPCI_MSG_SOP;
	possible[0].ctrl_msg = PD_CTRL_NOT_SUPPORTED;
	possible[0].data_msg = 0;

	possible[1].tx_type = TCPCI_MSG_SOP;
	possible[1].ctrl_msg = 0;
	possible[1].data_msg = PD_DATA_SOURCE_CAP;

	TEST_EQ(verify_tcpci_possible_tx(possible, 2, &found_index, data,
					 sizeof(data), &msg_len, 0),
		EC_SUCCESS, "%d");
	if (found_index == 0) {
		mock_set_alert(TCPC_REG_ALERT_TX_SUCCESS);
		task_wait_event(10 * MSEC);

		if (number_of_fixed_batteries() == 0 &&
		    number_of_swappable_batteries() == 0)
			return EC_SUCCESS;
	}
	/*
	 * d) If the Number of Batteries/Battery Slots field in the returned
	 *    Source_Capabilities_Extended message is 0, the test passes and
	 *    stops here.
	 */
	else {
		TEST_EQ(found_index, 1, "%d");
		mock_set_alert(TCPC_REG_ALERT_TX_SUCCESS);
		task_wait_event(10 * MSEC);

		if (data[HEADER_BYTE_OFFSET + HEADER_BYTE_CNT +
			 SRC_CAP_EXT_NUM_BATTERY_OFFSET] == 0)
			return EC_SUCCESS;
	}

	/*
	 * e) The Tester waits until it can start an AMS (Run PROC.PD.E3) and
	 *    sends a Get_Battery_Status message to the UUT
	 */
	ext_msg = EXT_MSG_CHUNKED | EXT_MSG_DATA_SIZE_1 | GBSDB_FIXED_BATTERY_0;
	partner_send_msg(TCPCI_MSG_SOP, PD_EXT_GET_BATTERY_STATUS, 1, 1,
			 &ext_msg);

	/*
	 * f) If a Battery_Status message is not received within
	 *    tReceiverResponse max, the test fails. This delay is measured
	 *    from the time the last bit of Get_Battery_Status message EOP has
	 *    been transmitted to the time the first bit of the Battery_Status
	 *    message preamble has been received.
	 */
	TEST_EQ(verify_tcpci_tx_timeout(TCPCI_MSG_SOP, 0,
					PD_DATA_BATTERY_STATUS, (15 * MSEC)),
		EC_SUCCESS, "%d");
	mock_set_alert(TCPC_REG_ALERT_TX_SUCCESS);
	task_wait_event(10 * MSEC);

	return EC_SUCCESS;
}


text:
Contact Us

			You are here: Home Contact Us

Get in Touch

Visit Us

Saveetha Nagar, Thandallam

Email Us

principalnursing@saveetha.com

Call Us

(+91) 123 456 7890

Fill the Contact Form

				<form class="form-inline findus" id="contact-form" onSubmit="return false">

								<input type="text" class="form-control" placeholder="Name"  name="name" id="name" required>

								<input type="email" class="form-control" placeholder="Email" name="email" id="email" required>

								<input type="text" class="form-control" placeholder="Website" name="website" id="website" required>

							<textarea placeholder="Comment"  name="message" id="message"></textarea>
							<button class="btn_common yellow border_radius" id="btn_submit">Submit</button>

				</form>


text:
using Rg.ServiceCore.Operations;
using Rg.ApiTypes;
using System.Threading.Tasks;
using System.Web.Http;

namespace Rg.Api.Controllers
{
    /// <summary>
    /// Searches for items.
    /// </summary>
    public class SearchController : ApiControllerBase
    {
        /// <summary>
        /// Gets items matching a search term.
        /// </summary>
        /// <param name="term">The search term to match.</param>
        /// <returns>The items matching this term.</returns>
        [Route("api/Search")]
        public Task<SearchResults> Get([FromUri] string term)
        {
            return SearchOperations.SearchAsync(DbContext, term);
        }
    }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Sales_Model_Entity_Setup */

$conn = $installer->getConnection();

/* @var $conn Varien_Db_Adapter_Pdo_Mysql */
$installer->addAttribute('quote_item', 'product_type', array());
$installer->addAttribute('order_item', 'product_type', array());


text:
"""Test for multi-worker training tutorial."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import os
import re
import zipfile
from absl import logging
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.experimental.ops import distribute_options
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import collective_all_reduce_strategy
from tensorflow.python.distribute import combinations as ds_combinations
from tensorflow.python.distribute import multi_process_runner
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import test_combinations as combinations
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.optimizer_v2 import gradient_descent
from tensorflow.python.lib.io import file_io
from tensorflow.python.platform import test
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training.tracking import util as tracking_util
from tensorflow.python.util import nest

class MultiWorkerTutorialTest(parameterized.TestCase, test.TestCase):
  """Test multi-worker training flow demo'ed in go/multi-worker-with-keras."""

  @contextlib.contextmanager
  def skip_fetch_failure_exception(self):
    try:
      yield
    except zipfile.BadZipfile as e:
      self.skipTest('Data loading error: Bad magic number for file header.')
    except Exception as e:  # pylint: disable=broad-except
      if 'URL fetch failure' in str(e):
        self.skipTest('URL fetch error not considered failure of the test.')
      else:
        raise

  @ds_combinations.generate(
      combinations.combine(
          mode=['eager'],
          shard_policy=[None] + list(distribute_options.AutoShardPolicy)))
  def testMultiWorkerTutorial(self, mode, shard_policy):
    """Test multi-worker training flow demo'ed in go/multi-worker-with-keras.

    This test should be kept in sync with the code samples in
    go/multi-worker-with-keras.

    Args:
      mode: Runtime mode.
      shard_policy: None or any of tf.data.experimental.AutoShardPolicy for
        testing.
    """
    if shard_policy is distribute_options.AutoShardPolicy.FILE:
      self.skipTest('TensorSliceDataset is not shardable with FILE policy.')

    def mnist_dataset(batch_size):
      with self.skip_fetch_failure_exception():
        (x_train, y_train), _ = mnist.load_data()
      # The `x` arrays are in uint8 and have values in the range [0, 255].
      # We need to convert them to float32 with values in the range [0, 1]
      x_train = x_train / np.float32(255)
      y_train = y_train.astype(np.int64)
      train_dataset = dataset_ops.DatasetV2.from_tensor_slices(
          (x_train, y_train)).shuffle(60000).repeat().batch(batch_size)
      return train_dataset

    def build_and_compile_cnn_model():
      model = keras.Sequential([
          keras.layers.Input(shape=(28, 28)),
          keras.layers.Reshape(target_shape=(28, 28, 1)),
          keras.layers.Conv2D(32, 3, activation='relu'),
          keras.layers.Flatten(),
          keras.layers.Dense(128, activation='relu'),
          keras.layers.Dense(10)
      ])
      model.compile(
          loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
          optimizer=gradient_descent.SGD(learning_rate=0.001),
          metrics=['accuracy'])
      return model

    per_worker_batch_size = 64

    single_worker_dataset = mnist_dataset(per_worker_batch_size)
    single_worker_model = build_and_compile_cnn_model()
    single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70)

    num_workers = 4

    def fn(model_path, checkpoint_dir):
      global_batch_size = per_worker_batch_size * num_workers
      strategy = collective_all_reduce_strategy.CollectiveAllReduceStrategy()
      with strategy.scope():
        multi_worker_model = build_and_compile_cnn_model()

      callbacks = [
          keras.callbacks.ModelCheckpoint(
              filepath=os.path.join(self.get_temp_dir(), 'checkpoint'))
      ]

      multi_worker_dataset = mnist_dataset(global_batch_size)
      if shard_policy:
        options = dataset_ops.Options()
        options.experimental_distribute.auto_shard_policy = shard_policy
        multi_worker_dataset = multi_worker_dataset.with_options(options)

      multi_worker_model.fit(
          multi_worker_dataset,
          epochs=2,
          steps_per_epoch=20,
          callbacks=callbacks)

      def _is_chief(task_type, task_id):
        return task_type is None or task_type == 'chief' or (
            task_type == 'worker' and task_id == 0)

      def _get_temp_dir(dirpath, task_id):
        base_dirpath = 'workertemp_' + str(task_id)
        temp_dir = os.path.join(dirpath, base_dirpath)
        file_io.recursive_create_dir_v2(temp_dir)
        return temp_dir

      def write_filepath(filepath, task_type, task_id):
        dirpath = os.path.dirname(filepath)
        base = os.path.basename(filepath)
        if not _is_chief(task_type, task_id):
          dirpath = _get_temp_dir(dirpath, task_id)
        return os.path.join(dirpath, base)

      task_type, task_id = (strategy.cluster_resolver.task_type,
                            strategy.cluster_resolver.task_id)
      write_model_path = write_filepath(model_path, task_type, task_id)

      multi_worker_model.save(write_model_path)
      if not _is_chief(task_type, task_id):
        file_io.delete_recursively_v2(os.path.dirname(write_model_path))

      # Make sure chief finishes saving before non-chief's assertions.
      multi_process_runner.get_barrier().wait()

      if not file_io.file_exists_v2(model_path):
        raise RuntimeError()
      if file_io.file_exists_v2(write_model_path) != _is_chief(
          task_type, task_id):
        raise RuntimeError()

      loaded_model = keras.saving.save.load_model(model_path)
      loaded_model.fit(multi_worker_dataset, epochs=2, steps_per_epoch=20)

      checkpoint = tracking_util.Checkpoint(model=multi_worker_model)
      write_checkpoint_dir = write_filepath(checkpoint_dir, task_type, task_id)
      checkpoint_manager = checkpoint_management.CheckpointManager(
          checkpoint, directory=write_checkpoint_dir, max_to_keep=1)

      checkpoint_manager.save()
      if not _is_chief(task_type, task_id):
        file_io.delete_recursively_v2(write_checkpoint_dir)

      # Make sure chief finishes saving before non-chief's assertions.
      multi_process_runner.get_barrier().wait()

      if not file_io.file_exists_v2(checkpoint_dir):
        raise RuntimeError()
      if file_io.file_exists_v2(write_checkpoint_dir) != _is_chief(
          task_type, task_id):
        raise RuntimeError()

      latest_checkpoint = checkpoint_management.latest_checkpoint(
          checkpoint_dir)
      checkpoint.restore(latest_checkpoint)
      multi_worker_model.fit(multi_worker_dataset, epochs=2, steps_per_epoch=20)

      logging.info('testMultiWorkerTutorial successfully ends')

    model_path = os.path.join(self.get_temp_dir(), 'model.tf')
    checkpoint_dir = os.path.join(self.get_temp_dir(), 'ckpt')
    try:
      mpr_result = multi_process_runner.run(
          fn,
          multi_worker_test_base.create_cluster_spec(num_workers=num_workers),
          args=(model_path, checkpoint_dir),
          return_output=True)
    except errors_impl.UnavailableError as e:
      self.skipTest('Skipping error: {}: {}'.format(type(e), str(e)))

    self.assertTrue(
        any([
            'testMultiWorkerTutorial successfully ends' in msg
            for msg in mpr_result.stdout
        ]))

    def extract_accuracy(worker_id, input_string):
      match = re.match(
          r'\[worker\-{}\].*accuracy: (\d+\.\d+).*'.format(worker_id),
          input_string)
      return None if match is None else float(match.group(1))

    for worker_id in range(num_workers):
      accu_result = nest.map_structure(
          lambda x: extract_accuracy(worker_id, x),  # pylint: disable=cell-var-from-loop
          mpr_result.stdout)
      self.assertTrue(
          any(accu_result), 'Every worker is supposed to have accuracy result.')

if __name__ == '__main__':
  multi_process_runner.test_main()


text:
<title>Cirrus | {{$title}}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<link rel="stylesheet" type="text/css" href="{{asset('bower/bootstrap/dist/css/bootstrap.min.css') }}" >
<link rel="stylesheet" type="text/css" href="{{asset('css/style.css')}}" />
<link rel="stylesheet" type="text/css" href="{{asset('css/custom.css')}}" />
<link href='http://fonts.googleapis.com/css?family=Poiret+One' rel='stylesheet' type='text/css' />
<script type="text/javascript" src="{{asset('js/jquery.min.js')}}"></script>
<script type="text/javascript" src="{{asset('js/script.js')}}"></script>
<script type="text/javascript" src="{{asset('js/menu.js')}}"></script>
<script src="/path/to/isotope.pkgd.min.js"></script>
<!--[if lt IE 9]>
	<script type="text/javascript" src="{{asset('js/html5.js')}}"></script>
<![endif]-->


text:
import { DOCUMENT } from "../const";
import { MethodError } from "../errors";
import { $Document } from "../document/index";
import { $Element } from "../element/index";

const reQuick = /^<([a-zA-Z-]+)\/?>$/;
const sandbox = DOCUMENT.createElement("body");

function makeMethod(all) {
    return function(value) {
        const node = this[0];

        if (!node || typeof value !== "string") {
            throw new MethodError("create" + all, arguments);
        }

        var result = all ? [] : null;

        const quickMatch = !result && reQuick.exec(value);
        if (quickMatch) {
            return new $Element(node.createElement(quickMatch[1]));
        }

        sandbox.innerHTML = value.trim(); // parse HTML string

        for (var it; it = sandbox.firstElementChild; ) {
            sandbox.removeChild(it); // detach element from the sandbox

            if (node !== DOCUMENT) {
                // adopt node for external documents
                it = node.adoptNode(it);
            }

            if (result) {
                result.push(new $Element(it));
            } else {
                result = new $Element(it);
                // need only the first element
                break;
            }
        }

        return result || new $Element();
    };
}

/**
 * Create a new {@link $Element} from a HTML string
 * @param  {String} content HTMLString
 * @return {$Element} an element wrapper
 * @function
 * @example
 * DOM.create("
");                // => wrapper of

 * DOM.create(""); // => wrapper of  + innner
 */
$Document.prototype.create = makeMethod("");

/**
 * Create a new Array.<{@link $Element}> from a HTML string
 * @param  {String} content HTMLString
 * @return {Array.<$Element>} an array of element wrappers
 * @function
 * @example
 * DOM.createAll(""); // => array with 2 $Elements:  and
 */
$Document.prototype.createAll = makeMethod("All");


text:
using System;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Weapsy.Domain.Menus;
using Menu = Weapsy.Data.Entities.Menu;

namespace Weapsy.Data.Tests.Reporting
{
    [TestFixture]
    public class MenuHandlersTests
    {
        private DbContextOptions<WeapsyDbContext> _contextOptions;
        private Guid _siteId;
        private Guid _menuId;

        [SetUp]
        public void Setup()
        {
            _contextOptions = DbContextShared.CreateContextOptions();

            using (var context = new WeapsyDbContext(_contextOptions))
            {
                _siteId = Guid.NewGuid();
                _menuId = Guid.NewGuid();

                context.Menus.AddRange(
                    new Menu
                    {
                        SiteId = _siteId,
                        Id = _menuId,
                        Name = "Menu Name 1",
                        Status = MenuStatus.Active
                    }
                );

                context.SaveChanges();
            }
        }
    }
}


text:
namespace P23.MetaTrader4.Manager.Contracts.Configuration
{
    /// <summary>
    /// Object that represents group margin configuration
    /// </summary>
    public class GroupMargin
    {
        /// <summary>
        /// Security
        /// </summary>
        public string Symbol { get; set; }

        /// <summary>
        /// Swap size for long positions
        /// </summary>
        public double SwapLong { get; set; }

        /// <summary>
        /// /// <summary>
        /// Swap size for short positions
        /// </summary>
        /// </summary>
        public double SwapShort { get; set; }

        /// <summary>
        /// Margin divider
        /// </summary>
        public double MarginDivider { get; set; }
    }
}


text:
package org.jboss.arquillian.container.was.embedded_8;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;

import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.container.spi.context.annotation.ContainerScoped;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;

/**
 * WebSphereEmbeddedContainer
 *
 * @author Gerhard Poul
 * @version $Revision: $
 */
public class WebSphereEmbeddedContainer implements DeployableContainer<WebSphereEmbeddedContainerConfiguration>
{
   //-------------------------------------------------------------------------------------||
   // Instance Members -------------------------------------------------------------------||
   //-------------------------------------------------------------------------------------||

   private static final String className = WebSphereEmbeddedContainer.class.getName();

   private static Logger log = Logger.getLogger(className);

   private WebSphereEmbeddedContainerConfiguration containerConfiguration;

   private EJBContainer ec;

   /**
    * The JNDI Context for this container.
    */
   @Inject
   @ContainerScoped
   private InstanceProducer<Context> jndiContext;

   //-------------------------------------------------------------------------------------||
   // Required Implementations - DeployableContainer -------------------------------------||
   //-------------------------------------------------------------------------------------||

   public void setup(WebSphereEmbeddedContainerConfiguration configuration)
   {
      if (log.isLoggable(Level.FINER)) {
            log.entering(className, "setup");
      }

      this.containerConfiguration = configuration;

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "setup");
      }
   }

   public void start() throws LifecycleException
   {
      if (log.isLoggable(Level.FINER)) {
         log.entering(className, "start");
      }

      // There should be nothing to do here.

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "start");
      }
   }

   public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException
   {
      if (log.isLoggable(Level.FINER)) {
         log.entering(className, "deploy");

         log.finer("Archive provided to deploy method: " + archive.toString(true));
      }

      // Save the archive to disk so it can be loaded by the container.
      // For JNDI lookups to work correctly the archive name must match the
      // one of the provided archive file.
      String tmpDir = System.getProperty("java.io.tmpdir");
      File exportedArchiveLocation = new File(tmpDir, archive.getName());
      archive.as(ZipExporter.class).exportTo(exportedArchiveLocation, true);

      // Create the properties object to pass to the embeddable container:
      Map<String,Object> props = new HashMap<String,Object>();

      // Set the embeddable container configuration file if it has been
      // provided in the arquillian configuration.
      if (containerConfiguration.getEmbeddedProperties() != null)
         props.put("com.ibm.websphere.embeddable.configFileName", containerConfiguration.getEmbeddedProperties());

      // Specify the EJB modules to start when creating the container:
      File[] ejbModules = new File[1];
      ejbModules[0] = exportedArchiveLocation;
      props.put(EJBContainer.MODULES, ejbModules);

      // Start the Embeddable Container
      ec = EJBContainer.createEJBContainer(props);

      // Set the JNDI Context
      jndiContext.set(ec.getContext());

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "deploy");
      }

      return new ProtocolMetaData();
   }

   public void undeploy(final Archive<?> archive) throws DeploymentException
   {
      if (log.isLoggable(Level.FINER)) {
         log.entering(className, "undeploy");
      }

      // Close the Embeddable Container
      ec.close();

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "undeploy");
      }
   }

   public void stop() throws LifecycleException
   {
      if (log.isLoggable(Level.FINER)) {
         log.entering(className, "stop");
      }

      // There should be nothing to do here.

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "stop");
      }
   }

	public ProtocolDescription getDefaultProtocol() {
      if (log.isLoggable(Level.FINER)) {
         log.entering(className, "getDefaultProtocol");
      }

      if (log.isLoggable(Level.FINER)) {
         log.exiting(className, "getDefaultProtocol");
      }

		return new ProtocolDescription("Local");
	}

	@Override
   public Class<WebSphereEmbeddedContainerConfiguration> getConfigurationClass() {
      return WebSphereEmbeddedContainerConfiguration.class;
   }

   public void deploy(Descriptor descriptor) throws DeploymentException {
      // TODO Auto-generated method stub

   }

   public void undeploy(Descriptor descriptor) throws DeploymentException {
      // TODO Auto-generated method stub

   }
}