text:
package com.github.flowersinthesand.spheres.portal;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.flowersinthesand.spheres.Action;
import com.github.flowersinthesand.spheres.Actions;
import com.github.flowersinthesand.spheres.ConcurrentActions;
import com.github.flowersinthesand.spheres.SerializableAction;
import com.github.flowersinthesand.spheres.SessionBaseSupport;
import com.github.flowersinthesand.spheres.Socket;
import com.github.flowersinthesand.spheres.VoidAction;

public class DefaultSession extends SessionBaseSupport implements Session {

	private static ObjectMapper mapper = new ObjectMapper();

	private ConcurrentMap<String, ActionsHolder<?>> holders = new ConcurrentHashMap<>();
	private ConcurrentMap<String, Action<Object>> replies = new ConcurrentHashMap<>();

	public DefaultSession(Socket socket) {
		super(socket);

		final Actions<Void> closeActions = new ConcurrentActions<Void>(new Actions.Options().once(true).memory(true));
		holders.put("close", new ActionsHolder<>(Void.class, closeActions));

		socket.closeAction(new VoidAction() {
			@Override
			public void on() {
				closeActions.fire();
			}
		});
		socket.textAction(new Action<String>() {
			@Override
			public void on(String text) {
				Map<String, Object> m;
				try {
					m = mapper.readValue(text, new TypeReference<Map<String, Object>>() {});
				} catch (IOException e) {
					throw new RuntimeException(e);
				}

				@SuppressWarnings("unchecked")
				ActionsHolder<Object> holder = (ActionsHolder<Object>) holders.get((String) m.get("type"));
				if (holder != null) {
					Object data;
					if (Reply.class == holder.dataType.getRawClass()) {
						data = new SimpleReply(m, holder.dataType.containedType(0));
					} else {
						data = mapper.convertValue(m.get("data"), holder.dataType);
					}
					holder.actions.fire(data);
				}
			}
		});

		on("reply", new Action<Map<String, Object>>() {
			@Override
			public void on(Map<String, Object> data) {
				String eventId = (String) data.get("id");
				Object response = data.get("data");

				Action<Object> reply = replies.remove(eventId);
				if (reply != null) {
					reply.on(mapper.convertValue(response, mapper.constructType(findRequiredDataType(reply.getClass()))));
				}
			}
		});
	}

	private class SimpleReply implements Reply<Object> {
		private AtomicBoolean sent = new AtomicBoolean();
		private Map<String, Object> m;
		private Object data;

		public SimpleReply(Map<String, Object> m, JavaType type) {
			this.m = m;
			data = mapper.convertValue(m.get("data"), type);
		}

		@Override
		public Object data() {
			return data;
		}

		@Override
		public void done() {
			done(null);
		}

		@Override
		public void done(Object value) {
			sendReply(value, false);
		}

		@Override
		public void fail() {
			fail(null);
		}

		@Override
		public void fail(Object value) {
			sendReply(value, true);
		}

		private void sendReply(Object value, boolean exception) {
			if (sent.compareAndSet(false, true)) {
				Map<String, Object> result = new LinkedHashMap<String, Object>();
				result.put("id", m.get("id"));
				result.put("data", value);
				result.put("exception", exception);
				DefaultSession.this.send("reply", result);
			} else {
				throw new IllegalStateException("The reply for the event [" + m + "] is already sent");
			}
		}
	}

	@Override
	public String id() {
		return socket.id();
	}

	@Override
	public URI uri() {
		return socket.uri();
	}

