text:
package org.appcelerator.titanium.proxy;

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;

import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.AsyncResult;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiBlob;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.util.TiAnimationBuilder;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiUrl;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.view.TiAnimation;
import org.appcelerator.titanium.view.TiUIView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewAnimationUtils;

/**
 * The parent class of view proxies.
 */
@Kroll.proxy(propertyAccessors={
	// background properties
	"backgroundImage", "backgroundRepeat", "backgroundSelectedImage",
	"backgroundFocusedImage", "backgroundDisabledImage", "backgroundColor",
	"backgroundSelectedColor", "backgroundFocusedColor", "backgroundDisabledColor",
	"backgroundPadding", "backgroundGradient",

	// border properties
	"borderColor", "borderRadius", "borderWidth",

	// layout / dimension (size/width/height have custom accessors)
	"left", "top", "right", "bottom", "layout", "zIndex",

	// accessibility
	TiC.PROPERTY_ACCESSIBILITY_HINT, TiC.PROPERTY_ACCESSIBILITY_LABEL, TiC.PROPERTY_ACCESSIBILITY_VALUE,
	TiC.PROPERTY_ACCESSIBILITY_HIDDEN,

	// others
	"focusable", "touchEnabled", "visible", "enabled", "opacity",
	"softKeyboardOnFocus", "transform", "elevation", "touchTestId",
	"translationX", "translationY", "translationZ"
})
public abstract class TiViewProxy extends KrollProxy implements Handler.Callback
{
	private static final String TAG = "TiViewProxy";

	private static final int MSG_FIRST_ID = KrollProxy.MSG_LAST_ID + 1;

	private static final int MSG_GETVIEW = MSG_FIRST_ID + 100;
	private static final int MSG_ADD_CHILD = MSG_FIRST_ID + 102;
	private static final int MSG_REMOVE_CHILD = MSG_FIRST_ID + 103;
	private static final int MSG_BLUR = MSG_FIRST_ID + 104;
	private static final int MSG_FOCUS = MSG_FIRST_ID + 105;
	private static final int MSG_SHOW = MSG_FIRST_ID + 106;
	private static final int MSG_HIDE = MSG_FIRST_ID + 107;
	private static final int MSG_ANIMATE = MSG_FIRST_ID + 108;
	private static final int MSG_TOIMAGE = MSG_FIRST_ID + 109;
	private static final int MSG_GETSIZE = MSG_FIRST_ID + 110;
	private static final int MSG_GETRECT = MSG_FIRST_ID + 111;
	private static final int MSG_FINISH_LAYOUT = MSG_FIRST_ID + 112;
	private static final int MSG_UPDATE_LAYOUT = MSG_FIRST_ID + 113;
	private static final int MSG_QUEUED_ANIMATE = MSG_FIRST_ID + 114;
	private static final int MSG_INSERT_VIEW_AT = MSG_FIRST_ID + 115;
	private static final int MSG_HIDE_KEYBOARD = MSG_FIRST_ID + 116;

	protected static final int MSG_LAST_ID = MSG_FIRST_ID + 999;

	protected ArrayList<TiViewProxy> children;
	protected WeakReference<TiViewProxy> parent;

	protected TiUIView view;
	protected Object pendingAnimationLock;
	protected TiAnimationBuilder pendingAnimation;
	private boolean isDecorView = false;
	private boolean overrideCurrentAnimation = false;

	// TODO: Deprecated since Release 3.0.0
	@Deprecated private AtomicBoolean layoutStarted = new AtomicBoolean();

	/**
	 * Constructs a new TiViewProxy instance.
	 * @module.api
	 */
	public TiViewProxy()
	{
		pendingAnimationLock = new Object();

		defaultValues.put(TiC.PROPERTY_BACKGROUND_REPEAT, false);
		defaultValues.put(TiC.PROPERTY_VISIBLE, true);
		defaultValues.put(TiC.PROPERTY_ENABLED, true);
	}

	@Override
	public void handleCreationDict(KrollDict options)
	{
		options = handleStyleOptions(options);
		super.handleCreationDict(options);

		if (options.containsKey(TiC.PROPERTY_OVERRIDE_CURRENT_ANIMATION)) {
			overrideCurrentAnimation = TiConvert.toBoolean(options, TiC.PROPERTY_OVERRIDE_CURRENT_ANIMATION, false);
		}

		//TODO eventManager.addOnEventChangeListener(this);
	}

	public boolean getOverrideCurrentAnimation() {
		return overrideCurrentAnimation;
	}

	private static HashMap<TiUrl,String> styleSheetUrlCache = new HashMap<TiUrl,String>(5);
	protected String getBaseUrlForStylesheet()
	{
		TiUrl creationUrl = getCreationUrl();
		if (styleSheetUrlCache.containsKey(creationUrl)) {
			return styleSheetUrlCache.get(creationUrl);
		}

		String baseUrl = creationUrl.baseUrl;
		if (baseUrl == null || (baseUrl.equals("app://") && creationUrl.url.equals(""))) {
			baseUrl = "app://app.js";
		} else {
			baseUrl = creationUrl.resolve();
		}

		int idx = baseUrl.lastIndexOf("/");
		if (idx != -1) {
			baseUrl = baseUrl.substring(idx + 1).replace(".js", "");
		}

		styleSheetUrlCache.put(creationUrl,baseUrl);
		return baseUrl;
	}

	protected KrollDict handleStyleOptions(KrollDict options)
	{
		String viewId = getProxyId();
		TreeSet<String> styleClasses = new TreeSet<String>();
		// TODO styleClasses.add(getShortAPIName().toLowerCase());

		if (options.containsKey(TiC.PROPERTY_ID)) {
			viewId = TiConvert.toString(options, TiC.PROPERTY_ID);
		}
		if (options.containsKey(TiC.PROPERTY_CLASS_NAME)) {
			String className = TiConvert.toString(options, TiC.PROPERTY_CLASS_NAME);
			for (String clazz : className.split(" ")) {
				styleClasses.add(clazz);
			}
		}
		if (options.containsKey(TiC.PROPERTY_CLASS_NAMES)) {
			Object c = options.get(TiC.PROPERTY_CLASS_NAMES);
			if (c.getClass().isArray()) {
				int length = Array.getLength(c);
				for (int i = 0; i < length; i++) {
					Object clazz = Array.get(c, i);
					if (clazz != null) {
						styleClasses.add(clazz.toString());
					}
				}
			}
		}

		String baseUrl = getBaseUrlForStylesheet();
		KrollDict dict = TiApplication.getInstance().getStylesheet(baseUrl, styleClasses, viewId);
		if (dict == null || dict.isEmpty()) {
			return options;
		}

		extend(dict);
		if (Log.isDebugModeEnabled()) {
			Log.d(TAG, "trying to get stylesheet for base:" + baseUrl + ",classes:" + styleClasses + ",id:" + viewId + ",dict:"
				+ dict, Log.DEBUG_MODE);
		}
		// merge in our stylesheet details to the passed in dictionary
		// our passed in dictionary takes precedence over the stylesheet
		dict.putAll(options);
		return dict;
	}

	public TiAnimationBuilder getPendingAnimation()
	{
		synchronized(pendingAnimationLock) {
			return pendingAnimation;
		}
	}

	public void clearAnimation(TiAnimationBuilder builder)
	{
		synchronized(pendingAnimationLock) {
			if (pendingAnimation != null && pendingAnimation == builder) {
				pendingAnimation = null;
			}
		}
	}

	//This handler callback is tied to the UI thread.
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public boolean handleMessage(Message msg)
	{
		switch(msg.what) {
			case MSG_GETVIEW : {
				AsyncResult result = (AsyncResult) msg.obj;
				result.setResult(handleGetView());
				return true;
			}
			case MSG_ADD_CHILD : {
				AsyncResult result = (AsyncResult) msg.obj;
				handleAdd((TiViewProxy) result.getArg());
				result.setResult(null); //Signal added.
				return true;
			}
			case MSG_REMOVE_CHILD : {
				AsyncResult result = (AsyncResult) msg.obj;
				handleRemove((TiViewProxy) result.getArg());
				result.setResult(null); //Signal removed.
				return true;
			}
			case MSG_BLUR : {
				handleBlur();
				return true;
			}
			case MSG_HIDE_KEYBOARD : {
				handleHideKeyboard();
				return true;
			}
			case MSG_FOCUS : {
				handleFocus();
				return true;
			}
			case MSG_SHOW : {
				handleShow((KrollDict) msg.obj);
				return true;
			}
			case MSG_HIDE : {
				handleHide((KrollDict) msg.obj);
				return true;
			}
			case MSG_ANIMATE : {
				handleAnimate();
				return true;
			}
			case MSG_QUEUED_ANIMATE: {
				// An animation that was re-queued
				// because the view's height and width
				// were not yet known (i.e., not yet laid out)
				handleQueuedAnimate();
				return true;
			}
			case MSG_TOIMAGE: {
				AsyncResult result = (AsyncResult) msg.obj;
				result.setResult(handleToImage());
				return true;
			}
			case MSG_GETSIZE : {
				AsyncResult result = (AsyncResult) msg.obj;
				KrollDict d = null;
				d = new KrollDict();
				d.put(TiC.PROPERTY_X, 0);
				d.put(TiC.PROPERTY_Y, 0);
				if (view != null) {
					View v = view.getNativeView();
					if (v != null) {
						TiDimension nativeWidth = new TiDimension(v.getWidth(), TiDimension.TYPE_WIDTH);
						TiDimension nativeHeight = new TiDimension(v.getHeight(), TiDimension.TYPE_HEIGHT);

						// TiDimension needs a view to grab the window manager, so we'll just use the decorview of the current window
						View decorView = TiApplication.getAppCurrentActivity().getWindow().getDecorView();

						d.put(TiC.PROPERTY_WIDTH, nativeWidth.getAsDefault(decorView));
						d.put(TiC.PROPERTY_HEIGHT, nativeHeight.getAsDefault(decorView));
					}
				}
				if (!d.containsKey(TiC.PROPERTY_WIDTH)) {
					d.put(TiC.PROPERTY_WIDTH, 0);
					d.put(TiC.PROPERTY_HEIGHT, 0);
				}

				result.setResult(d);
				return true;
			}
			case MSG_GETRECT: {
				AsyncResult result = (AsyncResult) msg.obj;
				KrollDict d = null;
				d = new KrollDict();
				if (view != null) {
					View v = view.getOuterView();
					if (v != null) {
						TiDimension nativeWidth = new TiDimension(v.getWidth(), TiDimension.TYPE_WIDTH);
						TiDimension nativeHeight = new TiDimension(v.getHeight(), TiDimension.TYPE_HEIGHT);
						TiDimension nativeLeft = new TiDimension(v.getLeft(), TiDimension.TYPE_LEFT);
						TiDimension nativeTop = new TiDimension(v.getTop(), TiDimension.TYPE_TOP);

						// TiDimension needs a view to grab the window manager, so we'll just use the decorview of the current window
						View decorView = TiApplication.getAppCurrentActivity().getWindow().getDecorView();

						d.put(TiC.PROPERTY_WIDTH, nativeWidth.getAsDefault(decorView));
						d.put(TiC.PROPERTY_HEIGHT, nativeHeight.getAsDefault(decorView));
						d.put(TiC.PROPERTY_X, nativeLeft.getAsDefault(decorView));
						d.put(TiC.PROPERTY_Y, nativeTop.getAsDefault(decorView));
					}
				}
				if (!d.containsKey(TiC.PROPERTY_WIDTH)) {
					d.put(TiC.PROPERTY_WIDTH, 0);
					d.put(TiC.PROPERTY_HEIGHT, 0);
					d.put(TiC.PROPERTY_X, 0);
					d.put(TiC.PROPERTY_Y, 0);
				}

				result.setResult(d);
				return true;
			}
			case MSG_FINISH_LAYOUT : {
				handleFinishLayout();
				return true;
			}
			case MSG_UPDATE_LAYOUT : {
				handleUpdateLayout((HashMap) msg.obj);
				return true;
			}
			case MSG_INSERT_VIEW_AT : {
				handleInsertAt((HashMap) msg.obj);
				return true;
			}
		}
		return super.handleMessage(msg);
	}