	@Override
	public Map<String, List<String>> params() {
		return socket.params();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Session on(String event, Action<?> action) {
		ActionsHolder<?> holder = holders.get(event);
		if (holder == null) {
			Type type = findRequiredDataType(action.getClass());
			ActionsHolder<?> value = new ActionsHolder<>(type, new ConcurrentActions<>(new Actions.Options()));
			holder = holders.putIfAbsent(event, value);
			if (holder == null) {
				holder = value;
			}
		}
		holder.actions.add((Action) action);
		return this;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Session off(String event, Action<?> action) {
		ActionsHolder<?> holder = holders.get(event);
		if (holder != null) {
			// To delete the given action and its proxy added by once
			holder.actions.remove(new ActionProxy(action));
		}
		return this;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Session once(final String event, final Action<?> action) {
		return on(event, new ActionProxy(action) {
			@Override
			public void on(Object object) {
				off(event, this);
				super.on(object);
			}
		});
	}

	private Type findRequiredDataType(Class<?> clazz) {
		for (Type genericInterface : clazz.getGenericInterfaces()) {
			if (genericInterface instanceof ParameterizedType) {
				ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
				Type rawType = parameterizedType.getRawType();
				if (rawType == Action.class || rawType == SerializableAction.class) {
					return parameterizedType.getActualTypeArguments()[0];
				}
			}
		}

		Class<?> superClass = clazz.getSuperclass();
		return superClass != null ? findRequiredDataType(superClass) : null;
	}

	@Override
	public Set<String> tags() {
		return socket.tags();
	}

	@Override
	public Session tag(String... name) {
		socket.tags().addAll(Arrays.asList(name));
		return this;
	}

	@Override
	public Session untag(String... name) {
		socket.tags().removeAll(Arrays.asList(name));
		return this;
	}

	@Override
	public Session send(String event) {
		return send(event, null);
	}

	@Override
	public Session send(String event, Object data) {
		return send(event, data, null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Session send(String event, Object data, Action<?> reply) {
		String eventId = UUID.randomUUID().toString();
		Map<String, Object> message = new LinkedHashMap<String, Object>();

		message.put("id", eventId);
		message.put("type", event);
		message.put("data", data);
		message.put("reply", reply != null);

		String text;
		try {
			text = mapper.writeValueAsString(message);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		socket.send(text);
		if (reply != null) {
			replies.put(eventId, (Action<Object>) reply);
		}

		return this;
	}

	@Override
	public void close() {
		socket.close();
	}

	private static class ActionsHolder<T> {
		JavaType dataType;
		Actions<T> actions;

		public ActionsHolder(Type dataType, Actions<T> actions) {
			this.dataType = mapper.constructType(dataType);
			this.actions = actions;
		}
	}

	private static class ActionProxy<T> implements Action<T> {

		private Action<T> action;

		public ActionProxy(Action<T> action) {
			this.action = action;
		}

		@Override
		public void on(T object) {
			action.on(object);
		}

		@Override
		public int hashCode() {
			return action.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (obj instanceof ActionProxy) {
				obj = ((ActionProxy<?>) obj).action;
			}
			return action.equals(obj);
		}

		@Override
		public String toString() {
			return "Proxy for " + action.toString();
		}

	}

}


text:
sap.ui.define([
	"sap/ui/integration/editor/fields/viz/VizBase",
	"sap/m/Select",
	"sap/ui/core/ListItem",
	"sap/ui/model/json/JSONModel",
	"sap/ui/core/IconPool",
	"sap/base/util/merge",
	"sap/ui/core/Core",
	"sap/base/util/deepClone"
], function (
	VizBase, Select, ListItem, JSONModel, IconPool, merge, Core, deepClone
) {
	"use strict";

	var oResourceBundle = Core.getLibraryResourceBundle("sap.ui.integration"),
		aDefaultIcons;

	/**
	 * @class
	 * @extends sap.ui.integration.editor.fields.viz.VizBase
	 * @alias sap.ui.integration.editor.fields.viz.IconSelect
	 * @author SAP SE
	 * @since 1.84.0
	 * @version ${version}
	 * @private
	 * @experimental since 1.84.0
	 * @ui5-restricted
	 */
	var IconSelect = VizBase.extend("sap.ui.integration.editor.fields.viz.IconSelect", {
		metadata: {
			library: "sap.ui.integration",
			properties: {
				value: {
					type: "string",
					defaultValue: "sap-icon://accept"
				},
				allowFile: {
					type: "boolean",
					defaultValue: true
				},
				allowNone: {
					type: "boolean",
					defaultValue: true
				}
			}
		},
		renderer: {
			apiVersion: 2
		}
	});

	IconSelect.prototype._initIconModel = function () {
		var aIconNames = IconPool.getIconNames();
		aIconNames = aIconNames.sort(function (a, b) {
			return a.toLowerCase().localeCompare(b.toLowerCase());
		});
		var aIcons = [];
		if (!aDefaultIcons) {
			aIconNames.filter(function (s) {
				var text = IconPool.getIconInfo(s).text || ("-" + s).replace(/-(.)/ig, function (sMatch, sChar) {
					return " " + sChar.toUpperCase();
				}).substring(1);
				aIcons.push({
					icon: "sap-icon://" + s,
					key: "sap-icon://" + s,
					text: text,
					tooltip: text,
					enabled: true
				});
			});
			aDefaultIcons = deepClone(aIcons, 500);
		} else {
			aIcons = deepClone(aDefaultIcons, 500);
		}
		aIcons = [{
			icon: "",
			text: oResourceBundle.getText("EDITOR_ICON_NONE"),
			tooltip: "",
			key: "",
			enabled: true
		}, {
			icon: "sap-icon://upload",
			text: oResourceBundle.getText("EDITOR_ICON_CHOOSE"),
			tooltip: "",
			key: "file",
			enabled: true
		}, {
			icon: "sap-icon://download",
			text: oResourceBundle.getText("EDITOR_ICON_SELECTED"),
			tooltip: "",
			key: "selected",
			enabled: false
		}].concat(aIcons);
		this._oIconModel = new JSONModel(aIcons);
		this._oIconModel.setSizeLimit(aIcons.length);
	};

	IconSelect.prototype.onInit = function () {
		if (oResourceBundle && oResourceBundle.sLocale !== Core.getConfiguration().getLanguage()) {
			oResourceBundle = Core.getLibraryResourceBundle("sap.ui.integration");
		}
		if (!this._oIconModel) {
			this._initIconModel();
		}
		var oItem = new ListItem({
			icon: "{iconlist>icon}",
			text: "{iconlist>text}",
			tooltip: "{iconlist>tooltip}",
			key: "{iconlist>key}",
			enabled: "{iconlist>enabled}"
		});

		this._oFileUpload = document.createElement("INPUT");
		this._oFileUpload.type = "file";
		this._oFileUpload.accept = ".png,.jpg,.jpeg,.svg";
		this._boundFileUploadChange = this._fileUploadChange.bind(this);
		this._oFileUpload.addEventListener("change", this._boundFileUploadChange);

		this._oControl = new Select({
			width: "100%",
			items: {
				path: "iconlist>/",
				template: oItem
			},
			change: function (oEvent) {
				var oSelect = oEvent.getSource(),
					sSelectedKey = oEvent.getSource().getSelectedKey();
				if (sSelectedKey === "file") {
					oSelect._customImage = null;
					//open file upload
					this._oFileUpload.click();
					this._boundFocusBack = this._focusBack.bind(this);
					oSelect.getDomRef("hiddenSelect").addEventListener("focus", this._boundFocusBack);
				} else {
					this.setValue(sSelectedKey);
				}
			}.bind(this)
		});
		this._oControl.setModel(this._oIconModel, "iconlist");

		//add style class and height on open
		var fnOpen = this._oControl.open;
		this._oControl.open = function () {
			fnOpen && fnOpen.apply(this, arguments);
			this.getPicker().addStyleClass("sapUiIntegrationIconSelectList");
			this.getPicker().setContentHeight("400px");
		};

		//show file image before the label
		this._oControl.addDelegate({
			onAfterRendering: function () {
				var oIconDomRef = this._oControl.getDomRef("labelIcon");
				if (oIconDomRef) {
					var sCustomImage = this._oControl._customImage;
					if (sCustomImage) {
						oIconDomRef.style.backgroundImage = "url('" + sCustomImage + "')";
						oIconDomRef.classList.add("sapMSelectListItemIconCustom");
					} else {
						oIconDomRef.style.backgroundImage = "unset";
						oIconDomRef.classList.remove("sapMSelectListItemIconCustom");
					}
				}
			}.bind(this)
		});

		//keyboard handling only if the list is open
		this._oControl.addDelegate({
			onsappageup: function () {
				if (this._oControl.isOpen()) {
					var iSelected = this._oControl.getSelectedIndex();
					this._oControl.setSelectedIndex(iSelected - 50); //select will do -10
				}
			}.bind(this),
			onsappagedown: function () {
				if (this._oControl.isOpen()) {
					var iSelected = this._oControl.getSelectedIndex();
					if (iSelected < 3) {
						this._oControl.setSelectedIndex(29);
					} else {
						this._oControl.setSelectedIndex(iSelected + 50); //select will do +10
					}
				}
			}.bind(this),
			onsapup: function () {
				if (this._oControl.isOpen()) {
					var bAllowFile = this.getAllowFile();
					var bAllowNone = this.getAllowNone();
					var bFileSelected = this._oIconModel.getProperty("/2/enabled");
					var iSelected = this._oControl.getSelectedIndex();
					if (iSelected > 11 + 2) {
						this._oControl.setSelectedIndex(iSelected - 11);//select will do -1
					} else if (iSelected >= 3) {
						if (bAllowNone && !bAllowFile) {
							this._oControl.setSelectedIndex(0);
						} else if (bFileSelected) {
							this._oControl.setSelectedIndex(2);
						} else {
							this._oControl.setSelectedIndex(3);
						}
					}
				}
			}.bind(this),
			onsapdown: function () {
				if (this._oControl.isOpen()) {
					var iSelected = this._oControl.getSelectedIndex();
					if (iSelected > 1) {
						this._oControl.setSelectedIndex(iSelected + 11); //select will do +1
					}
				}
			}.bind(this),
			onsapleft: function () {
				if (this._oControl.isOpen()) { //just do up
					this._oControl.onsapup.apply(this._oControl, arguments);
				}
			}.bind(this),
			onsapright: function () {
				if (this._oControl.isOpen()) { //just do up
					this._oControl.onsapdown.apply(this._oControl, arguments);
				}
			}.bind(this)

		}, true);
	};

	// add style class to the render manager
	IconSelect.prototype.applyStyle = function (oRm) {
		oRm.class("sapUiIntegrationIconSelect");
		if (this._oControl && this._oControl.getWidth) {
			oRm.style("width", this._oControl.getWidth());
		}
	};

	IconSelect.prototype._fileUploadChange = function () {
		var fileReader = new window.FileReader();
		fileReader.onload = function () {
			//file is uploaded
			this.setValue(fileReader.result);
			this._oControl.invalidate();
		}.bind(this);
		if (this._oFileUpload.files.length === 1) {
			fileReader.readAsDataURL(this._oFileUpload.files[0]);
		}
	};

	//focus is back after a file upload dialog
	IconSelect.prototype._focusBack = function () {
		this._oControl.getDomRef("hiddenSelect").removeEventListener("focus", this._boundFocusBack);
		setTimeout(function () {
			this.setValue(this.getValue());
		}.bind(this), 150);
	};

	IconSelect.prototype.bindPropertyToControl = function (sProperty, oBindingInfo) {
		if (sProperty === "editable") {
			var oControlBindingInfo = merge({}, oBindingInfo);
			this._oControl.bindProperty("editable", oControlBindingInfo);
		}
	};

	IconSelect.prototype.setValue = function (sValue) {
		this.setProperty("value", sValue, true);
		if (sValue && sValue.indexOf("data:image/") === 0) {
			this._oControl._customImage = sValue;
			this._oIconModel.setProperty("/2/enabled", true);
			this._oControl.setSelectedKey("selected");
		} else {
			this._oControl._customImage = null;
			this._oIconModel.setProperty("/2/enabled", false);
			this._oControl.setSelectedKey(sValue);
		}
		this._oControl.invalidate();
		return this;
	};

	IconSelect.prototype.setAllowFile = function (bValue) {
		this.setProperty("allowFile", bValue, true);
		bValue = this.getAllowFile();
		this._oIconModel.setProperty("/1/enabled", bValue);
		return this;
	};

	IconSelect.prototype.setAllowNone = function (bValue) {
		this.setProperty("allowNone", bValue, true);
		bValue = this.getAllowNone();
		this._oIconModel.setProperty("/0/enabled", bValue);
		return this;
	};

	return IconSelect;
});

redpajama_set_name: RedPajamaGithub


text:
function microAjax(url, callbackFunction)
{
	this.bindFunction = function (caller, object) {
		return function() {
			return caller.apply(object, [object]);
		};
	};

	this.stateChange = function (object) {
		if (this.request.readyState==4)
			this.callbackFunction(this.request.responseText);
	};

	this.getRequest = function() {
		if (window.ActiveXObject)
			return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest)
			return new XMLHttpRequest();
		return false;
	};

	this.postBody = (arguments[2] || "");

	this.callbackFunction=callbackFunction;
	this.url=url;
	this.request = this.getRequest();

	if(this.request) {
		var req = this.request;
		req.onreadystatechange = this.bindFunction(this.stateChange, this);

		if (this.postBody!=="") {
			req.open("POST", url, true);
			req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
			req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		} else {
			req.open("GET", url, true);
		}

		req.send(this.postBody);
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: at15
 * Date: 15-2-19
 * Time: 下午10:45
 */
namespace Dy\Orm;

use Dy\Db\Exception\DbException;
use Dy\Orm\Exception\NotDeleted;
use Dy\Orm\Exception\NotExists;
use Dy\Orm\Exception\NotFound;
use Dy\Orm\Exception\NotModified;
use Dy\Orm\Exception\NotSaved;
use Dy\Orm\Exception\UnknownColumn;

/**
 * Class Model
 * @package Dy\Orm
 */
abstract class Model
{
    const TABLE_NAME = '';
    const PRIMARY_KEY_NAME = 'id';
    const DEFAULT_PAGE_SIZE = 10;

    protected static $_booted = false;
    /**
     * @var \FakeCI
     */
    protected static $_ci;
    protected static $_redis;
    protected static $_white_list = array();

    /**
     * Whether to use timestamp
     * @var bool
     */
    public static $timestamps = true;

    protected $_attributes = array();
    protected $_original = array();

    public function __construct($attributes = array())
    {
        if (!static::$_booted) {
            static::_boot();
        }

        if (empty(static::TABLE_NAME)) {
            $class_name = get_called_class();
            throw new \Exception('Model ' . $class_name . ' must have table name');
        }
        // assign the attributes
        // TODO: how to know if attributes are from database not user input?
        if (!empty($attributes)) {
            $this->_set_attributes($attributes);
        }
    }

    private static function _check_field($name)
    {
        if (in_array($name, static::$_white_list)) {
            return TRUE;
        } else {
            throw new UnknownColumn($name);
        }
    }

    /**
     *
     * @todo Exception when attribute not exists?
     *
     * @param $name
     * @throws UnknownColumn
     * @return mixed
     */
    public function __get($name)
    {
        static::_check_field($name);
        return $this->_attributes[$name];
    }

    /**
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->_attributes[$name] = $value;
    }

    public static function select($select = '*')
    {
        if (!static::$_booted) {
            static::_boot();
        }
        if ($select === '*') {
            $select = static::$_white_list;
        } else {
            $select = static::_filter_select($select);
        }
        if (count($select)) {
            static::$_ci->db->select($select);
        }
    }

    private static function _filter_select($select)
    {
        if (is_string($select)) {
            $select = explode(',', $select);
        }
        $selectFiltered = array();
        foreach ($select as $val) {
            $val = trim($val);
            if ($val === '') {
                continue;
            }
            static::_check_field($val);
            $selectFiltered[] = $val;
        }
        return $selectFiltered;
    }

    /**
     * @todo Return something for the chain method.
     * @param string $order
     */
    public static function order($order)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        $order = static::_filter_order($order);
        foreach ($order as $val) {
            static::$_ci->db->order_by($val[0], $val[1]);
        }
    }

    private static function _filter_order($order)
    {
        if (is_string($order)) {
            $src = $order;
            $order = array();
            $offset = 0;
            $len = strlen($src);
            while ($offset < $len) {
                $offset += 1;
                $pos = static::_strpos_or($src, array('+', '-', ',', ' '), $offset);
                $name = substr($src, $offset, $pos - $offset);
                $direction = substr($src, $offset - 1, 1);
                if ($direction === '+') {
                    $direction = 'ASC';
                } elseif ($direction === '-') {
                    $direction = 'DESC';
                } else {
                    if ($offset === 1) {
                        $name = $direction . $name;
                    }
                    $direction = 'ASC';
                }
                $name = trim($name);
                if ($name !== '') {
                    static::_check_field($name);
                    $order[] = array($name, $direction);
                }
                $offset = $pos;
            }
        } else {
            foreach ($order as $val) {
                static::_check_field($val[0]);
            }
        }
        return $order;
    }

    /**
     * @param string $haystack
     * @param array $needles
     * @param int $offset
     * @return int the position as an integer or length of haystack if needle not found.
     */
    private static function _strpos_or($haystack, $needles, $offset = 0)
    {
        $posMin = strlen($haystack);
        foreach ($needles as $needle) {
            $pos = strpos($haystack, $needle, $offset);
            if ($pos !== FALSE AND $pos < $posMin) {
                $posMin = $pos;
            }
        }
        return $posMin;
    }

    public static function where($whereRaw, $whereAs = NULL)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        static::$_ci->db->where(static::_filter_where(is_array($whereRaw) ? $whereRaw : array($whereRaw => $whereAs)));
    }

    private static function _filter_where($whereRaw)
    {
        $where = array();
        foreach ($whereRaw as $key => $value) {
            static::_check_field($key);
            switch (substr($value, 0, 2)) {
                case '>=':          $key .= '>=';   $value = substr($value, 2); break;
                case '<=':          $key .= '<=';   $value = substr($value, 2); break;
                default:
                    switch (substr($value, 0, 1)) {
                        case '!':   $key .= '!=';   $value = substr($value, 1); break;
                        case '>':   $key .= '>';    $value = substr($value, 1); break;
                        case '<':   $key .= '<';    $value = substr($value, 1);
                    }
            }
            $where[$key] = $value;
        }
        return $where;
    }

    public static function paging($page = 1, $perPage = 10)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        static::limit(($page - 1) * $perPage, $perPage);
    }

    public static function limit($offset, $number)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        static::$_ci->db->limit($number, $offset);
    }

    public static function countAll()
    {
        if (!static::$_booted) {
            static::_boot();
        }
        static::$_ci->db->select('count(*) as num');
        return static::get()->row()->num;
    }

    /**
     * @todo Design the return value.
     * @return object
     */
    public static function get()
    {
        if (!static::$_booted) {
            static::_boot();
        }
        return static::_real_get();
    }

    /**
     * @param $whereRaw
     * @param $default
     * @return array [
     *     'count' => $count,
     *     'result' => [$item0, $item1, ...],
     *     'option' => ['page' => $page, 'per_page' => $perPage]
     * ]
     */
    public static function getWhere($whereRaw, $default = array())
    {
        if (!static::$_booted) {
            static::_boot();
        }

        $whereRaw = array_merge(array_merge(array(
            'select' => '*',
            'order' => '',
            'page' => 1,
            'per_page' => 10
        ), $default), $whereRaw);

        static::select($whereRaw['select']);
        if ($whereRaw['order']) {
            static::order($whereRaw['order']);
        }
        static::paging(
            $page = max(1, intval($whereRaw['page'])),
            $perPage = min(50, max(1, intval($whereRaw['per_page'])))
        );

        unset($whereRaw['select']);
        unset($whereRaw['order']);
        unset($whereRaw['page']);
        unset($whereRaw['per_page']);

        $where = static::_filter_where($whereRaw);

        static::$_ci->db->where($where);
        $result = static::get()->result();

        static::$_ci->db->where($where);
        $count = static::countAll();

        return array(
            'count'  => $count,
            'result' => $result,
            'option' => array(
                'page'     => $page,
                'per_page' => $perPage
            )
        );
    }

    /**
     * Perform the real getting.
     *
     * @return object result object
     */
    protected static function _real_get()
    {
        return static::$_ci->db->get(static::TABLE_NAME);
    }

    /**
     * Find one record by primary_key_value.
     *
     * @param $primary_key_value
     * @return static
     * @throws NotFound
     */
    public static function find($primary_key_value)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        static::$_ci->db->where(static::PRIMARY_KEY_NAME, $primary_key_value);
        // we must add limit 1 to avoid ci to get more result
        static::$_ci->db->limit(1);
        $record = static::get()->row_array();
        if (empty($record)) {
            throw new NotFound($primary_key_value);
        }

        return new static($record);
    }

    /**
     * Delete a row or rows by primary key(s)
     *
     * @param array|int   $primary_key_values
     * @return int|false  Count of deleted rows. If the query failed, FALSE will be returned.
     * @throws DbException
     */
    public static function destroy($primary_key_values)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        $primary_key_values = is_array($primary_key_values) ? $primary_key_values : func_get_args();

        // Use destroy_or_fail actually
        try {
            return static::destroyOrFail($primary_key_values);
        } catch (\Exception $e) {
            return FALSE;
        }
    }

    /**
     * Delete certain rows according to where clauses and number limitation.
     *
     * @param array|string  $whereRaw where clause; note an empty argument is not allowed
     * @param int           $limit the maximum number of rows to be deleted, positive numbers only
     * @return int          Count of deleted rows.
     * @throws \InvalidArgumentException
     * @throws DbException
     * @throws NotDeleted If the deletion fails.
     */
    public static function destroyWhere($whereRaw, $limit = 1)
    {
        if (!static::$_booted) {
            static::_boot();
        }

        // Check arguments for security
        if (empty($whereRaw)) {
            throw new \InvalidArgumentException('Empty where statement is not allowed');
        }
        if ($limit <= 0) {
            throw new \InvalidArgumentException('Limit has to be set when destroying');
        }

        // Execute the query
        self::where($whereRaw);
        self::limit(0, $limit);
        $count = static::_real_destroy();

        // Throws exception if no rows are affected
        if ($count == 0) {
            throw new NotDeleted($whereRaw);
        }
        return $count;
    }

    /**
     * Delete a row or rows by primary key(s) and throw an exception if query fails.
     *
     * @param array|int   $primary_key_values
     * @return int        Count of deleted rows.
     * @throws \InvalidArgumentException
     * @throws NotDeleted If the deletion fails.
     */
    public static function destroyOrFail($primary_key_values)
    {
        if (!static::$_booted) {
            static::_boot();
        }
        $primary_key_values = is_array($primary_key_values) ? $primary_key_values : func_get_args();

        // Empty array is not allowed in case the whole table is emptied.
        if (empty($primary_key_values)) {
            throw new \InvalidArgumentException('No primary keys are set for deleting');
        }

        // We'll actually add where conditions and move the real delete work to another method.
        static::$_ci->db->where_in(static::PRIMARY_KEY_NAME, $primary_key_values);
        $count = static::_real_destroy();

        // Throws exception if no rows are affected
        if ($count == 0) {
            throw new NotDeleted($primary_key_values);
        }
        return $count;
    }

    /**
     * Internal method for deleting rows.
     *
     * @return int Count of deleted rows.
     */
    protected static function _real_destroy()
    {
        static::$_ci->db->delete(static::TABLE_NAME);
        return static::$_ci->db->affected_rows();
    }

    /**
     * @return int primary_key_value for the created or updated record.
     *
     * @throws NotModified
     * @throws NotSaved
     */
    public function save()
    {
        if (!empty($this->_attributes)) {
            if (!$this->exists()) {
                return $this->create();
            } else {
                return $this->update();
            }
        } else {
            throw new NotModified();
        }
    }

    public function create()
    {
        // add the timestamps
        if (static::$timestamps AND !isset($this->_attributes['update_time'])) {
            $current_time = date("Y-m-d H:i:s");
            $this->_attributes['create_time'] = $current_time;
            $this->_attributes['update_time'] = $current_time;
        }

        $this->_real_insert();
        $id = intval(static::$_ci->db->insert_id());

        // in production, ci's database wont have exception so we check the id.
        if (!$id) {
            throw new NotSaved();
        }

        // TODO:should we refetch everything from database?
        $this->_attributes[static::PRIMARY_KEY_NAME] = $id;
        $this->_original = $this->_attributes;

        return $id;
    }

    /**
     * Perform the real insertion.
     *
     * @throws NotSaved
     */
    protected function _real_insert()
    {
        try {
            static::$_ci->db->insert(static::TABLE_NAME, $this->_attributes);
        } catch (\Exception $e) {
            throw new NotSaved($e->getMessage());
        }
    }

    public function update()
    {
        $dirty = $this->_get_dirty();
        if (empty($dirty)) {
            throw new NotModified();
        }

        if (static::$timestamps) {
            $this->_attributes['update_time'] = date("Y-m-d H:i:s");
        }
        $this->_real_update($dirty);

        // check if really saved. in production and dev environment ci's database doesn't throw error.
        $affected_rows = static::$_ci->db->affected_rows();
        if ($affected_rows !== 1) {
            throw new NotSaved();
        }
        $this->_original = $this->_attributes;

        return $this->_attributes[static::PRIMARY_KEY_NAME];
    }

    /**
     * Perform the real update.
     *
     * @param array $dirty Associative array of values to be updated.
     * @throws NotSaved
     */
    protected function _real_update($dirty)
    {
        try {
            static::$_ci->db->update(static::TABLE_NAME,
                $dirty,
                array(static::PRIMARY_KEY_NAME => $this->_attributes[static::PRIMARY_KEY_NAME]));
        } catch (\Exception $e) {
            throw new NotSaved($e->getMessage());
        }
    }

    /**
     * Delete the current object.
     *
     * @todo Update the state of other models if id of another model equals id of mine.
     * @return bool Whether the process succeeds.
     */
    public function delete()
    {
        if (!$this->exists()) {
            return FALSE;
        }

        try {
            $this->deleteOrFail();
        } catch (\Exception $e) {
            return FALSE;
        }
        return TRUE;
    }

    /**
     * Delete the current object and throw an exception when it fails.
     *
     * @todo Update the state of other models if id of another model equals id of mine.
     * @throws NotDeleted
     * @throws NotExists
     * @return bool Whether the process succeeds.
     */
    public function deleteOrFail()
    {
        if (!$this->exists()) {
            throw new NotExists('The current object does\'t exist.');
        }

        static::$_ci->db->where(static::PRIMARY_KEY_NAME, $this->_attributes[static::PRIMARY_KEY_NAME]);
        $this->_real_delete();
        return TRUE;
    }

    /**
     * Perform the real deletion.
     *
     * @throws NotDeleted
     */
    protected function _real_delete()
    {
        try {
            static::$_ci->db->delete(static::TABLE_NAME);
            $this->_original = array();
            unset($this->_attributes[static::PRIMARY_KEY_NAME]);
        } catch (\Exception $e) {
            throw new NotDeleted(array($this->_attributes[static::PRIMARY_KEY_NAME]));
        }
    }

    /**
     * Find whether the object exists(not deleted).
     * Note: This method doesn't query the db for a second time.
     *
     * @return bool Whether the object exists
     */
    public function exists()
    {
        return !empty($this->_original);
    }

    protected static function _boot()
    {
        // get ci ... since we are using ci...
        static::$_ci = &get_instance();
        static::$_redis = static::$_ci->redis_lib->client;
    }

    protected function _set_attributes($attributes)
    {
        if (!isset($attributes[static::PRIMARY_KEY_NAME])) {
            throw new \Exception('must have primary key when _set_attributes!');
        }
        // TODO:it's not safe to assign the values directly
        $this->_attributes = $attributes;
        $this->_original = $attributes;
    }

    protected function _get_dirty()
    {
        $dirty = array();
        foreach ($this->_attributes as $key => $current_value) {
            if (!isset($this->_original[$key])) {
                $dirty[$key] = $current_value;
                continue;
            }
            $origin = $this->_original[$key];
            if ($origin !== $current_value) {
                // 处理字符串数字相等但不严格等的问题
                if (is_numeric($origin) AND is_numeric($current_value) AND $origin == $current_value) {
                    continue;
                } else {
                    $dirty[$key] = $current_value;
                }
            }
        }
        return $dirty;
    }
}


text:
package com.udm.atp.player;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;

//import com.example.android.musicplayer.MusicFocusable;
//import com.example.android.musicplayer.PrepareMusicRetrieverTask;

/**
 * Service that handles media playback. This is the Service through which we perform all the media
 * handling in our application. Upon initialization, it starts a {@link MusicRetriever} to scan
 * the user's media. Then, it waits for Intents (which come from our main activity,
 * {@link MainActivity}, which signal the service to perform specific operations: Play, Pause,
 * Rewind, Skip, etc.
 */
public class EpisodeService extends Service implements OnCompletionListener, OnPreparedListener,
OnErrorListener, EpisodeFocusable//,
/*PrepareMusicRetrieverTask.MusicRetrieverPreparedListener */{

	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub

	}

	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	public void onGainedAudioFocus() {
		// TODO Auto-generated method stub

	}