	/*
	public Context getContext()
	{
		return getActivity();
	}
	*/

	@Kroll.getProperty @Kroll.method
	public KrollDict getRect()
	{
		return (KrollDict) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETRECT), getActivity());
	}

	@Kroll.getProperty @Kroll.method
	public KrollDict getSize()
	{
		return (KrollDict) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETSIZE), getActivity());
	}

	@Kroll.getProperty @Kroll.method
	public Object getWidth()
	{
		if (hasProperty(TiC.PROPERTY_WIDTH)) {
			return getProperty(TiC.PROPERTY_WIDTH);
		}

		return KrollRuntime.UNDEFINED;
	}

	@Kroll.setProperty(retain=false) @Kroll.method
	public void setWidth(Object width)
	{
		setPropertyAndFire(TiC.PROPERTY_WIDTH, width);
	}

	@Kroll.getProperty @Kroll.method
	public Object getHeight()
	{
		if (hasProperty(TiC.PROPERTY_HEIGHT)) {
			return getProperty(TiC.PROPERTY_HEIGHT);
		}

		return KrollRuntime.UNDEFINED;
	}

	@Kroll.setProperty(retain=false) @Kroll.method
	public void setHeight(Object height)
	{
		setPropertyAndFire(TiC.PROPERTY_HEIGHT, height);
	}

	@Kroll.getProperty @Kroll.method
	public Object getCenter()
	{
		Object dict = KrollRuntime.UNDEFINED;
		if (hasProperty(TiC.PROPERTY_CENTER)) {
			dict = getProperty(TiC.PROPERTY_CENTER);
		}

		return dict;
	}

	public void clearView()
	{
		if (view != null) {
			view.release();
		}
		view = null;
	}

	/**
	 * @return the TiUIView associated with this proxy.
	 * @module.api
	 */
	public TiUIView peekView()
	{
		return view;
	}

	public void setView(TiUIView view)
	{
		this.view = view;
	}

	public TiUIView forceCreateView()
	{
		view = null;
		return getOrCreateView();
	}

	/**
	 * Transfer an existing view to this view proxy.
	 * Special use in tableView. Do not use anywhere else.
	 * Called from TiTableViewRowProxyItem.java
	 * @param transferview - The view to transfer
	 * @param oldProxy - The currentProxy of the view
	 */
	public void transferView(TiUIView transferview, TiViewProxy oldProxy) {
		if(oldProxy != null) {
			oldProxy.setView(null);
			oldProxy.setModelListener(null);
		}
		view = transferview;
		modelListener = transferview;
		view.setProxy(this);
	}

	/**
	 * Creates or retrieves the view associated with this proxy.
	 * @return a TiUIView instance.
	 * @module.api
	 */
	public TiUIView getOrCreateView()
	{
		if (activity == null || view != null) {
			return view;
		}

		if (TiApplication.isUIThread()) {
			return handleGetView();
		}

		return (TiUIView) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETVIEW), 0);
	}

	protected TiUIView handleGetView()
	{
		if (view == null) {
			if (Log.isDebugModeEnabled()) {
				Log.d(TAG, "getView: " + getClass().getSimpleName(), Log.DEBUG_MODE);
			}

			Activity activity = getActivity();
			view = createView(activity);
			if (isDecorView) {
				if (activity != null) {
					((TiBaseActivity)activity).setViewProxy(view.getProxy());
				} else {
					Log.w(TAG, "Activity is null", Log.DEBUG_MODE);
				}
			}
			realizeViews(view);
			view.registerForTouch();
			view.registerForKeyPress();
		}
		return view;
	}

	public void realizeViews(TiUIView view)
	{
		setModelListener(view);

		// Use a copy so bundle can be modified as it passes up the inheritance
		// tree. Allows defaults to be added and keys removed.
		if (children != null) {
			try {
				for (TiViewProxy p : children) {
					TiUIView cv = p.getOrCreateView();
					view.add(cv);
				}
			} catch (ConcurrentModificationException e) {
				Log.e(TAG, e.getMessage(), e);
			}
		}

		synchronized(pendingAnimationLock) {
			if (pendingAnimation != null) {
				handlePendingAnimation(true);
			}
		}
	}

	public void releaseViews()
	{
		if (view != null) {
			if  (children != null) {
				for (TiViewProxy p : children) {
					p.releaseViews();
				}
			}
			view.release();
			view = null;
		}
		setModelListener(null);
		KrollRuntime.suggestGC();
	}

	/**
	 * Implementing classes should use this method to create and return the appropriate view.
	 * @param activity the context activity.
	 * @return a TiUIView instance.
	 * @module.api
	 */
	public abstract TiUIView createView(Activity activity);

	/**
	 * Adds a child to this view proxy.
	 * @param child The child view proxy to add.
	 * @module.api
	 */
	@Kroll.method
	public void add(TiViewProxy child)
	{
		if (child == null) {
			Log.e(TAG, "Add called with a null child");
			return;
		}

		if (children == null) {
			children = new ArrayList<TiViewProxy>();
		}

		if (peekView() != null) {
			if (TiApplication.isUIThread()) {
				handleAdd(child);
				return;
			}

			TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_ADD_CHILD), child);

		} else {
			children.add(child);
			child.parent = new WeakReference<TiViewProxy>(this);
		}
		//TODO zOrder
	}

	@Kroll.method
	public void replaceAt(Object params)
	{
		if (!(params instanceof HashMap)) {
			Log.e(TAG, "Argument for replaceAt must be a dictionary");
			return;
		}
		@SuppressWarnings("rawtypes")
		HashMap options = (HashMap) params;
		Integer position = -1;
		if(options.containsKey("position")) {
			position = (Integer) options.get("position");
		}
		if(children != null && children.size() > position) {
			TiViewProxy childToRemove = children.get(position);
			insertAt(params);
			remove(childToRemove);
		}
	}

	/**
	 * Adds a child to this view proxy in the specified position. This is useful for "vertical" and
	 * "horizontal" layouts.
	 * @param params A Dictionary containing a TiViewProxy for the view and an int for the position
	 * @module.api
	 */
	@Kroll.method
	public void insertAt(Object params)
	{
		if (!(params instanceof HashMap)) {
			Log.e(TAG, "Argument for insertAt must be a dictionary");
			return;
		}
		@SuppressWarnings("rawtypes")
		HashMap options = (HashMap) params;

		if (children == null) {
			children = new ArrayList<TiViewProxy>();
		}

		if (view != null) {
			if (TiApplication.isUIThread()) {
				handleInsertAt(options);
				return;
			}
			getMainHandler().obtainMessage(MSG_INSERT_VIEW_AT, options).sendToTarget();
		} else {
			handleInsertAt(options);
		}
	}

	private void handleInsertAt(@SuppressWarnings("rawtypes") HashMap options)
	{
		TiViewProxy child = null;
		Integer position = -1;
		if(options.containsKey("view")) {
			child = (TiViewProxy) options.get("view");
		}
		if(options.containsKey("position")) {
			position = (Integer) options.get("position");
		}
		if(child == null) {
			Log.e(TAG, "insertAt must be contain a view");
			return;
		}
		if(position < 0 || position > children.size()) {
			position = children.size();
		}

		children.add(position, child);
		child.parent = new WeakReference<TiViewProxy>(this);

		if (view != null) {
			child.setActivity(getActivity());
			if (this instanceof DecorViewProxy) {
				child.isDecorView = true;
			}
			TiUIView cv = child.getOrCreateView();
			view.insertAt(cv, position);
		}
	}

	private void handleAdd(TiViewProxy child)
	{
		children.add(child);
		child.parent = new WeakReference<TiViewProxy>(this);
		if (view != null) {
			child.setActivity(getActivity());
			if (this instanceof DecorViewProxy) {
				child.isDecorView = true;
			}
			view.add(child.getOrCreateView());
		}
	}

	/**
	 * Removes a view from this view proxy, releasing the underlying native view if it exists.
	 * @param child The child to remove.
	 * @module.api
	 */
	@Kroll.method
	public void remove(TiViewProxy child)
	{
		if (child == null) {
			Log.e(TAG, "Add called with null child");
			return;
		}

		if (peekView() != null) {
			if (TiApplication.isUIThread()) {
				handleRemove(child);
				return;
			}

			TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_REMOVE_CHILD), child);

		} else {
			if (children != null) {
				children.remove(child);
				if (child.parent != null && child.parent.get() == this) {
					child.parent = null;
				}
			}
		}
	}

	/**
	 * Removes all children views.
	 * @module.api
	 */
	@Kroll.method
	public void removeAllChildren()
	{
		if (children != null) {
			//children might be altered while we loop through it (threading)
			//so we first copy children as it was when asked to remove all children
			ArrayList<TiViewProxy> childViews = new ArrayList<TiViewProxy>();
			childViews.addAll(children);
			for (TiViewProxy child : childViews) {
				remove(child);
			}
		}
	}

	public void handleRemove(TiViewProxy child)
	{
		if (children != null) {
			children.remove(child);
			if (view != null) {
				view.remove(child.peekView());
			}
			if (child != null) {
				child.releaseViews();
			}
		}
	}

	@Kroll.method
	public void show(@Kroll.argument(optional=true) KrollDict options)
	{
		setProperty(TiC.PROPERTY_VISIBLE, true);
		if (TiApplication.isUIThread()) {
			handleShow(options);
		} else {
			getMainHandler().obtainMessage(MSG_SHOW, options).sendToTarget();
		}
	}

	protected void handleShow(KrollDict options)
	{
		if (view != null) {
			if (Build.VERSION.SDK_INT >= 21 && TiConvert.toBoolean(options, TiC.PROPERTY_ANIMATED, false)) {
				View nativeView = view.getOuterView();
				int width = nativeView.getWidth();
				int height = nativeView.getHeight();
				int radius = Math.max(width, height);
				Animator anim = ViewAnimationUtils.createCircularReveal(nativeView, width/2, height/2, 0, radius);
				view.show();
				anim.start();
				return;
			}
			view.show();
		}
	}

	@Kroll.method
	public void hide(@Kroll.argument(optional=true) KrollDict options)
	{
		setProperty(TiC.PROPERTY_VISIBLE, false);
		if (TiApplication.isUIThread()) {
			handleHide(options);
		} else {
			getMainHandler().obtainMessage(MSG_HIDE, options).sendToTarget();
		}

	}

	protected void handleHide(KrollDict options)
	{
		if (view != null) {
			synchronized(pendingAnimationLock) {
				if (pendingAnimation != null) {
					handlePendingAnimation(false);
				}
			}
			if (Build.VERSION.SDK_INT >= 21 && TiConvert.toBoolean(options, TiC.PROPERTY_ANIMATED, false)) {
				View nativeView = view.getOuterView();
				int width = nativeView.getWidth();
				int height = nativeView.getHeight();
				int radius = Math.max(width, height);
				Animator anim = ViewAnimationUtils.createCircularReveal(nativeView, width/2, height/2, radius, 0);
				anim.addListener(new AnimatorListenerAdapter() {
					@Override
					public void onAnimationEnd(Animator animation) {
						super.onAnimationEnd(animation);
						view.hide();
					}
				});

				anim.start();
				return;
			}
			view.hide();
		}
	}

	@Kroll.method
	public void animate(Object arg, @Kroll.argument(optional=true) KrollFunction callback)
	{
		synchronized (pendingAnimationLock) {
			if (arg instanceof HashMap) {
				@SuppressWarnings("rawtypes")
				HashMap options = (HashMap) arg;
				pendingAnimation = new TiAnimationBuilder();
				pendingAnimation.applyOptions(options);
			} else if (arg instanceof TiAnimation) {
				TiAnimation anim = (TiAnimation) arg;
				pendingAnimation = new TiAnimationBuilder();
				pendingAnimation.applyAnimation(anim);
			} else {
				throw new IllegalArgumentException("Unhandled argument to animate: " + arg.getClass().getSimpleName());
			}

			if (callback != null) {
				pendingAnimation.setCallback(callback);
			}

			handlePendingAnimation(false);
		}
	}

	public void handlePendingAnimation(boolean forceQueue)
	{
		if (pendingAnimation != null && peekView() != null) {
			if (forceQueue || !(TiApplication.isUIThread())) {
				if (Build.VERSION.SDK_INT < TiC.API_LEVEL_HONEYCOMB) {
					// Even this very small delay can help eliminate the bug
					// whereby the animated view's parent suddenly becomes
					// transparent (pre-honeycomb). cf. TIMOB-9813.
					getMainHandler().sendEmptyMessageDelayed(MSG_ANIMATE, 10);
				} else {
					getMainHandler().sendEmptyMessage(MSG_ANIMATE);
				}
			} else {
				handleAnimate();
			}
		}
	}

	protected void handleAnimate()
	{
		TiUIView tiv = peekView();

		if (tiv != null) {
			// If the nativeView's width and height are
			// zero, it could be that animate() was called
			// immediately upon window opening and the first
			// layout hasn't happened yet. In this case,
			// queue up a new request to animate.
			// Also do the same if layout properties
			// are changed and layout hasn't completed.
			View view = tiv.getNativeView();
			if (view == null || (view.getWidth() == 0 && view.getHeight() == 0) || tiv.isLayoutPending()) {
				getMainHandler().sendEmptyMessage(MSG_QUEUED_ANIMATE);
				return;
			} else {
				tiv.animate();
			}
		}
	}

	protected void handleQueuedAnimate()
	{
		TiUIView tiv = peekView();

		if (tiv != null) {
			tiv.animate();
		}
	}

	@Kroll.method
	public void blur()
	{
		if (TiApplication.isUIThread()) {
			handleBlur();
		} else {
			getMainHandler().sendEmptyMessage(MSG_BLUR);
		}
	}

	protected void handleBlur()
	{
		if (view != null) {
			view.blur();
		}
	}

	@Kroll.method
	public void focus()
	{
		if (TiApplication.isUIThread()) {
			handleFocus();
		} else {
			getMainHandler().sendEmptyMessage(MSG_FOCUS);
		}
	}

	protected void handleFocus()
	{
		if (view != null) {
			view.focus();
		}
	}

	@Kroll.method
	public TiBlob toImage()
	{
		if (TiApplication.isUIThread()) {
			return handleToImage();

		} else {
			return (TiBlob) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_TOIMAGE), getActivity());
		}
	}

	protected TiBlob handleToImage()
	{
		TiUIView view = getOrCreateView();
		if (view == null) {
			return null;
		}
		KrollDict dict = view.toImage();
		return TiUIHelper.getImageFromDict(dict);
	}

	/**
	 * Fires an event that can optionally be "bubbled" to the parent view.
	 *
	 * @param eventName event to get dispatched to listeners
	 * @param data data to include in the event
	 * @param bubbles if true will send the event to the parent view after it has been dispatched to this view's listeners.
	 * @return true if the event was handled
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean fireEvent(String eventName, Object data, boolean bubbles)
	{
		if (data == null) {
			data = new KrollDict();
		}

		// Set the "bubbles" property to indicate if the event needs to be bubbled.
		if (data instanceof HashMap) {
			((HashMap)data).put(TiC.PROPERTY_BUBBLES, bubbles);
		}

		// Dispatch the event to JavaScript which takes care of the bubbling.
		return super.fireEvent(eventName, data);
	}

	/**
	 * Fires an event that will be bubbled to the parent view.
	 */
	@Override
	public boolean fireEvent(String eventName, Object data)
	{
		// To remain compatible this override of fireEvent will always
		// bubble the event to the parent view. It should eventually be deprecated
		// in favor of using the fireEvent(String, Object, boolean) method.
		return fireEvent(eventName, data, true);
	}

	/**
	 * @return The parent view proxy of this view proxy.
	 * @module.api
	 */
	@Kroll.getProperty @Kroll.method
	public TiViewProxy getParent()
	{
		if (this.parent == null) {
			return null;
		}

		return this.parent.get();
	}

	public void setParent(TiViewProxy parent)
	{
		if (parent == null) {
			this.parent = null;
			return;
		}

		this.parent = new WeakReference<TiViewProxy>(parent);
	}

	@Override
	public KrollProxy getParentForBubbling()
	{
		return getParent();
	}

	@Override
	public void setActivity(Activity activity)
	{
		super.setActivity(activity);
		if (children != null) {
			for (TiViewProxy child : children) {
				child.setActivity(activity);
			}
		}
	}

	/**
	 * @return An array of the children view proxies of this view.
	 * @module.api
	 */
	@Kroll.getProperty @Kroll.method
	public TiViewProxy[] getChildren()
	{
		if (children == null) return new TiViewProxy[0];
		return children.toArray(new TiViewProxy[children.size()]);
	}

	@Override
	public void eventListenerAdded(String eventName, int count, KrollProxy proxy)
	{
		super.eventListenerAdded(eventName, count, proxy);
		if (eventName.equals(TiC.EVENT_CLICK) && proxy.equals(this) && count == 1 && !(proxy instanceof TiWindowProxy)) {
			if (!proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)
				|| TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED))) {
				setClickable(true);
			}
		}
	}

	@Override
	public void eventListenerRemoved(String eventName, int count, KrollProxy proxy)
	{
		super.eventListenerRemoved(eventName, count, proxy);
		if (eventName.equals(TiC.EVENT_CLICK) && count == 0 && proxy.equals(this) && !(proxy instanceof TiWindowProxy)) {
			if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)
				&& !TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED))) {
				setClickable(false);
			}
		}
	}

	public void setClickable(boolean clickable)
	{
		TiUIView v = peekView();
		if (v != null) {
			View nv = v.getNativeView();
			if (nv != null) {
				nv.setClickable(clickable);
			}
		}
	}

	@Kroll.method
	public void addClass(Object[] classNames)
	{
		// This is a pretty naive implementation right now,
		// but it will work for our current needs
		String baseUrl = getBaseUrlForStylesheet();
		ArrayList<String> classes = new ArrayList<String>();
		for (Object c : classNames) {
			classes.add(TiConvert.toString(c));
		}
		KrollDict options = TiApplication.getInstance().getStylesheet(baseUrl, classes, null);
		extend(options);
	}

	@Kroll.method @Kroll.getProperty
	public boolean getKeepScreenOn()
	{
		Boolean keepScreenOn = null;
		TiUIView v = peekView();
		if (v != null) {
			View nv = v.getNativeView();
			if (nv != null) {
				keepScreenOn = nv.getKeepScreenOn();
			}
		}

		//Keep the proxy in the correct state
		Object current = getProperty(TiC.PROPERTY_KEEP_SCREEN_ON);
		if (current != null) {
			boolean currentValue = TiConvert.toBoolean(current);
			if (keepScreenOn == null) {
				keepScreenOn = currentValue;
			} else {
				if (currentValue != keepScreenOn) {
					setProperty(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
				} else {
					keepScreenOn = currentValue;
				}
			}
		} else {
			if (keepScreenOn == null) {
				keepScreenOn = false; // Android default
			}

			setProperty(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
		}

		return keepScreenOn;
	}

	@Kroll.method @Kroll.setProperty(retain=false)
	public void setKeepScreenOn(boolean keepScreenOn)
	{
		setPropertyAndFire(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
	}

	@Kroll.method
	public KrollDict convertPointToView(KrollDict point, TiViewProxy dest)
	{
		if (point == null) {
			throw new IllegalArgumentException("convertPointToView: point must not be null");
		}

		if (dest == null) {
			throw new IllegalArgumentException("convertPointToView: destinationView must not be null");
		}

		if (!point.containsKey(TiC.PROPERTY_X)) {
			throw new IllegalArgumentException("convertPointToView: required property \"x\" not found in point");
		}

		if (!point.containsKey(TiC.PROPERTY_Y)) {
			throw new IllegalArgumentException("convertPointToView: required property \"y\" not found in point");
		}

		// The spec says to throw an exception if x or y cannot be converted to numbers.
		// TiConvert does that automatically for us.
		int x = TiConvert.toInt(point, TiC.PROPERTY_X);
		int y = TiConvert.toInt(point, TiC.PROPERTY_Y);

		TiUIView view = peekView();
		TiUIView destView = dest.peekView();
		if (view == null) {
			Log.w(TAG, "convertPointToView: View has not been attached, cannot convert point");
			return null;
		}

		if (destView == null) {
			Log.w(TAG, "convertPointToView: DestinationView has not been attached, cannot convert point");
			return null;
		}

		View nativeView = view.getNativeView();
		View destNativeView = destView.getNativeView();
		if (nativeView == null || nativeView.getParent() == null) {
			Log.w(TAG, "convertPointToView: View has not been attached, cannot convert point");
			return null;
		}

		if (destNativeView == null || destNativeView.getParent() == null) {
			Log.w(TAG, "convertPointToView: DestinationView has not been attached, cannot convert point");
			return null;
		}

		int viewLocation[] = new int[2];
		int destLocation[] = new int[2];
		nativeView.getLocationInWindow(viewLocation);
		destNativeView.getLocationInWindow(destLocation);

		if (Log.isDebugModeEnabled()) {
			Log.d(TAG, "nativeView location in window, x: " + viewLocation[0] + ", y: " + viewLocation[1], Log.DEBUG_MODE);
			Log.d(TAG, "destNativeView location in window, x: " + destLocation[0] + ", y: " + destLocation[1], Log.DEBUG_MODE);
		}

		int pointWindowX = viewLocation[0] + x;
		int pointWindowY = viewLocation[1] + y;

		// Apply reverse transformation to get the original location
		float[] points = new float[] { pointWindowX - destLocation[0], pointWindowY - destLocation[1] };
		points = destView.getPreTranslationValue(points);

		KrollDict destPoint = new KrollDict();
		destPoint.put(TiC.PROPERTY_X, (int) points[0]);
		destPoint.put(TiC.PROPERTY_Y, (int) points[1]);
		return destPoint;
	}

	// TODO: Deprecated since Release 3.0.0
	@Kroll.method @Deprecated
	public void startLayout()
	{
		Log.w(TAG, "startLayout() is deprecated.", Log.DEBUG_MODE);

		layoutStarted.set(true);
	}

	// TODO: Deprecated since Release 3.0.0
	@Kroll.method @Deprecated
	public void finishLayout()
	{
		Log.w(TAG, "finishLayout() is deprecated.", Log.DEBUG_MODE);

		// Don't force a layout if startLayout() was never called
		if (!isLayoutStarted()) {
			return;
		}
		if (TiApplication.isUIThread()) {
			handleFinishLayout();
		} else {
			getMainHandler().sendEmptyMessage(MSG_FINISH_LAYOUT);
		}
		layoutStarted.set(false);
	}

	// TODO: Deprecated since Release 3.0.0
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Kroll.method @Deprecated
	public void updateLayout(Object params)
	{
		Log.w(TAG, "updateLayout() is deprecated.", Log.DEBUG_MODE);

		HashMap<String, Object> paramsMap;

		if (!(params instanceof HashMap)) {
			Log.e(TAG, "Argument for updateLayout must be a dictionary");
			return;
		}
		paramsMap = (HashMap) params;

		layoutStarted.set(true);
		if (TiApplication.isUIThread()) {
			handleUpdateLayout(paramsMap);
		} else {
			getMainHandler().obtainMessage(MSG_UPDATE_LAYOUT, paramsMap).sendToTarget();
		}
		layoutStarted.set(false);
	}

	private void handleFinishLayout()
	{
		if (view.iszIndexChanged()) {
			view.forceLayoutNativeView(true);
			view.setzIndexChanged(false);
		} else {
			view.forceLayoutNativeView(false);
		}
	}

	private void handleUpdateLayout(HashMap<String, Object> params)
	{
		for (String key : params.keySet()) {
			setPropertyAndFire(key, params.get(key));
		}
		handleFinishLayout();
	}

	// TODO: Deprecated since Release 3.0.0
	// This is used to check if the user has called startLayout(). We mainly use this to perform a check before running
	// deprecated behavior. (i.e. performing layout when a property has changed, and the user didn't call startLayout)
	@Deprecated
	public boolean isLayoutStarted()
	{
		return layoutStarted.get();
	}

	@Kroll.method
	public void hideKeyboard()
	{
		if (TiApplication.isUIThread()) {
			handleHideKeyboard();
		} else {
			getMainHandler().sendEmptyMessage(MSG_HIDE_KEYBOARD);
		}
	}

	protected void handleHideKeyboard()
	{
		TiUIView v = peekView();
		if (v != null) {
			View nv = v.getNativeView();
			if (nv != null) {
				TiUIHelper.showSoftKeyboard(nv, false);
			}
		}
	}
}


text:
#ifndef TouchGesture_DEFINED
#define TouchGesture_DEFINED

#include "include/core/SkMatrix.h"
#include "include/private/SkTDArray.h"

class TouchGesture {
public:
    TouchGesture();
    ~TouchGesture();

    void touchBegin(void* owner, float x, float y);
    void touchMoved(void* owner, float x, float y);
    void touchEnd(void* owner);
    void reset();
    void resetTouchState();

    bool isActive() { return fFlinger.isActive(); }
    void stop() { fFlinger.stop(); }
    bool isBeingTouched() { return kEmpty_State != fState; }
    bool isFling(SkPoint* dir);

    void startZoom();
    void updateZoom(float scale, float startX, float startY, float lastX, float lastY);
    void endZoom();

    const SkMatrix& localM();
    const SkMatrix& globalM() const { return fGlobalM; }

    void setTransLimit(const SkRect& contentRect, const SkRect& windowRect,
                       const SkMatrix& preTouchM);

private:
    enum State {
        kEmpty_State,
        kTranslate_State,
        kZoom_State,
    };

    struct Rec {
        void*   fOwner;
        float   fStartX, fStartY;
        float   fPrevX, fPrevY;
        float   fLastX, fLastY;
        float   fPrevT, fLastT;
    };
    SkTDArray<Rec> fTouches;

    State           fState;
    SkMatrix        fLocalM, fGlobalM, fPreTouchM;

    struct FlingState {
        FlingState() : fActive(false) {}

        bool isActive() const { return fActive; }
        void stop() { fActive = false; }

        void reset(float sx, float sy);
        bool evaluateMatrix(SkMatrix* matrix);

        void get(SkPoint* dir, SkScalar* speed) {
            *dir = fDirection;
            *speed = fSpeed0;
        }

    private:
        SkPoint     fDirection;
        SkScalar    fSpeed0;
        double      fTime0;
        bool        fActive;
    };
    FlingState      fFlinger;
    double          fLastUpMillis;
    SkPoint         fLastUpP;

    // The following rects are used to limit the translation so the content never leaves the window
    SkRect          fContentRect, fWindowRect;
    bool            fIsTransLimited = false;

    void limitTrans(); // here we only limit the translation with respect to globalM
    void flushLocalM();
    int findRec(void* owner) const;
    void appendNewRec(void* owner, float x, float y);
    float computePinch(const Rec&, const Rec&);
    float limitTotalZoom(float scale) const;
    bool handleDblTap(float, float);
};

#endif

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable disable

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Overlays.Rankings;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Catch;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Taiko;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneSpotlightsLayout : OsuTestScene
    {
        protected override bool UseOnlineAPI => true;

        [Cached]
        private readonly OverlayColourProvider overlayColour = new OverlayColourProvider(OverlayColourScheme.Green);

        public TestSceneSpotlightsLayout()
        {
            var ruleset = new Bindable<RulesetInfo>(new OsuRuleset().RulesetInfo);

            Add(new BasicScrollContainer
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.Both,
                Width = 0.8f,
                Child = new SpotlightsLayout
                {
                    Ruleset = { BindTarget = ruleset }
                }
            });

            AddStep("Osu ruleset", () => ruleset.Value = new OsuRuleset().RulesetInfo);
            AddStep("Mania ruleset", () => ruleset.Value = new ManiaRuleset().RulesetInfo);
            AddStep("Taiko ruleset", () => ruleset.Value = new TaikoRuleset().RulesetInfo);
            AddStep("Catch ruleset", () => ruleset.Value = new CatchRuleset().RulesetInfo);
        }
    }
}


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

<title>Propagations (MaltParser 1.8.1)</title>
<meta name="date" content="2014-11-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.maltparser.core.propagation

Class Propagations

java.lang.Object

org.maltparser.core.propagation.Propagations

public class Propagations
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

Propagations(PropagationSpecs specs,
                        DataFormatInstance dataFormatInstance,
                        SymbolTableHandler tableHandler)

Method Summary

Methods

Modifier and Type
Method and Description

java.util.ArrayList<Propagation>
getPropagations()

void
propagate(Edge e)

java.lang.String
toString()

Methods inherited from class java.lang.Object

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

Constructor Detail

Propagations

public Propagations(PropagationSpecs specs,
            DataFormatInstance dataFormatInstance,
            SymbolTableHandler tableHandler)
             throws MaltChainedException

Throws:

MaltChainedException

Method Detail

propagate

public void propagate(Edge e)
               throws MaltChainedException

Throws:

MaltChainedException

getPropagations

public java.util.ArrayList<Propagation> getPropagations()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright 2007-2014 Johan Hall, Jens Nilsson and Joakim Nivre.


text:
\n
static inline int efi_guidcmp (efi_guid_t left, efi_guid_t right)
static inline char * efi_guid_to_str(efi_guid_t *guid, char *out)
static inline efi_status_t efi_query_variable_store(u32 attributes, unsigned long size, bool nonblocking)
static inline int efi_range_is_wc(unsigned long start, unsigned long len)
static inline bool efi_enabled(int feature)
extern bool efi_is_table_address(unsigned long phys_addr)
; static inline bool efi_enabled(int feature)
static inline bool efi_capsule_pending(int *reset_type)
static inline bool efi_is_table_address(unsigned long phys_addr)
static inline void memrange_efi_to_native(u64 *addr, u64 *npages)
static inline void efivar_unregister(struct efivar_entry *var)
int efi_runtime_map_init(struct kobject *)
; int efi_get_runtime_map_size(void)
; int efi_get_runtime_map_desc_size(void)
; int efi_runtime_map_copy(void *buf, size_t bufsz)
; static inline int efi_runtime_map_init(struct kobject *kobj)
static inline int efi_get_runtime_map_size(void)
static inline int efi_get_runtime_map_desc_size(void)
static inline int efi_runtime_map_copy(void *buf, size_t bufsz)
\n
      4 void
      2 void *buf
      2 unsigned long phys_addr
      2 size_t bufsz
      2 int feature
      1 unsigned long start
      1 unsigned long size
      1 unsigned long len
      1 u64 *npages
      1 u64 *addr
      1 u32 attributes
      1 struct kobject *kobj
      1 struct kobject *
      1 struct efivar_entry *var
      1 int *reset_type
      1 efi_guid_t right
      1 efi_guid_t left
      1 efi_guid_t *guid
      1 char *out
      1 bool nonblocking