	public void onLostAudioFocus(boolean canDuck) {
		// TODO Auto-generated method stub

	}

}


text:
package data_science.ui.loc.text;

import javafx.scene.text.Text;

/**
 * A {@link Text} label widget containing the 'Select' text.
 * @author I.A
 */
public final class SelectText extends Text {
	/**
	 * Creates a new {@link SelectText}.
	 */
	public SelectText() {
		super("Select");

		applyStyling();
	}

	private void applyStyling() {
		setStyle("-fx-font: normal 25px 'Segoe UI'");
	}
}


text:
namespace Microsoft.Win32
{
    public static class WH
    {
        /// <summary>
        /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
        /// </summary>
        public const int MOUSE_LL = 14;

        /// <summary>
        /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard  input events.
        /// </summary>
        public const int KEYBOARD_LL = 13;

        /// <summary>
        /// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
        /// </summary>
        public const int MOUSE = 7;

        /// <summary>
        /// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
        /// </summary>
        public const int KEYBOARD = 2;
    }
    public static class WM
    {
        /// <summary>
        /// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
        /// </summary>
        public const int MOUSEMOVE = 0x200;

        /// <summary>
        /// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
        /// </summary>
        public const int LBUTTONDOWN = 0x201;

        /// <summary>
        /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
        /// </summary>
        public const int RBUTTONDOWN = 0x204;