text:
This repository contains all Auth0 documentation content (including Quickstarts).

**Please review the [Contributing Guidelines](CONTRIBUTING.md) before sending a PR or opening an issue.**

* If you are looking for the application that *hosts* the Docs content, see [auth0-docs](https://github.com/auth0/auth0-docs).
* If you would like to modify the Management API v2 API docs, they are generated from the [api2](https://github.com/auth0/api2) repository.

Both of the above repositories require team access.

## Editing Docs Content

* You can edit Docs content by using the GitHub web editor and editing a file. This is best suited for typos and small changes.
* You can also pull down the `/docs` repo to your computer via Git and edit files in your local editor, before pushing a new branch (or a branch to your own fork of the project). You can then go to GitHub.com and start a PR. We will be able to review the changes in a Heroku test application prior to merging.
* Lastly, you can [run and test the docs site locally](https://github.com/auth0/auth0-docs/blob/master/README.md) (access available to Auth0 employees only). This option is best suited for repeat contributors or for complex contributions. You gain the benefit of locally testing and viewing your changed or added pages, navigation, and config, but you also gain the complexity of dealing with the local docs app, setting it up, and keeping it updated.

Regardless of which option you use, again, please review any relevant sections of the [Contributing Guidelines](CONTRIBUTING.md) before sending a PR.

## Issue Reporting

If you find a bug or inaccuracy in the documentation content, please report it in this repository's [issues](https://github.com/auth0/docs/issues) section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.

## Author

[Auth0](https://auth0.com)

## License

This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.


text:
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.Navigation;
using System.Windows.Shapes;

namespace CustomAnimation
{
  /// <summary>
  /// Interaction logic for PathOptionsControlView.xaml
  /// </summary>
  public partial class PathOptionsControlView : UserControl
  {
    public PathOptionsControlView()
    {
      InitializeComponent();
    }
  }
}


text:
license: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations

   under the License.
---

# PositionError

A `PositionError` objeto se pasa a la `geolocationError` devolución de llamada cuando se produce un error.

## Propiedades

*   **código**: uno de los códigos de error predefinido enumerados a continuación.

*   **mensaje**: mensaje de Error que describe los detalles del error encontrado.

## Constantes

*   `PositionError.PERMISSION_DENIED`
*   `PositionError.POSITION_UNAVAILABLE`
*   `PositionError.TIMEOUT`

## Descripción

El `PositionError` objeto se pasa a la `geolocationError` función de devolución de llamada cuando se produce un error con geolocalización.

### `PositionError.PERMISSION_DENIED`

Regresó cuando el usuario no permite su aplicación recuperar información de la posición. Esto depende de la plataforma.

### `PositionError.POSITION_UNAVAILABLE`

Regresó cuando el dispositivo es capaz de recuperar una posición. En general esto significa que el dispositivo no tiene ninguna conectividad de red o no puede obtener una solución vía satélite.

### `PositionError.TIMEOUT`

Cuando el dispositivo es capaz de recuperar una posición dentro del tiempo especificado en el `geolocationOptions` ' `timeout` propiedad. Cuando se utiliza con `geolocation.watchPosition` , este error se podría pasar a la `geolocationError` "callback" cada `timeout` milisegundos.


text:
using Synology.FileStation.Common.Results;

namespace Synology.FileStation.VirtualFolder.Results
{
    /// <summary>
    /// Virtual folder perm acl result.
    /// </summary>
    public interface IVirtualFolderPermAclResult : ITaskVirtualFolderPermAclResult
    {
    }
}


text:
#region copyright
// Copyright 2015 Habart Thierry
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace SimpleIdentityServer.Uma.Core.Policies
{
    public enum AuthorizationPolicyResultEnum
    {
        NotAuthorized,
        NeedInfo, // TODO : Not supported yet
        RequestSubmitted,
        Authorized
    }

    public class AuthorizationPolicyResult
    {
        public AuthorizationPolicyResultEnum Type { get; set; }
        public object ErrorDetails { get; set; }
    }
}


text:
require 'test_helper'

module DocumentationEditor
  class PagesControllerTest < ActionController::TestCase
    setup do
      @routes = Engine.routes
    end

    # test "the truth" do
    #   assert true
    # end
  end
end


text:
namespace blink {

namespace {

using ::testing::_;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::StrEq;
using ::testing::Truly;
using Checkpoint = ::testing::StrictMock<::testing::MockFunction<void(int)>>;

class MockThreadableLoaderClient : public ThreadableLoaderClient {
 public:
  static std::unique_ptr<MockThreadableLoaderClient> create() {
    return wrapUnique(new ::testing::StrictMock<MockThreadableLoaderClient>);
  }
  MOCK_METHOD2(didSendData, void(unsigned long long, unsigned long long));
  MOCK_METHOD3(didReceiveResponseMock,
               void(unsigned long,
                    const ResourceResponse&,
                    WebDataConsumerHandle*));
  void didReceiveResponse(unsigned long identifier,
                          const ResourceResponse& response,
                          std::unique_ptr<WebDataConsumerHandle> handle) {
    didReceiveResponseMock(identifier, response, handle.get());
  }
  MOCK_METHOD2(didReceiveData, void(const char*, unsigned));
  MOCK_METHOD2(didReceiveCachedMetadata, void(const char*, int));
  MOCK_METHOD2(didFinishLoading, void(unsigned long, double));
  MOCK_METHOD1(didFail, void(const ResourceError&));
  MOCK_METHOD1(didFailAccessControlCheck, void(const ResourceError&));
  MOCK_METHOD0(didFailRedirectCheck, void());
  MOCK_METHOD1(didReceiveResourceTiming, void(const ResourceTimingInfo&));
  MOCK_METHOD1(didDownloadData, void(int));

 protected:
  MockThreadableLoaderClient() = default;
};

bool isCancellation(const ResourceError& error) {
  return error.isCancellation();
}

bool isNotCancellation(const ResourceError& error) {
  return !error.isCancellation();
}

KURL successURL() {
  return KURL(KURL(), "http://example.com/success");
}
KURL errorURL() {
  return KURL(KURL(), "http://example.com/error");
}
KURL redirectURL() {
  return KURL(KURL(), "http://example.com/redirect");
}
KURL redirectLoopURL() {
  return KURL(KURL(), "http://example.com/loop");
}

enum ThreadableLoaderToTest {
  DocumentThreadableLoaderTest,
  WorkerThreadableLoaderTest,
  PerThreadHeapEnabledWorkerThreadableLoaderTest
};

class ThreadableLoaderTestHelper {
 public:
  virtual ~ThreadableLoaderTestHelper() {}

  virtual void createLoader(ThreadableLoaderClient*,
                            CrossOriginRequestPolicy) = 0;
  virtual void startLoader(const ResourceRequest&) = 0;
  virtual void cancelLoader() = 0;
  virtual void cancelAndClearLoader() = 0;
  virtual void clearLoader() = 0;
  virtual Checkpoint& checkpoint() = 0;
  virtual void callCheckpoint(int) = 0;
  virtual void onSetUp() = 0;
  virtual void onServeRequests() = 0;
  virtual void onTearDown() = 0;
};

class DocumentThreadableLoaderTestHelper : public ThreadableLoaderTestHelper {
 public:
  DocumentThreadableLoaderTestHelper()
      : m_dummyPageHolder(DummyPageHolder::create(IntSize(1, 1))) {}

  void createLoader(
      ThreadableLoaderClient* client,
      CrossOriginRequestPolicy crossOriginRequestPolicy) override {
    ThreadableLoaderOptions options;
    options.crossOriginRequestPolicy = crossOriginRequestPolicy;
    ResourceLoaderOptions resourceLoaderOptions;
    m_loader = DocumentThreadableLoader::create(document(), client, options,
                                                resourceLoaderOptions);
  }

  void startLoader(const ResourceRequest& request) override {
    m_loader->start(request);
  }

  void cancelLoader() override { m_loader->cancel(); }
  void cancelAndClearLoader() override {
    m_loader->cancel();
    m_loader = nullptr;
  }
  void clearLoader() override { m_loader = nullptr; }
  Checkpoint& checkpoint() override { return m_checkpoint; }
  void callCheckpoint(int n) override { m_checkpoint.Call(n); }

  void onSetUp() override {}

  void onServeRequests() override {}

  void onTearDown() override {
    if (m_loader) {
      m_loader->cancel();
      m_loader = nullptr;
    }
  }

 private:
  Document& document() { return m_dummyPageHolder->document(); }

  std::unique_ptr<DummyPageHolder> m_dummyPageHolder;
  Checkpoint m_checkpoint;
  Persistent<DocumentThreadableLoader> m_loader;
};

class WorkerThreadableLoaderTestHelper : public ThreadableLoaderTestHelper,
                                         public WorkerLoaderProxyProvider {
 public:
  explicit WorkerThreadableLoaderTestHelper(
      BlinkGC::ThreadHeapMode threadHeapMode)
      : m_dummyPageHolder(DummyPageHolder::create(IntSize(1, 1))),
        m_threadHeapMode(threadHeapMode) {}

  void createLoader(
      ThreadableLoaderClient* client,
      CrossOriginRequestPolicy crossOriginRequestPolicy) override {
    std::unique_ptr<WaitableEvent> completionEvent =
        makeUnique<WaitableEvent>();
    postTaskToWorkerGlobalScope(
        BLINK_FROM_HERE,
        createCrossThreadTask(
            &WorkerThreadableLoaderTestHelper::workerCreateLoader,
            crossThreadUnretained(this), crossThreadUnretained(client),
            crossThreadUnretained(completionEvent.get()),
            crossOriginRequestPolicy));
    completionEvent->wait();
  }

  void startLoader(const ResourceRequest& request) override {
    std::unique_ptr<WaitableEvent> completionEvent =
        makeUnique<WaitableEvent>();
    postTaskToWorkerGlobalScope(
        BLINK_FROM_HERE,
        createCrossThreadTask(
            &WorkerThreadableLoaderTestHelper::workerStartLoader,
            crossThreadUnretained(this),
            crossThreadUnretained(completionEvent.get()), request));
    completionEvent->wait();
  }

  // Must be called on the worker thread.
  void cancelLoader() override {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());
    m_loader->cancel();
  }

  void cancelAndClearLoader() override {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());
    m_loader->cancel();
    m_loader = nullptr;
  }

  // Must be called on the worker thread.
  void clearLoader() override {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());
    m_loader = nullptr;
  }

  Checkpoint& checkpoint() override { return m_checkpoint; }

  void callCheckpoint(int n) override {
    testing::runPendingTasks();

    std::unique_ptr<WaitableEvent> completionEvent =
        makeUnique<WaitableEvent>();
    postTaskToWorkerGlobalScope(
        BLINK_FROM_HERE,
        createCrossThreadTask(
            &WorkerThreadableLoaderTestHelper::workerCallCheckpoint,
            crossThreadUnretained(this),
            crossThreadUnretained(completionEvent.get()), n));
    completionEvent->wait();
  }

  void onSetUp() override {
    m_mockWorkerReportingProxy = makeUnique<MockWorkerReportingProxy>();
    m_securityOrigin = document().getSecurityOrigin();
    m_workerThread = wrapUnique(new WorkerThreadForTest(
        this, *m_mockWorkerReportingProxy, m_threadHeapMode));

    expectWorkerLifetimeReportingCalls();
    m_workerThread->startWithSourceCode(m_securityOrigin.get(),
                                        "//fake source code");
    m_workerThread->waitForInit();
  }

  void onServeRequests() override { testing::runPendingTasks(); }

  void onTearDown() override {
    postTaskToWorkerGlobalScope(
        BLINK_FROM_HERE,
        createCrossThreadTask(&WorkerThreadableLoaderTestHelper::clearLoader,
                              crossThreadUnretained(this)));
    WaitableEvent event;
    postTaskToWorkerGlobalScope(
        BLINK_FROM_HERE, createCrossThreadTask(&WaitableEvent::signal,
                                               crossThreadUnretained(&event)));
    event.wait();
    m_workerThread->terminateAndWait();

    // Needed to clean up the things on the main thread side and
    // avoid Resource leaks.
    testing::runPendingTasks();

    m_workerThread->workerLoaderProxy()->detachProvider(this);
  }

 private:
  Document& document() { return m_dummyPageHolder->document(); }

  void expectWorkerLifetimeReportingCalls() {
    EXPECT_CALL(*m_mockWorkerReportingProxy, didCreateWorkerGlobalScope(_))
        .Times(1);
    EXPECT_CALL(*m_mockWorkerReportingProxy, didEvaluateWorkerScript(true))
        .Times(1);
    EXPECT_CALL(*m_mockWorkerReportingProxy, willDestroyWorkerGlobalScope())
        .Times(1);
    EXPECT_CALL(*m_mockWorkerReportingProxy, didTerminateWorkerThread())
        .Times(1);
  }

  void workerCreateLoader(ThreadableLoaderClient* client,
                          WaitableEvent* event,
                          CrossOriginRequestPolicy crossOriginRequestPolicy) {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());

    ThreadableLoaderOptions options;
    options.crossOriginRequestPolicy = crossOriginRequestPolicy;
    ResourceLoaderOptions resourceLoaderOptions;

    // Ensure that WorkerThreadableLoader is created.
    // ThreadableLoader::create() determines whether it should create
    // a DocumentThreadableLoader or WorkerThreadableLoader based on
    // isWorkerGlobalScope().
    DCHECK(m_workerThread->globalScope()->isWorkerGlobalScope());

    m_loader = ThreadableLoader::create(*m_workerThread->globalScope(), client,
                                        options, resourceLoaderOptions);
    DCHECK(m_loader);
    event->signal();
  }

  void workerStartLoader(
      WaitableEvent* event,
      std::unique_ptr<CrossThreadResourceRequestData> requestData) {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());

    ResourceRequest request(requestData.get());
    m_loader->start(request);
    event->signal();
  }

  void workerCallCheckpoint(WaitableEvent* event, int n) {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());
    m_checkpoint.Call(n);
    event->signal();
  }

  // WorkerLoaderProxyProvider methods.
  void postTaskToLoader(const WebTraceLocation& location,
                        std::unique_ptr<ExecutionContextTask> task) override {
    DCHECK(m_workerThread);
    DCHECK(m_workerThread->isCurrentThread());
    document().postTask(location, std::move(task));
  }

  void postTaskToWorkerGlobalScope(
      const WebTraceLocation& location,
      std::unique_ptr<ExecutionContextTask> task) override {
    DCHECK(m_workerThread);
    m_workerThread->postTask(location, std::move(task));
  }

  RefPtr<SecurityOrigin> m_securityOrigin;
  std::unique_ptr<MockWorkerReportingProxy> m_mockWorkerReportingProxy;
  std::unique_ptr<WorkerThreadForTest> m_workerThread;

  std::unique_ptr<DummyPageHolder> m_dummyPageHolder;
  Checkpoint m_checkpoint;
  // |m_loader| must be touched only from the worker thread only.
  CrossThreadPersistent<ThreadableLoader> m_loader;
  const BlinkGC::ThreadHeapMode m_threadHeapMode;
};

class ThreadableLoaderTest
    : public ::testing::TestWithParam<ThreadableLoaderToTest> {
 public:
  ThreadableLoaderTest() {
    switch (GetParam()) {
      case DocumentThreadableLoaderTest:
        m_helper = wrapUnique(new DocumentThreadableLoaderTestHelper);
        break;
      case WorkerThreadableLoaderTest:
        m_helper = wrapUnique(
            new WorkerThreadableLoaderTestHelper(BlinkGC::MainThreadHeapMode));
        break;
      case PerThreadHeapEnabledWorkerThreadableLoaderTest:
        m_helper = wrapUnique(
            new WorkerThreadableLoaderTestHelper(BlinkGC::PerThreadHeapMode));
        break;
    }
  }

  void startLoader(const KURL& url) {
    ResourceRequest request(url);
    request.setRequestContext(WebURLRequest::RequestContextObject);
    m_helper->startLoader(request);
  }

  void cancelLoader() { m_helper->cancelLoader(); }
  void cancelAndClearLoader() { m_helper->cancelAndClearLoader(); }
  void clearLoader() { m_helper->clearLoader(); }
  Checkpoint& checkpoint() { return m_helper->checkpoint(); }
  void callCheckpoint(int n) { m_helper->callCheckpoint(n); }

  void serveRequests() {
    m_helper->onServeRequests();
    Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  }

  void createLoader(CrossOriginRequestPolicy crossOriginRequestPolicy =
                        AllowCrossOriginRequests) {
    m_helper->createLoader(client(), crossOriginRequestPolicy);
  }

  MockThreadableLoaderClient* client() const { return m_client.get(); }

 private:
  void SetUp() override {
    setUpSuccessURL();
    setUpErrorURL();
    setUpRedirectURL();
    setUpRedirectLoopURL();

    m_client = MockThreadableLoaderClient::create();
    m_helper->onSetUp();
  }

  void TearDown() override {
    m_helper->onTearDown();
    Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs();
    memoryCache()->evictResources();
    m_client.reset();
  }

  void setUpSuccessURL() {
    URLTestHelpers::registerMockedURLLoad(
        successURL(), "fox-null-terminated.html", "text/html");
  }

  void setUpErrorURL() {
    URLTestHelpers::registerMockedErrorURLLoad(errorURL());
  }

  void setUpRedirectURL() {
    KURL url = redirectURL();

    WebURLLoadTiming timing;
    timing.initialize();

    WebURLResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(301);
    response.setLoadTiming(timing);
    response.addHTTPHeaderField("Location", successURL().getString());
    response.addHTTPHeaderField("Access-Control-Allow-Origin", "null");

    URLTestHelpers::registerMockedURLLoadWithCustomResponse(
        url, "fox-null-terminated.html", "", response);
  }

  void setUpRedirectLoopURL() {
    KURL url = redirectLoopURL();

    WebURLLoadTiming timing;
    timing.initialize();

    WebURLResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(301);
    response.setLoadTiming(timing);
    response.addHTTPHeaderField("Location", redirectLoopURL().getString());
    response.addHTTPHeaderField("Access-Control-Allow-Origin", "null");

    URLTestHelpers::registerMockedURLLoadWithCustomResponse(
        url, "fox-null-terminated.html", "", response);
  }

  std::unique_ptr<MockThreadableLoaderClient> m_client;
  std::unique_ptr<ThreadableLoaderTestHelper> m_helper;
};