        /// <summary>
        /// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
        /// </summary>
        public const int MBUTTONDOWN = 0x207;

        /// <summary>
        /// The WM_LBUTTONUP message is posted when the user releases the left mouse button
        /// </summary>
        public const int LBUTTONUP = 0x202;

        /// <summary>
        /// The WM_RBUTTONUP message is posted when the user releases the right mouse button
        /// </summary>
        public const int RBUTTONUP = 0x205;

        /// <summary>
        /// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
        /// </summary>
        public const int MBUTTONUP = 0x208;

        /// <summary>
        /// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
        /// </summary>
        public const int LBUTTONDBLCLK = 0x203;

        /// <summary>
        /// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
        /// </summary>
        public const int RBUTTONDBLCLK = 0x206;

        /// <summary>
        /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
        /// </summary>
        public const int MBUTTONDBLCLK = 0x209;

        /// <summary>
        /// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
        /// </summary>
        public const int MOUSEWHEEL = 0x020A;

        /// <summary>
        /// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
        /// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
        /// </summary>
        public const int KEYDOWN = 0x100;

        /// <summary>
        /// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
        /// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
        /// or a keyboard key that is pressed when a window has the keyboard focus.
        /// </summary>
        public const int KEYUP = 0x101;

        /// <summary>
        /// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
        /// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
        /// presses another key. It also occurs when no window currently has the keyboard focus;
        /// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
        /// receives the message can distinguish between these two contexts by checking the context
        /// code in the lParam parameter.
        /// </summary>
        public const int SYSKEYDOWN = 0x104;