INSTANTIATE_TEST_CASE_P(Document,
                        ThreadableLoaderTest,
                        ::testing::Values(DocumentThreadableLoaderTest));

INSTANTIATE_TEST_CASE_P(Worker,
                        ThreadableLoaderTest,
                        ::testing::Values(WorkerThreadableLoaderTest));

INSTANTIATE_TEST_CASE_P(
    PerThreadHeapEnabledWorker,
    ThreadableLoaderTest,
    ::testing::Values(PerThreadHeapEnabledWorkerThreadableLoaderTest));

TEST_P(ThreadableLoaderTest, StartAndStop) {}

TEST_P(ThreadableLoaderTest, CancelAfterStart) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));
  EXPECT_CALL(checkpoint(), Call(3));

  startLoader(successURL());
  callCheckpoint(2);
  callCheckpoint(3);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelAndClearAfterStart) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2))
      .WillOnce(
          InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelAndClearLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));
  EXPECT_CALL(checkpoint(), Call(3));

  startLoader(successURL());
  callCheckpoint(2);
  callCheckpoint(3);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidReceiveResponse) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelAndClearInDidReceiveResponse) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _))
      .WillOnce(
          InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelAndClearLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidReceiveData) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(_, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelAndClearInDidReceiveData) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(_, _))
      .WillOnce(
          InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelAndClearLoader));
  EXPECT_CALL(*client(), didFail(Truly(isCancellation)));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, DidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4));
  // We expect didReceiveResourceTiming() calls in DocumentThreadableLoader;
  // it's used to connect DocumentThreadableLoader to WorkerThreadableLoader,
  // not to ThreadableLoaderClient.
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(_, _));
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInDidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(_, _));
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, DidFail) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didFail(Truly(isNotCancellation)));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidFail) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didFail(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInDidFail) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didFail(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, DidFailInStart) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(DenyCrossOriginRequests);
  callCheckpoint(1);

  EXPECT_CALL(
      *client(),
      didFail(ResourceError(errorDomainBlinkInternal, 0, errorURL().getString(),
                            "Cross origin requests are not supported.")));
  EXPECT_CALL(checkpoint(), Call(2));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidFailInStart) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(DenyCrossOriginRequests);
  callCheckpoint(1);

  EXPECT_CALL(*client(), didFail(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));
  EXPECT_CALL(checkpoint(), Call(2));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInDidFailInStart) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(DenyCrossOriginRequests);
  callCheckpoint(1);

  EXPECT_CALL(*client(), didFail(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));
  EXPECT_CALL(checkpoint(), Call(2));

  startLoader(errorURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, DidFailAccessControlCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(
      *client(),
      didFailAccessControlCheck(ResourceError(
          errorDomainBlinkInternal, 0, successURL().getString(),
          "No 'Access-Control-Allow-Origin' header is present on the requested "
          "resource. Origin 'null' is therefore not allowed access.")));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidFailAccessControlCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didFailAccessControlCheck(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInDidFailAccessControlCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didFailAccessControlCheck(_))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));

  startLoader(successURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, RedirectDidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4));
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _));

  startLoader(redirectURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInRedirectDidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4));
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));

  startLoader(redirectURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInRedirectDidFinishLoading) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader();
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didReceiveResponseMock(_, _, _));
  EXPECT_CALL(*client(), didReceiveData(StrEq("fox"), 4));
  EXPECT_CALL(*client(), didReceiveResourceTiming(_));
  EXPECT_CALL(*client(), didFinishLoading(_, _))
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));

  startLoader(redirectURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, DidFailRedirectCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didFailRedirectCheck());

  startLoader(redirectLoopURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, CancelInDidFailRedirectCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didFailRedirectCheck())
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::cancelLoader));

  startLoader(redirectLoopURL());
  callCheckpoint(2);
  serveRequests();
}

TEST_P(ThreadableLoaderTest, ClearInDidFailRedirectCheck) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(checkpoint(), Call(2));
  EXPECT_CALL(*client(), didFailRedirectCheck())
      .WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::clearLoader));

  startLoader(redirectLoopURL());
  callCheckpoint(2);
  serveRequests();
}

// This test case checks blink doesn't crash even when the response arrives
// synchronously.
TEST_P(ThreadableLoaderTest, GetResponseSynchronously) {
  InSequence s;
  EXPECT_CALL(checkpoint(), Call(1));
  createLoader(UseAccessControl);
  callCheckpoint(1);

  EXPECT_CALL(*client(), didFailAccessControlCheck(_));
  EXPECT_CALL(checkpoint(), Call(2));

  // Currently didFailAccessControlCheck is dispatched synchronously. This
  // test is not saying that didFailAccessControlCheck should be dispatched
  // synchronously, but is saying that even when a response is served
  // synchronously it should not lead to a crash.
  startLoader(KURL(KURL(), "about:blank"));
  callCheckpoint(2);
}

}  // namespace

}  // namespace blink


text:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>{{ site.name }}</title>

<meta name="description" content="{{ page.description }}">

<!-- font -->
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>

<!-- stylesheet -->
<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
<link rel="stylesheet" href="{{ "/css/highlight.css" | prepend: site.baseurl }}">

<!-- font-awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">

<!-- Meta for tags -->

<!-- Analytics -->


text:
@interface HYCameraIrisHollowOpenTransitionAnimation : HYSystemTransitionAnimation

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/TimeLayout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            >
            <TextView
                android:id="@+id/TimeText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                    android:text="000"
                />
            <SeekBar
                android:id="@+id/TimeSeek"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                    android:max="50"
                />
        </LinearLayout>

        <ToggleButton
            android:id="@+id/EyeLightToggle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/TimeLayout"
            android:layout_centerHorizontal="true" />

        <TableLayout
            android:id="@+id/UpperLayout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/EyeLightToggle" >

            <TableRow
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >

                <SeekBar
                    android:id="@+id/ArmLeftSeek"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:max="255"
                    />

                <SeekBar
                    android:id="@+id/ArmRightSeek"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:max="255"
                    />
            </TableRow>

            <TableRow
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/ArmLeftValue"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center_horizontal"
                    android:text="0" />

                <TextView
                    android:id="@+id/ArmRightValue"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center_horizontal"
                    android:text="0" />
            </TableRow>
        </TableLayout>

        <LinearLayout
            android:id="@+id/BottomLayout2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" >

            <RadioGroup
                android:id="@+id/motorDirLeft"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true" >

                <RadioButton
                    android:id="@+id/stopItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="Stop" />

                <RadioButton
                    android:id="@+id/forwardItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Forward" />

                <RadioButton
                    android:id="@+id/reverseItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Reverse" />
            </RadioGroup>

            <RadioGroup
                android:id="@+id/motorDirRight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true" >

                <RadioButton
                    android:id="@+id/stopItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="Stop" />

                <RadioButton
                    android:id="@+id/forwardItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Forward" />

                <RadioButton
                    android:id="@+id/reverseItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Reverse" />
            </RadioGroup>
        </LinearLayout>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/BottomLayout2"
            android:layout_below="@+id/UpperLayout"
            android:src="@drawable/android_logo" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" >

        <Button
            android:id="@+id/button0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancel" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ok" />
    </LinearLayout>

</LinearLayout>


text:
package app.color.activity;

import android.app.Activity;
import android.os.Bundle;
import app.color.service.OverlayService;

public class OverlayActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OverlayService.start(this, true);
    finish();
  }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>All Classes (Java IPv6 Library 0.15 API)</title>
<meta name="date" content="2013-08-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

IPv6Address

IPv6AddressHelpers

IPv6AddressPool

IPv6AddressRange

IPv6Network

IPv6NetworkHelpers

IPv6NetworkMask


text:
require "dry/inflector"

module Fog
  module Brightbox
    module ModelHelper
      def resource_name
        inflector.underscore(inflector.demodulize(self.class))
      end

      def collection_name
        inflector.pluralize(resource_name)
      end

      private

      def inflector
        @inflector ||= Dry::Inflector.new
      end
    end
  end
end


text:
package org.eknet.publet.web.filter

import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import javax.servlet._
import org.eknet.publet.web.{PageWriter, PubletRequestWrapper}
import org.eknet.publet.vfs.ContentType
import org.eknet.publet.Publet
import com.google.inject.Singleton

/** Servlet that processes the resource using the engine
 * as specified with `a=` http request parameter or the
 * default engine.
 *
 * @author Eike Kettner
 * @since 05.04.12 15:03
 *
 */
@Singleton
class PubletFilter(publet: Publet) extends Filter with PageWriter with PubletRequestWrapper {

  def init(filterConfig: FilterConfig) {}

  def destroy() {}

  def doFilter(req: ServletRequest, resp: ServletResponse, chain: FilterChain) {
    req.param("a") match {
      case Some(engine) => processEngine(req, resp, engine)
      case _ => processDefault(req, resp)
    }
  }

  def processEngine(req: HttpServletRequest, resp: HttpServletResponse, engine: String) {
    val engineId = Symbol(engine)
    val path = req.applicationPath

    val targetType = path.name.targetType
    val someEngine = Some(publet.engineManager.getEngine(engineId).getOrElse(sys.error("No engine '"+engineId+"' available")))
    val html = publet.process(path, targetType, someEngine)
    writePage(html, req, resp)
  }

  def processDefault(req: HttpServletRequest, resp: HttpServletResponse) {
    val path = req.applicationPath

    val tt = if (path.name.targetType == ContentType.unknown) ContentType.html else path.name.targetType
    val html = publet.process(path, tt)
    writePage(html, req, resp)
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<migration name="Add indicators for plant analysis">
  <item-creation item="indicators#germination_rate" datatype="measure" unit="percent"/>
  <item-creation item="indicators#species_purity" datatype="measure" unit="percent"/>
  <item-change item="analysis_natures#plant_analysis" items="ready_to_harvest, fresh_mass, healthy, plant_growth_level, plant_life_state, plant_reproduction_state, plants_interval, plants_count, germination_rate, species_purity"/>
</migration>


text:
package org.eclipse.ui.examples.templateeditor.editors;

import org.eclipse.jface.text.rules.IWhitespaceDetector;

public class XMLWhitespaceDetector implements IWhitespaceDetector {

	public boolean isWhitespace(char c) {
		return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
	}
}


text:
<?php

namespace Synapse\Cmf\Bundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class SynapseCmfExtension extends Extension implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        // publish into parameters to allow listening
        $container->setParameter('synapse.media_store.physical_path', $config['media']['store']['physical_path']);
        $container->setParameter('synapse.media_store.web_path', $config['media']['store']['web_path']);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        // register components into memory
        if (!empty($config['components'])) {
            $componentData = array();
            foreach ($config['components'] as $name => $data) {
                if (empty($data)) {
                    continue;
                }
                $componentData[] = array(
                    'id' => $name,
                    'name' => $name,
                    'controller' => $data['controller'],
                    'template_path' => $data['template_path'],
                    'form_type' => $data['form'],
                );
            }
            $container->getDefinition('synapse.component_type.in_memory_loader')
                ->addMethodCall('registerData', array($componentData))
            ;
            $container->setParameter('synapse.component_types', array_keys($config['components']));
        }

        // register content types into memory
        if (!empty($config['content_types'])) {
            $contentTypeData = array();
            $contentTypeNames = array();
            foreach ($config['content_types'] as $class => $data) {
                $contentTypeData[] = array(
                    'id' => $data['alias'],
                    'name' => $data['alias'],
                    'contentClass' => $class,
                    'contentProvider' => new Reference($data['provider']),
                );
                $contentTypeNames[] = $data['alias'];
            }
            $container->getDefinition('synapse.content_type.in_memory_loader')
                ->addMethodCall('registerData', array($contentTypeData))
            ;
            $container->setParameter('synapse.content_types', $contentTypeNames);
        }

        // forms enabled ?
        if (!empty($config['forms']['enabled'])) {
            $loader->load('services/forms.xml');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $container->getParameterBag()->remove('synapse.component_types');
        $container->getParameterBag()->remove('synapse.content_types');
    }
}


text:
export default {
    tag: 'my_tag',
    askForConfirmation: 'Do you agree with our terms?',
    agreeText: 'Yes, I do',
    declineText: 'No, I don\'t',
    notifyAgreed: 'Nice, you are good to go',
    notifyDeclined: 'Maybe next time',
    greeting: (userName, botName) => `Welcome ${userName}. Please talk to @${botName} to have your photos posted on the screen` //eslint-disable-line
};


text:
<?php

namespace PushoverLib\Api;

/**
 * Subscription Migrate Api
 *
 * @package PushoverLib
 * @license MIT License
 */
class SubscriptionMigrate extends AbstractApi implements ApiInterface
{
    /** @inherit */
    protected $method = self::METHOD_POST;