        /// <summary>
        /// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
        /// releases a key that was pressed while the ALT key was held down. It also occurs when no
        /// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
        /// to the active window. The window that receives the message can distinguish between
        /// these two contexts by checking the context code in the lParam parameter.
        /// </summary>
        public const int SYSKEYUP = 0x105;
    }
    public static class VK
    {
        public const byte SHIFT = 0x10;
        public const byte CAPITAL = 0x14;
        public const byte NUMLOCK = 0x90;

        public const byte CONTROL = 0x11;
    }
}


text:
<TITLE>Review for Cadillac Man (1990)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Cadillac Man (1990)

reviewed by
Elisabeth Riba

                          No Lemons in CADILLAC MAN
                       A film review by Elisabeth Riba
                        Copyright 1990 Elisabeth Riba

     CADILLAC MAN opens with shots of a cemetery.  An unlikely place to
begin a movie about cars ... until we focus on the procession stalled
by a broken hearse.  Not only does Robin Williams, the consummate
salesman, pitch the undertaker, he also hits on the widow.

     Despite this sell-at-all-costs attitude (or perhaps because of it)
Williams doesn't move the cars as fast as he once did.  His problems
pile on quickly.  He can't resist the ladies, juggling three of them as
the film starts.  To help meet his expenses, he owes massive debts to
some not-so-savory sources.  And then he receives an ultimatum.
Williams will lose his job unless he can sell twelve cars in two days.

     That sets up a tidy plot--Robin Williams does DEATH OF A SALESMAN.