    /** @inherit */
    protected $parameters = [
        'subscription',
        'device_name',
        'sound',
    ];

    /**
     * @inherit
     */
    public function getResource() {
        return 'subscriptions/migrate';
    }
}


text:
//
// mdsclient - friendly interface to CDSA MDS API
//
#include <security_cdsa_client/mdsclient.h>

namespace Security {
namespace CssmClient {

//
// DLAccess gets a virtual destructor just in case
//
DLAccess::~DLAccess()
{ }

//
// Basic Record objects (abstract)
//
Record::Record(const char * const * names)
	: CssmAutoData(Allocator::standard(Allocator::sensitive))
{
	addAttributes(names);
}

void Record::addAttributes(const char * const * name)
{
	if (name)
		while (*name)
			mAttributes.add(CssmDbAttributeInfo(*name++));
}

Record::~Record()
{ }

//
// Tables and their components (non-template common features)
//
TableBase::TableBase(DLAccess &source, CSSM_DB_RECORDTYPE type, bool getData /* = true */)
	: database(source), mRecordType(type), mGetData(getData)
{
}

TableBase::Handle::~Handle()
{
	if (query)
		mAccess->dlAbortQuery(query);
}

TableBase::Uid::~Uid()
{
	if (uid)
		mAccess->dlFreeUniqueId(uid);
}

TableBase::Iterator::Iterator(DLAccess *ac, CSSM_HANDLE query,
		CSSM_DB_UNIQUE_RECORD *id, Record *record, bool getData)
	: mAccess(ac), mQuery(new Handle(ac, query)),
	  mUid(new Uid(ac, id)), mRecord(record), mGetData(getData)
{ }

void TableBase::Iterator::advance(Record *fill)
{
	RefPointer<Record> newRecord = fill;	// hold it safely
	CSSM_DB_UNIQUE_RECORD *id;
	CssmAutoData data(mAccess->allocator());
	if (mAccess->dlGetNext(mQuery->query, newRecord->attributes(),
		mGetData ? &data.get() : NULL, id)) {
		if (mGetData)
			newRecord->recordData() = data;
		mUid = new Uid(mAccess, id);
		mRecord = newRecord;
	} else {
		mQuery->query = CSSM_INVALID_HANDLE; // was automatically aborted
		// release all iterator resources and make me == end()
		mQuery = NULL;
		mUid = NULL;
		mRecord = NULL;
	}
}

uint32 TableBase::erase(const CSSM_QUERY &query)
{
	CSSM_DB_UNIQUE_RECORD *id;
	CssmDbRecordAttributeData noAttributes;
	CSSM_HANDLE handle = database.dlGetFirst(query, noAttributes, NULL, id);
	if (handle == CSSM_INVALID_HANDLE)
		return 0;   // no match, nothing erased
	uint32 count = 0;
	do {
		database.dlDeleteRecord(id);
		count++;
		database.dlFreeUniqueId(id);
	} while (database.dlGetNext(handle, noAttributes, NULL, id));
	return count;
}

uint32 TableBase::erase(const Query &query)
{
	return erase(query.cssmQuery());
}

} // end namespace CssmClient
} // end namespace Security


text:
package org.activiti.engine.impl.cmd;

import java.io.Serializable;

import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.task.Event;

/**

 */
public class GetTaskEventCmd implements Command<Event>, Serializable {

  private static final long serialVersionUID = 1L;
  protected String eventId;

  public GetTaskEventCmd(String eventId) {
    this.eventId = eventId;

    if (eventId == null) {
      throw new ActivitiIllegalArgumentException("eventId is null");
    }
  }

  public Event execute(CommandContext commandContext) {
    return commandContext.getCommentEntityManager().findEvent(eventId);
  }
}


text:
require File.dirname(__FILE__) + '/../test_helper.rb'

module SessionTest
  module KlassTest
    class ConfigTest < ActiveSupport::TestCase
      def test_authenticate_with
        UserSession.authenticate_with = Employee
        assert_equal "Employee", UserSession.klass_name
        assert_equal Employee, UserSession.klass

        UserSession.authenticate_with User
        assert_equal "User", UserSession.klass_name
        assert_equal User, UserSession.klass
      end

      def test_klass
        assert_equal User, UserSession.klass
      end

      def test_klass_name
        assert_equal "User", UserSession.klass_name
      end
    end

    class InstanceMethodsTest < ActiveSupport::TestCase
      def test_record_method
        ben = users(:ben)
        set_session_for(ben)
        session = UserSession.find
        assert_equal ben, session.record
        assert_equal ben, session.user
      end
    end
  end
end


text:
package org.jetbrains.plugins.scala
package project.template

import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider
import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.openapi.module.{Module, ModuleType, ModuleTypeId}
import com.intellij.openapi.roots.ui.configuration.FacetsProvider
import org.jetbrains.plugins.scala.project._
import org.jetbrains.plugins.scala.icons.Icons

/**
 * @author Pavel Fatin
 */
class ScalaSupportProvider extends FrameworkSupportInModuleProvider {
  override def getIcon = Icons.SCALA_SMALL_LOGO

  override def getFrameworkType = ScalaFrameworkType.Instance

  override def isEnabledForModuleType(moduleType: ModuleType[_ <: ModuleBuilder]) = {
    val id = moduleType.getId
    id == ModuleTypeId.JAVA_MODULE || id == "PLUGIN_MODULE" // PluginModuleType.getInstance.getId
  }

  override def isSupportAlreadyAdded(module: Module, facetsProvider: FacetsProvider) = module.hasScala

  override def createConfigurable(model: FrameworkSupportModel) = new ScalaSupportConfigurable()
}


text:
(function(root) {
	'use strict';

	var Node	= require('./node');

	var Statement	= Node.extend({ type: 'Statement', abstract: true }),
		Expression	= Statement.extend({ type: 'Expression', abstract: true });

	Expression.extend({ type: 'Assignable', abstract: true }),
	Expression.extend({ type: 'Operator', abstract: true });

})();


text:
/**
 * Author:  Davide Alocci
 * Version: 0.0.1
 */

import Node from '../../dataStructure/GraphNode';
import Anomericity from '../dictionary/Anomericity';
import Isomer from '../dictionary/Isomer';
import RingType from '../dictionary/RingType';
import MonosaccharideType from '../../../views/glycomics/dictionary/MonosaccharideType';

export default class Monosaccharide extends Node{

    constructor(id,monosaccharideType,anomericity,isomer,ringType){
        super(id);

        if(monosaccharideType instanceof MonosaccharideType){
            this._monosaccharideType = monosaccharideType;
        } else if(typeof monosaccharideType == 'undefined') {
            this._monosaccharideType = MonosaccharideType.UNDEFINED;
        } else{
            throw 'Please use the MonosaccharideType class and forget about string. Extend the enum if you need a specific value';
        }

        if(anomericity instanceof Anomericity){
            this._anomericity = anomericity;
        } else if(typeof anomericity == 'undefined') {
            this._anomericity = Anomericity.UNDEFINED;
        } else {
            throw 'Please use the Anomericity class and forget about string. Extend the enum if you need a specific value';
        }

        if(isomer instanceof Isomer){
            this._isomer = isomer;
        } else if(typeof isomer == 'undefined') {
            this._isomer = Isomer.UNDEFINED;
        } else {
            throw 'Please use the Isomer class and forget about string. Extend the enum if you need a specific value';
        }

        if(ringType instanceof RingType){
            this._ringType = ringType;
        } else if(typeof ringType == 'undefined') {
            this._ringType = RingType.UNDEFINED;
        } else{
            throw 'Please use the RingType class and forget about string. Extend the enum if you need a specific value';
        }

    }

    get ringType(){
        return this._ringType;
    }

    get monosaccharideType(){
        return this._monosaccharideType;
    }

    get isomer(){
        return this._isomer;
    }

    get anomericity(){
        return this._anomericity;
    }

    set ringType(ringType){
        if(ringType instanceof RingType){
            this._ringType = ringType;
        } else{
            throw 'Please use the RingType class and forget about string. Extend the enum if you need a specific value';
        }
    }

    set monosaccharideType(monosaccharideType){
        if(monosaccharideType instanceof MonosaccharideType){
            this._monosaccharideType = monosaccharideType;
        } else{
            throw 'Please use the MonosaccharideType class and forget about string. Extend the enum if you need a specific value';
        }
    }

    set isomer(isomer){
        if(isomer instanceof Isomer){
            this._isomer = isomer;
        } else {
            throw 'Please use the Isomer class and forget about string. Extend the enum if you need a specific value';
        }
    }

    set anomericity(anomericity){
        if(anomericity instanceof Anomericity){
            this._anomericity = anomericity;
        } else {
            throw 'Please use the Anomericity class and forget about string. Extend the enum if you need a specific value';
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. fl. 17:596. 1939

#### Original name
null

### Remarks
null