But just as you think you've got the movie straightened out, it throws
you a curve.  Tim Robbins (BULL DURHAM) takes the dealership hostage.
You see, his wife is having an affair with someone in the office, and he
wants to know who.  Only Williams' practiced patter can free them.

     I found this movie the funniest I've seen all year.  It doesn't
reflect as sharp a vision as other black comedies, but it also isn't as
cruel.

     Generally, the minor characters portrayed broad stereotypes.
However, strong acting took them past the familiar territory.  Both of
Williams' girlfriends had strong personalities, although his ex-wife
seemed rather bland.  Likewise, the other salesmen seemed to blend
together, although the customers all sharply define themselves.

     Tim Robbins basically reprises his role of befuddled innocent from
BULL DURHAM.  All he wants to know was "Who did Donna?"  As his plot
falls apart, his frustration is evident.  He honestly never expected
police to show up.  When they request his demands, he only wants them to
go away.  Despite the situation, you soon sympathize with him.

     Robin Williams is quite credible as the sleazy salesman.  He knows
the reputation and lives up to it.  Williams narrates the bridges and
slower scenes, the camera an invisible passenger in his car.  I found
this technique distracting at times, although his points were often
valid.

     Robin Williams has definitely graduated from the pack of Seventies'
comics.  While much of the SNL/SCTV crowd has stagnated, he takes us
from laughs to near tears in seconds.  If future movies continue in the
vein of CADILLAC MAN and DEAD POETS' SOCIETY, I can see Robin Williams
winning an Oscar within the next decade.

     The language seemed unnecessarily strong, but didn't detract too
much from the story.  Otherwise, it was a marvelous film.  The
soundtrack consisted of older tunes.  In some ways, this added to the
image of Robin Williams as a dying breed.

     Although I enjoy most movies, I'm offering unequivocal praise here.
See this film and do so soon.  I'm afraid that the summer blockbusters
will roll CADILLAC MAN right out of the theaters.  But that's a shame,
because this definitely deserves a test drive.

--
                                  Lady Lis
                                  ~~~~~~~~
                                  a.k.a. Elisabeth Anne Riba
                                         lis@cs.brandeis.edu

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
% This function reads the parameters of a gmm file
%
% Usage: [w, mu, sigma] = gmm_read (filename)
function [w, mu, sigma] = gmm_read (filename)

% open the file and count the number of descriptors
fid = fopen (filename, 'rb');

if fid == -1
  error ('I/O error : Unable to open the file %s\n', filename)
end

% first read the vector size and the number of centroids
d = fread (fid, 1, 'int');
k = fread (fid, 1, 'int');

% read the elements
w = fread (fid, k, 'float=>single');
mu = fread (fid, d*k, 'float=>single');
sigma = fread (fid, d*k, 'float=>single');

mu = reshape (mu, d, k);
sigma = reshape (sigma, d, k);

fclose (fid);