text:
using System;
using System.Collections.Generic;

namespace DataStructures
{
    [Serializable]
    public class BurstTrie : ITrie
    {
        // Burst Tries have a root trie node, each of which can resolve to either buckets or another trie node.

        readonly BurstTrieNode _root = new BurstTrieNode();

        public void Add(string word) { Add(word.ToCharArray()); }
        public void Add(char[] word)
        {
            _root.Add(word,0);
        }
        public bool IsPresent(char[] word)
        {
            return _root.IsPresent(word);
        }
        public bool IsPresent(string word) { return IsPresent(word.ToCharArray()); }
        public bool Contains(string word) { return IsPresent(word.ToCharArray()); }
        public bool Contains(char[] word) { return IsPresent(word); }

        /// <summary>
        /// NOTE THIS METHOD HAS A BEHAVIOR YOU MAY CARE ABOUT.
        /// Duplicate words are not always tracked separately,
        /// so they may be 'collapsed' into single entries here.
        /// To fix this, BurstTrieNodes must carry 'end' as an integer, not just a boolean.
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllEntries()
        {
            List<string> items = new List<string>();
            _root.Reconstruct(new char[128], 0, items);
            return items;
        }

        public static short BurstThreshold
        {
            get
            {  return BurstCacheBucket.BurstThreshold;  }
            set
            {  BurstCacheBucket.BurstThreshold = value;  }
        }
    }
}


text:
import logging

from powervc_nova.virt.ibmpowervm.vif import vm_import
from powervc_nova.virt.ibmpowervm.vif.common import ras
from powervc_nova.virt.ibmpowervm.vif.hmc import topo_hmc
from powervc_nova.virt.ibmpowervm.vif.hmc import utils
from powervc_nova.virt.ibmpowervm.vif import hmc

from oslo.config import cfg

LOG = logging.getLogger(__name__)

CONF = cfg.CONF
CONF.import_opt('ibmpowervm_comm_timeout', 'powervc_nova.virt.ibmpowervm.hmc')

class ImportVMNetworkHMC(vm_import.ImportVMNetwork):
    """
    HMC Implementation of the VM Import function.
    """

    def __init__(self, operator, mtms=None, k2resp=None):
        """
        ImportVMNetworkHMC constructor

        :param operator: Communication channel to interface with PowerVM host
        """
        self._k2op = operator

        # Initialize some cached k2responses
        self._k2entry_ms = None

        if mtms:
            self.mtms = mtms
        else:
            self.mtms = CONF.host

        # Centralized topology service for IVM
        self._topo = topo_hmc.IBMPowerVMNetworkTopoHMC(host_name=self.mtms,
                                                       operator=self._k2op,
                                                       mtms=self.mtms)
        # Need the latest vswitch data
        self._topo._repopulate_vswitch_data()

        if not k2resp:
            self.k2resp = self._k2op.read(
                rootType='ManagedSystem',
                rootId=self._topo._find_managed_system(),
                childType='LogicalPartition',
                timeout=hmc.K2_READ_SEC,
                xag=[None])
        else:
            self.k2resp = k2resp

    def list_ports(self, lpar_id):
        """
        Will query the endpoint and determine the network configuration of the
        VM.

        :param lpar_id: The lpar identifier
        :returns: A list of dictionary objects which represents the networking
                  information.  Each dictionary will contain a 'mac_address'
                  and a 'provider:segmentation_id' - which represents the VLAN.
        """
        # A return list of dictionary objects.
        ret_adapter_list = []

        # Get the adapter information for this LPAR, note that UUIDs are
        # passed in
        logical_partition = utils.get_k2entry_for_lpar_uuid(self.k2resp,
                                                            lpar_id).element
        cna_links = logical_partition.findall('./ClientNetworkAdapters/link')
        orphaned_pairs = self._get_orphan_pairs()

        for cna_link in cna_links:
            try:
                vea = self._k2op.readbyhref(href=cna_link.get('href') +
                                            '?group=None',
                                            timeout=hmc.K2_READ_SEC)
            except Exception:
                LOG.info(_('Read failed for K2 Client Network Adapter (CNA) '
                           'link, skipping the element.'))
                continue

            # If we didn't get an entry back for some reason...
            if not vea.entry:
                ras.trace(LOG, __name__, ras.TRACE_WARNING,
                          'Failed to obtain href link from vea.entry')
                continue
            elem = vea.entry.element

            # Elements needed for import
            adapter_dict = {}
            adapter_dict['slot_num'] = elem.find('VirtualSlotNumber')\
                                           .gettext()
            adapter_dict['mac_address'] = elem.find('MACAddress').gettext()
            adapter_dict['provider:segmentation_id'] = elem.find('PortVLANID')\
                                                           .gettext()
            adapter_dict['status'] = 'Available'
            adapter_dict['physical_network'] = 'default'

            k2_vswitch_id = elem.findtext('VirtualSwitchID')
            k2_vswitch = self._topo.vswitch_map.get(k2_vswitch_id)
            adapter_dict['vswitch'] = k2_vswitch.element.findtext('SwitchName')

            # Elements for internal disection
            adapter_dict['tagged'] = elem.find('TaggedVLANSupported').gettext()
            adapter_dict['is_veth'] = True

            qbg_type = elem.findtext('VirtualStationInterfaceTypeID')
            if qbg_type is not None and len(qbg_type) > 0:
                adapter_dict['is_qbg'] = True
            else:
                adapter_dict['is_qbg'] = False

            # Determine whether the adapter is orphaned
            orphan = False
            vlanid = int(adapter_dict['provider:segmentation_id'])
            pair = '%(vs)s:%(vlan)d' % {'vs': adapter_dict['vswitch'],
                                        'vlan': vlanid}
            if pair in orphaned_pairs:
                orphan = True
            adapter_dict['is_orphan'] = orphan

            ret_adapter_list.append(adapter_dict)

        # Need to check for Host Ethernet Adapters...  K2 has a bug in some
        # versions where we need to check for Port and Ports...
        s = './HostEthernetAdapterLogicalPort/HostEthernetAdapterLogicalPort'
        adpts = logical_partition.findall(s)
        s = './HostEthernetAdapterLogicalPorts/HostEthernetAdapterLogicalPort'
        adpts.extend(logical_partition.findall(s))
        s = ('./PartitionIOConfiguration/ProfileIOSlots/ProfileIOSlot/'
             'AssociatedIOSlot/RelatedIOAdapter')
        adpts.extend(logical_partition.findall(s))
        if len(adpts) > 0:
            # Make a fake adapter...to get it to fail
            adapter_dict = {}
            adapter_dict['is_veth'] = False
            adapter_dict['addl_vlan_ids'] = []
            adapter_dict['slot_num'] = -1
            adapter_dict['lpar_id'] = lpar_id
            adapter_dict['mac_address'] = ""
            adapter_dict['provider:segmentation_id'] = -1

            # Only need one adapter to tell this is bad.
            ret_adapter_list.append(adapter_dict)

        return ret_adapter_list

    def _is_veth_adapter(self, adapter):
        """
        Determines whether or not the adapter is a Virtual Ethernet Adapter.

        :param adapter: The adapter object.  Will vary by platform.
        :returns: True if it is a Virtual Ethernet Adapter.
        """

        # Set via _list_net_adapters method
        return adapter['is_veth']

    def _is_qbg_veth(self, adapter):
        """
        Determines whether or not the adapter is a Qbg Virtual Ethernet
        Adapter.

        :param adapter: The adapter.
        :returns: True if it is a Qbg enabled adapter.
        """
        return adapter['is_qbg']

    def _has_only_pvid(self, adapter):
        """
        Determines whether or not the adapter only has a PVID (no additional
        VLANs).

        :param adapter: The adapter.
        :returns: True if it has only a PVID.  False if it has 'additional'
                  VLANs
        """
        return adapter['tagged'] == 'false'

    def _is_orphan_vlan(self, adapter):
        """
        Determines whether or not the adapter has a PVID that does not have an
        associated SEA, and thus is considered an "orphan".

        :param adapter: The adapter.
        :returns: True if the adapters PVID is an orphan, otherwise False.
        """
        return adapter['is_orphan']

redpajama_set_name: RedPajamaGithub


text:
var loader = {
    show: function (insideObjectName) {
        $(insideObjectName).append('');
    },
    hide: function (insideObjectName) {
        $(insideObjectName).find('.loader').remove();
    }
};

var tabAjax = {
    reloadTab: {},
    initTab: function (callBackOnSuccess, preLoadCallback) {
        $("a[data-toggle='tab']").each(function (key, obj) {
            var href = $(obj).attr('href');
            tabAjax.reloadTab[href] = tabAjax.reloadTab[href] == undefined;
            $(obj).click(function () {
                if (tabAjax.reloadTab[href]) {
                    if (preLoadCallback != undefined) {
                        preLoadCallback(this);
                    }
                    var $contentTab = $($(this).attr('data-content'));
                    var $url = $(this).attr('data-url');
                    loader.show($contentTab);
                    $.get($url, function (data) {
                        $contentTab.html(data);
                        loader.hide($contentTab);
                        tabAjax.reloadTab[href] = false;
                        if (callBackOnSuccess != undefined) {
                            callBackOnSuccess(href);
                        }
                    })
                }
            });
        })
    },
    reloadActiveTab: function (callBackOnSuccess, preLoadCallback) {
        var $activeTab = $('ul.nav-tabs li.active a[data-toggle="tab"]');
        var $contentTab = $($activeTab.attr('data-content'));
        var $url = $activeTab.attr('data-url');
        var href = $activeTab.attr('href');
        loader.show($contentTab);
        tabAjax.reloadTab[href] = true;
        if (preLoadCallback != undefined) {
            preLoadCallback($activeTab);
        }
        $.get($url, function (data) {
            $contentTab.html(data);
            loader.hide($contentTab);
            tabAjax.reloadTab[href] = false;
            if (callBackOnSuccess != undefined) {
                callBackOnSuccess(href);
            }
        })
    }
};

var flashback = {
    container: '#flashback',
    add: function (type, text) {
        $(flashback.container).append(
            '
' + text + '
'
        );

    }
};


text:
print "Let's print stuff!"
print "Say your name, and something cool about yourself!"

# each person should put a print statement for themselves
# for example: print "Hi, I'm John, and I like pie."


text:
package play.modules.morphia;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.DatastoreImpl;
import com.google.code.morphia.Key;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Reference;
import com.google.code.morphia.annotations.Transient;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.*;
import com.google.code.morphia.query.Query;
import com.mongodb.*;
import org.apache.commons.lang.StringUtils;
import org.bson.types.CodeWScope;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.data.binding.BeanWrapper;
import play.data.binding.Binder;
import play.data.binding.ParamNode;
import play.data.validation.Validation;
import play.db.jpa.JPA;
import play.db.jpa.JPABase;
import play.exceptions.UnexpectedException;
import play.modules.morphia.MorphiaPlugin.MorphiaModelLoader;
import play.modules.morphia.utils.IdGenerator;
import play.modules.morphia.utils.StringUtil;
import play.mvc.Scope.Params;

import javax.persistence.*;
import java.io.Serializable;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * This class provides the abstract declarations for all Models. Implementations
 * of these declarations are provided by the MorphiaEnhancer.
 *
 * @author greenlaw110@gmail.com
 */
public class Model implements Serializable, play.db.Model {

    public static final String ALL = "__all__";

    private static final long serialVersionUID = -719759872826848048L;

    // -- play.db.Model interface
    @Override
    public Object _key() {
        return getId();
    }

    @Override
    public void _save() {
        save();
    }

    @Override
    public void _delete() {
        if (isNew()) return;
        _h_OnDelete();
        ds().delete(this);
        _h_Deleted();
    }

    // -- porting from play.db.GenericModel
    /**
     * This method is deprecated. Use this instead:
     *
     *  public static <T extends Model> T create(ParamNode rootParamNode, String name, Class<?> type, Annotation[] annotations)
     */
    @Deprecated
    public static <T extends Model> T create(Class<?> type, String name, Map<String, String[]> params, Annotation[] annotations) {
        ParamNode rootParamNode = ParamNode.convert(params);
        return (T)create(rootParamNode, name, type, annotations);
    }

    public static <T extends Model> T create(ParamNode rootParamNode, String name, Class<?> type, Annotation[] annotations) {
        try {
            Constructor c = type.getDeclaredConstructor();
            c.setAccessible(true);
            Object model = c.newInstance();
            return (T) edit(rootParamNode, name, model, annotations);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("deprecation")
    public static <T extends Model> T edit(ParamNode rootParamNode, String name, Object o, Annotation[] annotations) {
        ParamNode paramNode = rootParamNode.getChild(name, true);
        // #1195 - Needs to keep track of whick keys we remove so that we can restore it before
        // returning from this method.
        List<ParamNode.RemovedNode> removedNodesList = new ArrayList<ParamNode.RemovedNode>();
        try {
            BeanWrapper bw = new BeanWrapper(o.getClass());
            // Start with relations
            Set<Field> fields = new HashSet<Field>();
            Class clazz = o.getClass();
            while (!clazz.equals(Object.class)) {
                Collections.addAll(fields, clazz.getDeclaredFields());
                clazz = clazz.getSuperclass();
            }
            for (Field field : fields) {
                boolean isEntity = false;
                String relation = null;
                boolean multiple = false;
                boolean isEmbedded = field.isAnnotationPresent(Embedded.class);
                //
                if (isEmbedded || field.isAnnotationPresent(Reference.class)) {
                    isEntity = true;
                    multiple = false;
                    Class<?> clz = field.getType();
                    Class<?>[] supers = clz.getInterfaces();
                    for (Class<?> c : supers) {
                        if (c.equals(Collection.class)) {
                            multiple = true;
                            break;
                        }
                    }
                    // TODO handle Map<X, Y> relationship
                    // TODO handle Collection<Collection2<..>>
                    relation = multiple ? ((Class<?>) ((ParameterizedType) field
                            .getGenericType()).getActualTypeArguments()[0]).getName()
                            : clz.getName();
                }

                if (isEntity) {

                    ParamNode fieldParamNode = paramNode.getChild(field.getName(), true);

                    Class<Model> c = (Class<Model>) Play.classloader.loadClass(relation);
                    if (Model.class.isAssignableFrom(c)) {
                        String keyName = Model.Manager.factoryFor(c).keyName();
                        if (multiple && Collection.class.isAssignableFrom(field.getType())) {
                            Collection l = new ArrayList();
                            if (SortedSet.class.isAssignableFrom(field.getType())) {
                                l = new TreeSet();
                            } else if (Set.class.isAssignableFrom(field.getType())) {
                                l = new HashSet();
                            }
                            String[] ids = fieldParamNode.getChild(keyName, true).getValues();
                            if (ids != null) {
                                // Remove it to prevent us from finding it again later
                                fieldParamNode.removeChild(keyName, removedNodesList);
                                for (String _id : ids) {
                                    if (_id.equals("")) {
                                        continue;
                                    }

                                    MorphiaQuery q = new MorphiaQuery(c);
                                    q.filter(keyName, Binder.directBind(rootParamNode.getOriginalKey(), annotations, _id, Model.Manager.factoryFor((Class<Model>) Play.classloader.loadClass(relation)).keyType(), null));
                                    try {
                                        l.add(q.get());

                                    } catch (NoResultException e) {
                                        Validation.addError(name + "." + field.getName(), "validation.notFound", _id);
                                    }
                                }
                                bw.set(field.getName(), o, l);
                            }
                        } else {
                            String[] ids = fieldParamNode.getChild(keyName, true).getValues();
                            if (ids != null && ids.length > 0 && !ids[0].equals("")) {

                                MorphiaQuery q = new MorphiaQuery(c);
                                q.filter(keyName, Binder.directBind(rootParamNode.getOriginalKey(), annotations, ids[0], Model.Manager.factoryFor((Class<Model>) Play.classloader.loadClass(relation)).keyType(), null));
                                try {
                                    Object to = q.get();
                                    edit(paramNode, field.getName(), to, field.getAnnotations());
                                    // Remove it to prevent us from finding it again later
                                    paramNode.removeChild( field.getName(), removedNodesList);
                                    bw.set(field.getName(), o, to);
                                } catch (NoResultException e) {
                                    Validation.addError(fieldParamNode.getOriginalKey(), "validation.notFound", ids[0]);
                                    // Remove only the key to prevent us from finding it again later
                                    // This how the old impl does it..
                                    fieldParamNode.removeChild(keyName, removedNodesList);
                                    if (fieldParamNode.getAllChildren().size()==0) {
                                        // remove the whole node..
                                        paramNode.removeChild( field.getName(), removedNodesList);
                                    }

                                }

                            } else if (ids != null && ids.length > 0 && ids[0].equals("")) {
                                bw.set(field.getName(), o, null);
                                // Remove the key to prevent us from finding it again later
                                fieldParamNode.removeChild(keyName, removedNodesList);
                            }
                        }
                    }
                }
            }
            ParamNode beanNode = rootParamNode.getChild(name, true);
            Binder.bindBean(beanNode, o, annotations);
            return (T) o;
        } catch (Exception e) {
            throw new UnexpectedException(e);
        } finally {
            // restoring changes to paramNode
            ParamNode.restoreRemovedChildren( removedNodesList );
        }
    }

    /**
     * This method is deprecated. Use this instead:
     *
     *  public static <T extends Model> T edit(ParamNode rootParamNode, String name, Object o, Annotation[] annotations)
     *
     * @return
     */
    @Deprecated
    public static <T extends Model> T edit(Object o, String name, Map<String, String[]> params, Annotation[] annotations) {
        ParamNode rootParamNode = ParamNode.convert(params);
        return (T)edit( rootParamNode, name, o, annotations);
    }

    /**
     * This method is deprecated. Use this instead:
     *
     *  public <T extends Model> T edit(ParamNode rootParamNode, String name)
     */
    @Deprecated
    public <T extends Model> T edit(String name, Map<String, String[]> params) {
        ParamNode rootParamNode = ParamNode.convert(params);
        return (T)edit(rootParamNode, name, this, null);
    }

    public <T extends Model> T edit(ParamNode rootParamNode, String name) {
        edit(rootParamNode, name, this, null);
        return (T) this;
    }

    public boolean validateAndSave() {
        if (Validation.current().valid(this).ok) {
            save();
            return true;
        }
        return false;
    }

    public boolean validateAndCreate() {
        if (Validation.current().valid(this).ok) {
            return create();
        }
        return false;
    }

    /**
     * This method is deprecated as Embedded object shall not extends Model class
     * and shall not be enhanced
     *
     * @deprecated
     * @return
     */
    protected boolean isEmbedded_() {
        return false;
    }

    /**
     * MorphiaEnhancer will override this method for sub class with \@Id
     * annotation specified
     *
     * @return
     */
    protected boolean isUserDefinedId_() {
        return false;
    }

    /**
     * Any sub class with \@Id annotation specified need to rewrite this method
     *
     * @return
     */
    protected static Object processId_(Object id) {
        return IdGenerator.processId(id);
    }

    /**
     * MorphiaEnhancer will override this method for sub class without \@Embedded
     * annotation specified
     *
     * If user defined customized \@Id field, it's better to override this
     * method for the sake of performance. Otherwise framework will use
     * reflection to get the value
     *
     * @return
     */
    public Object getId() {
        return null;
    }

    @SuppressWarnings("unchecked")
    public <T> T getId(Class<T> clazz) {
        return (T) getId();
    }

    public final void setId(Object id) {
        if (null != getId()) {
            throw new IllegalStateException(
                    "Cannot set ID to entity with ID presented");
        }
        setId_(id);
    }

    /**
     * MorphiaEnhancer will override this method for sub class without user
     * annotated \@Id fields
     */
    protected void setId_(Object id) {
        throw new UnsupportedOperationException(
                "Please override this method for user marked Id field entity: "
                        + this.getClass().getName());
    }

    private void generateId_() {
        if (isEmbedded_())
            return;
        if (null == getId()) {
            if (isUserDefinedId_()) {
                throw new IllegalStateException(
                        "User defined ID should be populated before persist");
            } else {
                setId_(IdGenerator.generateId(this));
            }
        }
    }

    public static play.db.Model.Factory getModelFactory() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    // -- common object methods
    @Override
    public String toString() {
        String id = getId() == null ? "empty_key" : getId().toString();
        return getClass().getSimpleName() + "[" + id + "]";
    }

    /**
     * For sub class with \@Embedded annotation specified, it's better to
     * override this method
     */
    @Override
    public int hashCode() {
        Object oid = getId();
        return null == oid ? 0 : oid.hashCode();
    }

    /**
     * For sub class with \@Embedded annotation specified, it's better to
     * override this method
     */
    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if ((this == other)) {
            return true;
        }
        if (!this.getClass().isAssignableFrom(other.getClass())) {
            return false;
        }
        Object oid = getId();
        if (oid == null) {
            return false;
        }
        return oid.equals(((Model) other).getId());
    }

    // -- helper utilities
    @Transient
    private transient boolean saved_ = false;

    /**
     * A utility method determine whether this entity is a newly constructed
     * object in memory or represents a data from mongodb
     *
     * @return true if this is a memory object which has not been saved to db
     *         yet, false otherwise
     */
    public final boolean isNew() {
        return !saved_;
    }

    private void setSaved_() {
        saved_ = true;
    }

    // -- Play JPA style methods
    /**
     * This method has no effect at all
     */
    @SuppressWarnings("unchecked")
    public <T extends Model> T merge() {
        return (T) this;
    }

    /**
     * Refresh the entity state.
     */
    @SuppressWarnings("unchecked")
    public <T extends Model> T refresh() {
        return (T) ds().get(this);
    }

    public static <T extends Model> MorphiaQuery all() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Model create(String name, Params params) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Shortcut to createQuery
     *
     * @return
     */
    public static <T extends Model> MorphiaQuery q() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static <T extends Model> MorphiaQuery createQuery() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static <T extends Model> MorphiaQuery disableValidation() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static long count() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static long count(String keys, Object... params) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Return a Set of distinct values for the given key
     *
     * @param key
     * @return a distinct set of key values
     */
    public static Set<?> _distinct(String key) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Long _max(String field) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static AggregationResult groupMax(String field, String... groupKeys) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Long _min(String field) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static AggregationResult groupMin(String field, String... groupKeys) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Long _average(String field) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static AggregationResult groupAverage(String field,
            String... groupKeys) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Long _sum(String field) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static AggregationResult groupSum(String field, String... groupKeys) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static AggregationResult groupCount(String field,
            String... groupKeys) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static Map<String, Long> _cloud(String field) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    @SuppressWarnings("unchecked")
    public <T extends Model> T delete() {
        if (isNew()) {
            Logger.warn("invocation of delete on new entity ignored");
            return (T) this;
        }

        _delete();

        return (T) this;
    }

    private void _h_OnDelete() {
        postEvent_(MorphiaEvent.ON_DELETE, this);
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.ON_DELETE, this);
        h_OnDelete();
        deleteBlobs();
    }

    protected void h_OnDelete() {
        // for enhancer usage
    }

    private void _h_Deleted() {
        h_Deleted();
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.DELETED, this);
        postEvent_(MorphiaEvent.DELETED, this);
    }

    protected void h_Deleted() {
        // for enhancer usage
    }

    protected void h_OnBatchDelete(MorphiaQuery q) {
        // for enhancer usage
    }

    protected void h_BatchDeleted(MorphiaQuery q) {
        // for enhancer usage
    }

    protected void deleteBlobs() {
        // for enhancer usage
    }

    protected void deleteBlobsInBatch(MorphiaQuery q) {
        // for enhancer usage
    }

    /**
     * store (ie insert) the entity.
     */
    public boolean create() {
        if (isNew()) {
            _save();
            return true;
        }
        return false;
    }

    public static long delete(MorphiaQuery query) {
        return query.delete();
    }

    /**
     * Shortcut to Model.delete(find())
     *
     * @return
     */
    public static long deleteAll() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Shortcut to createQuery()
     *
     * @return
     */
    public static <T extends Model> MorphiaQuery find() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * JPA style find method
     *
     * @param keys
     *            could be either "byKey1[AndKey2[AndKey3...]]" or
     *            "Key1[AndKey2[AndKey3...]]" or "key1 key2..."
     * @param params
     *            number should either be one or the same number of keys
     * @return
     */
    public static <T extends Model> MorphiaQuery find(String keys,
            Object... params) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static <T> List<T> findAll() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static <T extends Model> T findById(Object id) {
        throw new UnsupportedOperationException(
                "Embedded entity does not support this method");
    }

    /**
     * Shortcut to find(String, Object...)
     *
     * @param keys
     * @param keys
     * @return
     */
    public static <T extends Model> MorphiaQuery q(String keys, Object value) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Morphia style filter method.
     *
     * <p>
     * if you have MyModel.find("byNameAndAge", "John", 20), you can also use
     * MyModel.filter("name", "John").filter("age", 20) for the same query
     *
     * @param property
     *            should be the filter name
     * @param value
     *            the filter value
     * @return
     */
    public static <T extends Model> MorphiaQuery filter(String property,
            Object value) {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    public static <T extends Model> MorphiaUpdateOperations createUpdateOperations() {
        throw new UnsupportedClassVersionError("Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Alias of #updateOperations()
     * @param <T>
     * @return
     */
    public static <T extends Model> MorphiaUpdateOperations o() {
        throw new UnsupportedClassVersionError("Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    // -- additional quick access method
    /**
     * Return the first element in the data storage. Return null if there is no
     * record found
     */
    public static <T extends Model> T get() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Return Morphia Datastore instance
     *
     * @return
     */
    public static Datastore ds() {
        return MorphiaPlugin.ds();
    }

    /**
     * Return MongoDB DBCollection for this model
     */
    public static DBCollection col() {
        throw new UnsupportedOperationException(
                "Please annotate your model with @com.google.code.morphia.annotations.Entity annotation.");
    }

    /**
     * Return MongoDB DB instance
     *
     * @return
     */
    public static DB db() {
        return ds().getDB();
    }

    /**
     * Save and return this entity
     *
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T extends Model> T save() {
        save2();
        return (T) this;
    }

    /**
     * Save and return Morphia Key
     *
     * @return
     */
    public Key<? extends Model> save2() {
        boolean isNew = isNew();
        postEvent_(isNew ? MorphiaEvent.ON_ADD : MorphiaEvent.ON_UPDATE, this);
        if (isNew) _h_OnAdd(); else _h_OnUpdate();
        Key<? extends Model> k = ds().save(this);
        saveBlobs();
        if (isNew) {setSaved_();_h_Added();} else _h_Updated();
        return k;
    }

    /**
     * for PlayMorphia internal usage only
     */
    public final void _h_OnLoad() {
        postEvent_(MorphiaEvent.ON_LOAD, this);
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.ON_LOAD, this);
        h_OnLoad();
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_OnLoad() {
        // for enhancer usage
    }

    /**
     * for PlayMorphia internal usage only
     */
    public final void _h_Loaded() {
        setSaved_();
        loadBlobs();
        h_Loaded();
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.LOADED, this);
        postEvent_(MorphiaEvent.LOADED, this);
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_Loaded() {
        // for enhancer usage
    }

    /**
     * for PlayMorphia internal usage only
     */
    private void _h_Added() {
        h_Added();
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.ADDED, this);
        postEvent_(MorphiaEvent.ADDED, this);
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_Added() {
        // used by enhancer
    }

    /**
     * for PlayMorphia internal usage only
     */
    private void _h_Updated() {
        h_Updated();
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.UPDATED, this);
        postEvent_(MorphiaEvent.UPDATED, this);
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_Updated() {
        // used by enhancer
    }

    /**
     * for PlayMorphia internal usage only
     */
    private void _h_OnAdd() {
        postEvent_(MorphiaEvent.ON_ADD, this);
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.ON_ADD, this);
        h_OnAdd();
        generateId_();
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_OnAdd() {
        // used by enhancer
    }

    /**
     * for PlayMorphia internal usage only
     */
    private void _h_OnUpdate() {
        postEvent_(MorphiaEvent.ON_UPDATE, this);
        MorphiaPlugin.onLifeCycleEvent(MorphiaEvent.ON_UPDATE, this);
        h_OnUpdate();
    }

    /**
     * for PlayMorphia internal usage only
     */
    protected void h_OnUpdate() {
        // used by enhancer
    }

    protected void saveBlobs() {
        // used by enhancer
    }

    protected void loadBlobs() {
        // used by enhander
    }

    transient protected final Map<String, Boolean> blobFieldsTracker = new HashMap<String, Boolean>();
    protected final boolean blobChanged(String fieldName) {
        return (blobFieldsTracker.containsKey(fieldName) && blobFieldsTracker.get(fieldName));
    }
    protected final void setBlobChanged(String fieldName) {
        blobFieldsTracker.put(fieldName, true);
    }

    public String getBlobFileName(String fieldName) {
        return getBlobFileName(getClass().getSimpleName(), getId(), fieldName);
    }

    public static String getBlobFileName(String className, Object id, String fieldName) {
        return String.format("%s_%s_%s", className, StringUtils.capitalize(fieldName), id);
    }

    public static void removeGridFSFiles(String className, Object id, String...fieldNames) {
        for (String fieldName: fieldNames) {
            String fileName = getBlobFileName(className, id, fieldName);
            Blob.delete(fileName);
        }
    }

    public static void removeGridFSFiles(MorphiaQuery q, String... fieldNames) {
        q.retrievedFields(true, "_id");
        for (Key<Model> key: q.fetchKeys()) {
            Object id = key.getId();
            removeGridFSFiles(q.getEntityClass().getSimpleName(), id, fieldNames);
        }
    }

    // -- auto timestamp methods
    public long _getCreated() {
        throw new UnsupportedOperationException(
                "Please annotate model with @AutoTimestamp annotation");
    }

    public long _getModified() {
        throw new UnsupportedOperationException(
                "Please annotate model with @AutoTimestamp annotation");
    }

    private static void postEvent_(MorphiaEvent event, Object context) {
        if (MorphiaPlugin.postPluginEvent) PlayPlugin.postEvent(event.getId(), context);
    }

    public static class MorphiaUpdateOperations {
        public static Datastore ds() {
            return MorphiaPlugin.ds();
        }

        private UpdateOpsImpl<? extends Model> u_;
        private Class <? extends Model> c_;

        public UpdateOperations<? extends Model> getMorphiaUpdateOperations() {
            return u_;
        }

        public DBObject getUpdateOperationsObject() {
            return u_.getOps();
        }

        public DBCollection col() {
            return ds().getCollection(c_);
        }

        private MorphiaUpdateOperations() {
            // constructor for clone() usage
        }

        public MorphiaUpdateOperations(Class<? extends Model> clazz) {
            u_ = new UpdateOpsImpl(clazz, ((DatastoreImpl)ds()).getMapper());
            c_ = clazz;
        }

        private boolean multi = true;
        public MorphiaUpdateOperations multi(boolean multi) {
            this.multi = multi;
            return this;
        }
        public boolean multi() {
            return multi;
        }

        public MorphiaUpdateOperations validation(boolean validate) {
            if (validate) u_.enableValidation();
            else u_.disableValidation();
            return this;
        }

        public MorphiaUpdateOperations enableValidation() {
            return validation(true);
        }

        public MorphiaUpdateOperations disableValidation() {
            return validation(false);
        }

        public MorphiaUpdateOperations isolate(boolean isolate) {
            if (isolate) u_.isolated();
            else {
                throw new UnsupportedOperationException("Morphia does not support set isolated to false");
            }
            return this;
        }

        public MorphiaUpdateOperations enableIsolate() {
            return isolate(true);
        }

        public MorphiaUpdateOperations disableIsolate() {
            return isolate(false);
        }

        public MorphiaUpdateOperations isolated() {
            return enableIsolate();
        }

        public MorphiaUpdateOperations add(String fieldExpr, Object value) {
            u_.add(fieldExpr, value);
            return this;
        }

        public MorphiaUpdateOperations add(String fieldExpr, Object value, boolean addDups) {
            u_.add(fieldExpr, value, addDups);
            return this;
        }

        public MorphiaUpdateOperations addAll(String fieldExpr, List<?> values, boolean addDups) {
            u_.addAll(fieldExpr, values, addDups);
            return this;
        }

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);    //To change body of overridden methods use File | Settings | File Templates.
        }

        public MorphiaUpdateOperations dec(String fieldExpr) {
            if (StringUtil.isEmpty(fieldExpr)) {
                throw new IllegalArgumentException("Invalid fieldExpr or params");
            }
            if (fieldExpr.startsWith("by"))
                fieldExpr = fieldExpr.substring(2);
            String[] keys = fieldExpr.split("(And|[,;\\s]+)");

            for (int i = 0; i < keys.length; ++i) {
                StringBuilder sb = new StringBuilder(keys[i]);
                sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                u_.dec(sb.toString());
            }
            return this;
        }

        public MorphiaUpdateOperations inc(String fieldExpr) {
            if (StringUtil.isEmpty(fieldExpr)) {
                throw new IllegalArgumentException("Invalid fieldExpr or params");
            }
            if (fieldExpr.startsWith("by"))
                fieldExpr = fieldExpr.substring(2);
            String[] keys = fieldExpr.split("(And|[,;\\s]+)");

            for (int i = 0; i < keys.length; ++i) {
                StringBuilder sb = new StringBuilder(keys[i]);
                sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                u_.inc(sb.toString());
            }
            return this;
        }

        public MorphiaUpdateOperations inc(String fieldExpr, Number... values) {
            if (null == values) values = new Number[] {null};
            if (StringUtil.isEmpty(fieldExpr) || values.length == 0) {
                throw new IllegalArgumentException("Invalid fieldExpr or params");
            }
            if (fieldExpr.startsWith("by"))
                fieldExpr = fieldExpr.substring(2);
            String[] keys = fieldExpr.split("(And|[,;\\s]+)");

            if ((values.length != 1) && (keys.length != values.length)) {
                throw new IllegalArgumentException(
                        "Query key number does not match the params number");
            }

            Number oneVal = values.length == 1 ? values[0] : null;

            for (int i = 0; i < keys.length; ++i) {
                StringBuilder sb = new StringBuilder(keys[i]);
                sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                u_.inc(sb.toString(), oneVal == null ? values[i] : oneVal);
            }
            return this;
        }

        public MorphiaUpdateOperations removeAll(String fieldExpr, Object value) {
            u_.removeAll(fieldExpr, value);
            return this;
        }

        public MorphiaUpdateOperations removeAll(String fieldExpr, List<?> values) {
            u_.removeAll(fieldExpr, values);
            return this;
        }

        public MorphiaUpdateOperations removeFirst(String fieldExpr) {
            u_.removeFirst(fieldExpr);
            return this;
        }

        public MorphiaUpdateOperations removeLast(String fieldExpr) {
            u_.removeLast(fieldExpr);
            return this;
        }

        public MorphiaUpdateOperations set(String fieldExpr, Object... values) {
            if (null == values) values = new Object[] {null};
            if (null == fieldExpr || values.length == 0) {
                throw new IllegalArgumentException("Invalid query or params");
            }
            if (fieldExpr.startsWith("by"))
                fieldExpr = fieldExpr.substring(2);
            String[] keys = fieldExpr.split("(And|[,;\\s]+)");

            if ((values.length != 1) && (keys.length != values.length)) {
                throw new IllegalArgumentException(
                        "Query key number does not match the params number");
            }

            Object oneVal = values.length == 1 ? values[0] : null;

            for (int i = 0; i < keys.length; ++i) {
                StringBuilder sb = new StringBuilder(keys[i]);
                sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                u_.set(sb.toString(), oneVal == null ? values[i] : oneVal);
            }
            return this;
        }

        public MorphiaUpdateOperations unset(String fieldExpr) {
            u_.unset(fieldExpr);
            return this;
        }

        public <T> T updateFirst(MorphiaQuery q) {
            return (T)findAndModify(q);
        }

        public <T> T updateFirst(String query, Object... params) {
            MorphiaQuery q = new MorphiaQuery(c_).findBy(query, params);
            return (T)findAndModify(q);
        }

        public <T> T findAndModify(MorphiaQuery q) {
            return (T)ds().findAndModify((Query)q.getMorphiaQuery(), (UpdateOperations)u_);
        }

        public <T> T findAndModify(String query, Object... params) {
            MorphiaQuery q = new MorphiaQuery(c_).findBy(query, params);
            return (T)findAndModify(q);
        }

        public <T> T updateFirst(MorphiaQuery q, boolean oldVersion) {
            return (T)findAndModify(q, oldVersion);
        }

        public <T> T updateFirst(boolean oldVersion, String query, Object... params) {
            MorphiaQuery q = new MorphiaQuery(c_).findBy(query, params);
            return (T)findAndModify(q, oldVersion);
        }

        public <T> T findAndModify(MorphiaQuery q, boolean oldVersion) {
            return (T)ds().findAndModify((Query)q.getMorphiaQuery(), (UpdateOperations)u_, oldVersion);
        }

        public <T> T findAndModify(boolean oldVersion, String query, Object... params) {
            MorphiaQuery q = new MorphiaQuery(c_).findBy(query, params);
            return (T)findAndModify(q, oldVersion);
        }

        public <T> T updateFirst(MorphiaQuery q, boolean oldVersion, boolean createIfMissing) {
            return (T)findAndModify(q, oldVersion, createIfMissing);
        }

        public <T> T findAndModify(MorphiaQuery q, boolean oldVersion, boolean createIfMissing) {
            return (T)ds().findAndModify((Query)q.getMorphiaQuery(), (UpdateOperations)u_, oldVersion, createIfMissing);
        }

        public <T> UpdateResults<T> update(MorphiaQuery q) {
            return ds().update((Query<T>)q.getMorphiaQuery(), (UpdateOperations<T>)u_);
        }

        public <T> UpdateResults<T> update(String query, Object... params) {
            MorphiaQuery q = new MorphiaQuery(c_).findBy(query, params);
            return ds().update((Query<T>)q.getMorphiaQuery(), (UpdateOperations<T>)u_);
        }

        private <T> UpdateResults<T> update(Query<T> q) {
            return ds().update(q, (UpdateOperations<T>)u_);
        }

        public <T> UpdateResults<T> updateAll() {
            return ds().update((QueryImpl) ds().createQuery(c_), (UpdateOperations<T>)u_);
        }

    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static class MorphiaQuery {
        public static Datastore ds() {
            return MorphiaPlugin.ds();
        }

        private QueryImpl<? extends Model> q_;
        private Class<? extends Model> c_;

        public Query<? extends Model> getMorphiaQuery() {
            return q_;
        }

        public DBObject getQueryObject() {
            return q_.getQueryObject();
        }

        public DBCollection col() {
            return ds().getCollection(c_);
        }

        // constructor for clone() usage
        private MorphiaQuery() {
        }

        public MorphiaQuery(Class<? extends Model> clazz) {
            // super(clazz, ds().getCollection(clazz), ds());
            q_ = (QueryImpl<? extends Model>) ds().createQuery(clazz);
            c_ = clazz;
        }

        public MorphiaQuery(Class<? extends Model> clazz, DBCollection coll,
                Datastore ds) {
            // super(clazz, coll, ds);
            q_ = new QueryImpl(clazz, coll, ds);
            c_ = clazz;
        }

        public MorphiaQuery(Class<? extends Model> clazz, DBCollection coll,
                Datastore ds, int offset, int limit) {
            // super(clazz, coll, ds, offset, limit);
            q_ = new QueryImpl(clazz, coll, ds, offset, limit);
            c_ = clazz;
        }

        public long delete() {
            long l = count();
            postEvent_(MorphiaEvent.ON_BATCH_DELETE, this);
            MorphiaPlugin.onBatchLifeCycleEvent(MorphiaEvent.ON_BATCH_DELETE, this);
            Model m = null;
            try {
                Constructor c = c_.getDeclaredConstructor();
                if (!c.isAccessible()) {
                    c.setAccessible(true);
                }
                m = (Model)c.newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Cannot init model class", e);
            }
            if (null != m) {
                m.h_OnBatchDelete(this);
                m.deleteBlobsInBatch(this);
            }
            ds().delete(q_);
            if (null != m) {
                m.h_BatchDeleted(this);
            }
            postEvent_(MorphiaEvent.BATCH_DELETED, this);
            return l;
        }

        /**
         * Alias of countAll()
         *
         * @return
         */
        public long count() {
            return q_.countAll();
        }

        /**
         * Used to simulate JPA.find("byXXAndYY", ...);
         *
         * @param query
         *            could be either "Key1[AndKey2[AndKey3]]" or
         *            "byKey1[AndKey2[AndKey3]]" or "key1 key2 ..."
         *
         * @param params
         *            the number of params should either be exactly one or the
         *            number match the key number
         * @return
         */
        public MorphiaQuery findBy(String query, Object... params) {
            if (null == params) params = new Object[] {null};
            if (null == query || params.length == 0) {
                throw new IllegalArgumentException("Invalid query or params");
            }
            if (query.startsWith("by"))
                query = query.substring(2);
            String[] keys = query.split("(And|[,;\\s]+)");

            if ((params.length != 1) && (keys.length != params.length)) {
                throw new IllegalArgumentException(
                        "Query key number does not match the params number");
            }

            Object oneVal = params.length == 1 ? params[0] : null;

            for (int i = 0; i < keys.length; ++i) {
                StringBuilder sb = new StringBuilder(keys[i]);
                sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                q_.filter(sb.toString(), params.length > 1 ? params[i] : oneVal);
            }

            return this;
        }

        @Override
        public String toString() {
            return q_.toString();
        }

        // ---------------------------------------------------------------------------
        // JPAQuery style interfaces
        // ---------------------------------------------------------------------------
        public <T> T first() {
            return (T) get();
        }

        /**
         * Set the position to start
         *
         * @param position
         *            Position of the first element
         * @return A new query
         */
        public <T> MorphiaQuery from(int position) {
            q_.offset(position);
            return this;
        }

        /**
         * Retrieve all results of the query
         *
         * This is a correspondence to JPAQuery's fetch(), which however, used
         * as another method signature of Morphia Query
         *
         * @return A list of entities
         */
        public <T extends Model> List<T> fetchAll() {
            return (List<T>) q_.asList();
        }

        /**
         * Retrieve results of the query
         *
         * @param max
         *            Max results to fetch
         * @return A list of entities
         */
        public <T extends Model> List<T> fetch(int max) {
            return (List<T>) q_.limit(max).asList();
        }

        /**
         * Retrieve a page of result
         *
         * @param page
         *            Page number (start at 1)
         * @param length
         *            (page length)
         * @return a list of entities
         */
        public <T extends Model> List<T> fetch(int page, int length) {
            if (page < 1) {
                page = 1;
            }
            return (List<T>) q_.offset((page - 1) * length).limit(length)
                    .asList();
        }

        // ---------------------------------------------------------------------------
        // Morphia Query, QueryResults, Criteria, CriteriaContainer interface
        // ---------------------------------------------------------------------------

        // for the sake of enhancement
        public Model _get() {
            return q_.get();
        }

        public <T extends Model> T get() {
            return (T) q_.get();
        }

        public <T extends Model> MorphiaQuery filter(String condition,
                Object value) {
            q_.filter(condition, value);
            return this;
        }

        public <T extends Model> Key<T> getKey() {
            return (Key<T>) q_.getKey();
        }

        public <T extends Model> Iterator<T> iterator() {
            return (Iterator<T>) q_.iterator();
        }

        public <T extends Model> List<T> asList() {
            return (List<T>) q_.asList();
        }

        public <T extends Model> List<Key<T>> asKeyList() {
            return ((Query<T>) q_).asKeyList();
        }

        public <T extends Model> Iterable<T> fetch() {
            return (Iterable<T>) q_.fetch();
        }

        public Set<?> distinct(String key) {
            return new HashSet(col().distinct(key, getQueryObject()));
        }

        public Map<String, Long> cloud(String field) {
            String map = String.format("function() {if (!this.%s) return; for (index in this.%s) emit(this.tags[index], 1);}", field, field);
            String reduce = "function(previous, current) {var count = 0; for (index in current) count += current[index]; return count;}";
            MapReduceCommand cmd = new MapReduceCommand(col(), map, reduce, null, MapReduceCommand.OutputType.INLINE, q_.getQueryObject());
            MapReduceOutput out = col().mapReduce(cmd);
            Map<String, Long> m = new HashMap<String, Long>();
            for (Iterator<DBObject> itr = out.results().iterator(); itr.hasNext();) {
                DBObject dbo = itr.next();
                m.put((String)dbo.get("_id"), ((Double)dbo.get("value")).longValue());
            }
            return m;
        }

        /**
         *
         * @param groupKeys
         *            could be either "f1Andf2.." or "f1 f2" or "f1,f2"
         * @return
         */
        public List<BasicDBObject> group(String groupKeys, DBObject initial,
                String reduce, String finalize) {
            DBObject key = new BasicDBObject();
            if (!StringUtil.isEmpty(groupKeys)) {
                if (groupKeys.startsWith("by"))
                    groupKeys = groupKeys.substring(2);
                String[] sa = groupKeys.split("(And|[\\s,;]+)");
                for (String s : sa) {
                    key.put(s, true);
                }
            }
            return (List<BasicDBObject>) ds().getCollection(c_).group(key,
                    q_.getQueryObject(), initial, reduce, finalize);
        }

        private AggregationResult aggregate_(String field, DBObject initial,
                Long initVal, String reduce, String finalize,
                String... groupKeys) {
            if (null == initial)
                initial = new BasicDBObject();
            initial.put(field, initVal);
            return new AggregationResult(group(StringUtil.join(",", groupKeys),
                    initial, reduce, finalize), field);
        }

        public AggregationResult groupMax(String field, String... groupKeys) {
            String reduce = String
                    .format("function(obj, prev){if (obj.%s > prev.%s) prev.%s = obj.%s}",
                            field, field, field, field);
            return aggregate_(field, null, Long.MIN_VALUE + 1, reduce, null,
                    groupKeys);
        }

        public Long max(String maxField) {
            return groupMax(maxField).getResult();
        }

        public AggregationResult groupMin(String field, String... groupKeys) {
            String reduce = String
                    .format("function(obj, prev){if (obj.%s < prev.%s) prev.%s = obj.%s}",
                            field, field, field, field);
            return aggregate_(field, null, Long.MAX_VALUE - 1, reduce, null,
                    groupKeys);
        }

        public Long min(String minField) {
            return groupMin(minField).getResult();
        }

        public AggregationResult groupAverage(String field, String... groupKeys) {
            DBObject initial = new BasicDBObject();
            initial.put("__count", 0);
            initial.put("__sum", 0);
            String reduce = String.format(
                    "function(obj, prev){prev.__count++; prev.__sum+=obj.%s;}",
                    field);
            String finalize = String.format(
                    "function(prev) {prev.%s = prev.__sum / prev.__count;}",
                    field);
            return aggregate_(field, initial, 0L, reduce, finalize, groupKeys);
        }

        public Long average(String field) {
            return groupAverage(field).getResult();
        }

        public AggregationResult groupSum(String field, String... groupKeys) {
            String reduce = String.format(
                    "function(obj, prev){prev.%s+=obj.%s;}", field, field);
            return aggregate_(field, null, 0L, reduce, null, groupKeys);
        }

        public Long sum(String field) {
            return groupSum(field).getResult();
        }

        public AggregationResult groupCount(String field, String... groupKeys) {
            String reduce = String.format("function(obj, prev){prev.%s++;}", field);
            return aggregate_(field, null, 0L, reduce, null, groupKeys);
        }

        public <T extends Model> Iterable<T> fetchEmptyEntities() {
            return (Iterable<T>) q_.fetchEmptyEntities();
        }

        public <T extends Model> FieldEnd<? extends Query<T>> field(String field) {
            return (FieldEnd<? extends Query<T>>) q_.field(field);
        }

        public <T extends Model> Iterable<Key<T>> fetchKeys() {
            return ((Query<T>) q_).fetchKeys();
        }

        public <T extends Model> FieldEnd<? extends CriteriaContainerImpl> criteria(
                String field) {
            return q_.criteria(field);
        }

        public <T extends Model> CriteriaContainer and(Criteria... criteria) {
            return q_.and(criteria);
        }

        public long countAll() {
            return q_.countAll();
        }

        public <T extends Model> CriteriaContainer or(Criteria... criteria) {
            return q_.or(criteria);
        }

        public <T extends Model> MorphiaQuery where(String js) {
            q_.where(js);
            return this;
        }

        public <T extends Model> MorphiaQuery where(CodeWScope js) {
            q_.where(js);
            return this;
        }

        public <T extends Model> MorphiaQuery order(String condition) {
            q_.order(condition);
            return this;
        }

        public <T extends Model> MorphiaQuery limit(int value) {
            q_.limit(value);
            return this;
        }

        public <T extends Model> MorphiaQuery batchSize(int value) {
            q_.batchSize(value);
            return this;
        }

        public <T extends Model> MorphiaQuery offset(int value) {
            q_.offset(value);
            return this;
        }

        @Deprecated
        public <T extends Model> MorphiaQuery skip(int value) {
            q_.skip(value);
            return this;
        }

        public <T extends Model> MorphiaQuery enableValidation() {
            q_.enableValidation();
            return this;
        }

        public <T extends Model> MorphiaQuery disableValidation() {
            q_.disableValidation();
            return this;
        }

        public <T extends Model> MorphiaQuery hintIndex(String idxName) {
            q_.hintIndex(idxName);
            return this;
        }

        public <T extends Model> MorphiaQuery retrievedFields(boolean include,
                String... fields) {
            q_.retrievedFields(include, fields);
            return this;
        }

        public <T extends Model> MorphiaQuery enableSnapshotMode() {
            q_.enableSnapshotMode();
            return this;
        }

        public <T extends Model> MorphiaQuery disableSnapshotMode() {
            q_.disableSnapshotMode();
            return this;
        }

        public <T extends Model> MorphiaQuery queryNonPrimary() {
            q_.queryNonPrimary();
            return this;
        }

        public <T extends Model> MorphiaQuery queryPrimaryOnly() {
            q_.queryPrimaryOnly();
            return this;
        }

        @Deprecated
        public <T extends Model> MorphiaQuery disableTimeout() {
            return disableCursorTimeout();
        }

        public <T extends Model> MorphiaQuery disableCursorTimeout() {
            q_.disableCursorTimeout();
            return this;
        }

        @Deprecated
        public <T extends Model> MorphiaQuery enableTimeout() {
            return enableCursorTimeout();
        }

        public <T extends Model> MorphiaQuery enableCursorTimeout() {
            q_.enableCursorTimeout();
            return this;
        }

        public Class<? extends Model> getEntityClass() {
            return q_.getEntityClass();
        }

        @Override
        public MorphiaQuery clone() {
            MorphiaQuery mq = new MorphiaQuery();
            mq.q_ = q_.clone();
            return mq;
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface ByPass {
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE })
    public @interface AutoTimestamp {
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface Column {
        /** The name of the key to store the field in; Defaults to the field name. */
        String value() default Mapper.IGNORED_FIELDNAME;

        /** Specify the concrete class to instantiate. */
        Class<?> concreteClass() default Object.class;
    }

    /**
     * NoID is used to annotate on sub types which is sure to get ID field from
     * parent type
     *
     * @see //groups.google.com/d/topic/play-framework/hPWJCvefPoI/discussion
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE })
    public @interface NoId {
    }

    /**
     * OnLoad mark a method be called after an new instance of an entity is initialized and
     * before the properties are filled with mongo db columns
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface OnLoad {
    }

    /**
     * OnLoad mark a method be called immediately after an entity loaded from mongodb
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface Loaded {
    }

    /**
     * OnAdd mark a method be called before an new entity is saved. If any exception get thrown
     * out in the method the entity will not be saved
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface OnAdd {
    }

    /**
     * OnUpdate mark a method be called before an existing entity is saved. If any exception get thrown
     * out in the method the entity will not be saved
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface OnUpdate {
    }

    /**
     * Added mark a method be called after an new entity is saved.
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface Added {
    }

    /**
     * Updated mark a method be called after an existing entity is saved.
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface Updated {
    }

    /**
     * OnDelete mark a method be called before an entity is deleted. If any exception throw out
     * in this method the entity will not be removed
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface OnDelete {
    }

    /**
     * Deleted mark a method be called after an entity is deleted
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface Deleted {
    }

    /**
     * OnBatchDelete mark a method be called before a query's delete method get called. If any exception throw out
     * in this method the query deletion will be canceled
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface OnBatchDelete {
    }

    /**
     * Deleted mark a method be called after an a query deletion executed
     *
     * @author luog
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface BatchDeleted {
    }

}


text:
#include <stdlib.h>

#include "cdx11.h"
#include "cdimage.h"

static void cdkillcanvas(cdCtxCanvas* ctxcanvas)
{
  cdxKillCanvas(ctxcanvas);
}

static void cdcreatecanvas(cdCanvas* canvas, void *data)
{
  cdCtxImage *ctximage = ((cdImage*)data)->ctximage;
  cdxCreateCanvas(canvas, ctximage->dpy, ctximage->scr, ctximage->img, ctximage->vis);
}

static void cdinittable(cdCanvas* canvas)
{
  cdxInitTable(canvas);

  canvas->cxKillCanvas = cdkillcanvas;
}

static cdContext cdImageContext =
{
  CD_CAP_ALL & ~(CD_CAP_PLAY | CD_CAP_YAXIS | CD_CAP_FPRIMTIVES | CD_CAP_PATH | CD_CAP_BEZIER ),
  CD_CTX_IMAGE,
  cdcreatecanvas,
  cdinittable,
  NULL,
  NULL
};

cdContext* cdContextImage(void)
{
  if (cdUseContextPlus(CD_QUERY))
  {
    cdContext* ctx = cdGetContextPlus(CD_CTXPLUS_IMAGE);
    if (ctx != NULL)
      return ctx;
  }

  return &cdImageContext;
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: aouicher
 * Date: 15/05/2014
 * Time: 11:17
 */

namespace Figaromedias\Bundle\PiagetBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class ItemAdmin extends Admin
{

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('id')
            ->add('titreItem')
            ->add('accrocheItem')
            ->add('numeroItem')
            ->add('dateItem')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('titreItem', null, array('label'=> 'Titre'))
            ->add('accrocheItem', null, array('label'=>'Accroche'))
            ->add('descriptionItem', null, array('label'=>'Description','attr'=>array('class'=>'tinymce')))
            ->add('numeroItem', null, array('label'=> 'Numéro'))
            ->add('dateItem', null, array('label'=> 'Date'))
            ->add('formatItem', 'choice', array(
                'choices' => array('g' => 'Grand', 'p' => 'Petit'),'label'=>'Format'
            ))
            ->add('couleurItem', 'choice', array(
                'choices' => array('#FFFFFF' => 'Blanc', '#B61C6E' => 'Rose'),'label'=>'Couleur chiffre'
            ))
            ->add('urlItem', null, array('label'=> 'Url'))
            ->add('PhotoUne', 'sonata_type_model_list', array('required' => false, 'label' => 'Photo Une', 'help'=>'Dimensions : 480px X 460px'), array(
                'link_parameters' => array()))
            ->add('PhotoBloc', 'sonata_type_model_list', array('required' => false, 'label' => 'Photo Bloc', 'help'=>'Dimensions : 100px X 100px'), array(
                'link_parameters' => array()))
            ->add('PhotoBlocOff', 'sonata_type_model_list', array('required' => false, 'label' => 'Photo Bloc Off (rose)', 'help'=>'Dimensions : 100px X 100px'), array(
                'link_parameters' => array()))
        ;
    }

    /**
     * @param ShowMapper $showMapper
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('id')
            ->add('titreItem', null, array('label'=> 'Titre'))
            ->add('accrocheItem', null, array('label'=> 'Accroche'))
            ->add('descriptionItem', null, array('label'=> 'Description'))
            ->add('numeroItem', null, array('label'=> 'Numéro'))
            ->add('dateItem', null, array('label'=> 'Date'))
            ->add('formatItem', null, array('label'=> 'Format'))
            ->add('urlItem', null, array('label'=> 'Url'))
            ->add('PhotoUne', null, array('label'=> 'Photo Une'))
            ->add('PhotoBloc', null, array('label'=> 'Photo Bloc'))
            ->add('PhotoBlocOff', null, array('label'=> 'Photo Bloc'))
        ;
    }
}


text:
require 'debox/command/base'

class Debox::Command::Status < Debox::Command::Base

  help :index, text: 'Show server status'
  def index
    status = Debox::API.status
    puts status
  end

end


text:
INSTALL=/usr/local/srs

##################################################################################
##################################################################################
##################################################################################
# discover the current work dir, the log and access.
echo "argv[0]=$0"
if [[ ! -f $0 ]]; then
    echo "directly execute the scripts on shell.";
    work_dir=`pwd`
else
    echo "execute scripts in file: $0";
    work_dir=`dirname $0`; work_dir=`(cd ${work_dir} && pwd)`
fi
product_dir=$work_dir

log="${work_dir}/logs/package.`date +%s`.log" && . ${product_dir}/scripts/_log.sh && check_log
ret=$?; if [[ $ret -ne 0 ]]; then exit $ret; fi

# user must stop service first.
ok_msg "check previous install"
if [[ -f /etc/init.d/srs ]]; then
    /etc/init.d/srs status >/dev/null 2>&1
    ret=$?; if [[ 0 -eq ${ret} ]]; then
        failed_msg "you must stop the service first: sudo /etc/init.d/srs stop";
        exit 1;
    fi
fi
ok_msg "previous install checked"

# backup old srs
ok_msg "backup old srs"
install_root=$INSTALL
install_bin=$install_root/objs/srs
if [[ -d $install_root ]]; then
    version="unknown"
    if [[ -f $install_bin ]]; then
        version=`$install_bin -v 2>/dev/stdout 1>/dev/null`
    fi

    backup_dir=${install_root}.`date "+%Y-%m-%d_%H-%M-%S"`.v-$version
    ok_msg "backup installed dir, version=$version"
    ok_msg "    to=$backup_dir"
    mv $install_root $backup_dir >>$log 2>&1
    ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "backup installed dir failed"; exit $ret; fi
    ok_msg "backup installed dir success"
fi
ok_msg "old srs backuped"

# prepare files.
ok_msg "prepare files"
(
    sed -i "s|^ROOT=.*|ROOT=\"${INSTALL}\"|g" $work_dir/${INSTALL}/etc/init.d/srs
) >> $log 2>&1
ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "prepare files failed"; exit $ret; fi
ok_msg "prepare files success"

# copy core files
ok_msg "copy core components"
(
    mkdir -p $install_root
    cp -r $work_dir/${INSTALL}/conf $install_root &&
    cp -r $work_dir/${INSTALL}/etc $install_root &&
    cp -r $work_dir/${INSTALL}/objs $install_root
) >>$log 2>&1
ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "copy core components failed"; exit $ret; fi
ok_msg "copy core components success"

# install init.d scripts
ok_msg "install init.d scripts"
(
    rm -rf /etc/init.d/srs &&
    ln -sf $install_root/etc/init.d/srs /etc/init.d/srs
) >>$log 2>&1
ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "install init.d scripts failed"; exit $ret; fi
ok_msg "install init.d scripts success"

# install system service
lsb_release --id|grep "CentOS" >/dev/null 2>&1; os_id_centos=$?
lsb_release --id|grep "Ubuntu" >/dev/null 2>&1; os_id_ubuntu=$?
lsb_release --id|grep "Debian" >/dev/null 2>&1; os_id_debian=$?
lsb_release --id|grep "Raspbian" >/dev/null 2>&1; os_id_rasabian=$?
if [[ 0 -eq $os_id_centos ]]; then
    ok_msg "install system service for CentOS"
    /sbin/chkconfig --add srs && /sbin/chkconfig srs on
    ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "install system service failed"; exit $ret; fi
    ok_msg "install system service success"
elif [[ 0 -eq $os_id_ubuntu ]]; then
    ok_msg "install system service for Ubuntu"
    update-rc.d srs defaults
    ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "install system service failed"; exit $ret; fi
    ok_msg "install system service success"
elif [[ 0 -eq $os_id_debian ]]; then
    ok_msg "install system service for Debian"
    update-rc.d srs defaults
    ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "install system service failed"; exit $ret; fi
    ok_msg "install system service success"
elif [[ 0 -eq $os_id_rasabian ]]; then
    ok_msg "install system service for RaspberryPi"
    update-rc.d srs defaults
    ret=$?; if [[ 0 -ne ${ret} ]]; then failed_msg "install system service failed"; exit $ret; fi
    ok_msg "install system service success"
else
    warn_msg "ignore and donot install system service for `lsb_release --id|awk '{print $3}'`."
fi

echo ""
echo "see: https://github.com/winlinvip/simple-rtmp-server/wiki/LinuxService"
echo "install success, you can:"
echo -e "${GREEN}      sudo /etc/init.d/srs start${BLACK}"

exit 0


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * MeanTevent Schema
 */
var MeanTeventSchema = new Schema({
	// MeanTevent model fields
	title:{
        type: String,
        default: "",
        required: 'Please fill Event title',
        trim: true
    },
    content:{
        type: String,
        default: "",
        required: 'Please fill Event title',
        trim : true
    },
    created : {
        type : Date ,
        default : Date . now
    },
    user : {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

mongoose.model('MeanTevent', MeanTeventSchema);


text:
"""Tests to make sure that the file-update-monitoring code is working properly

THIS TEST MODULE IS JUST A SHELL AT THE MOMENT. Feel like filling it in??

Meta-Data
================================================================================
Author: Tavis Rudd <tavis@damnsimple.com>,
Version: $Revision: 1.6 $
Start Date: 2001/10/01
Last Revision Date: $Date: 2002/10/01 17:52:03 $
"""
__author__ = "Tavis Rudd <tavis@damnsimple.com>"
__revision__ = "$Revision: 1.6 $"[11:-2]

##################################################
## DEPENDENCIES ##

import sys
import types
import os
import os.path

import unittest_local_copy as unittest
from Cheetah.Template import Template

##################################################
## CONSTANTS & GLOBALS ##

try:
    True,False
except NameError:
    True, False = (1==1),(1==0)

##################################################
## TEST DATA FOR USE IN THE TEMPLATES ##

##################################################
## TEST BASE CLASSES

class TemplateTest(unittest.TestCase):
    pass

##################################################
## TEST CASE CLASSES

##################################################
## if run from the command line ##

if __name__ == '__main__':
    unittest.main()


text:
package de.plushnikov.intellij.plugin.psi;

import com.intellij.lang.Language;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.light.LightParameterListBuilder;

import java.util.Arrays;

public class LombokLightParameterListBuilder extends LightParameterListBuilder {
  public LombokLightParameterListBuilder(PsiManager manager, Language language) {
    super(manager, language);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    LombokLightParameterListBuilder that = (LombokLightParameterListBuilder) o;

    return Arrays.equals(getParameters(), that.getParameters());
  }

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


text:
namespace("jssynth");

jssynth.Global = {};

jssynth.Global.clone = function(obj) {
    var newObj = {};
};

jssynth.Global.merge = function(existingObj, toMerge) {
};

jssynth.Global.makeArrayOf = function (value, length) {
};

jssynth.Global.additiveSynth = function(length, sampleRate, baseFreq, harmonics, globalVolume, state) {
	new jssynth.player.S3MLoader();
	new jssynth.Instrument();
};


text:
FPSCamera::FPSCamera(ds::Camera* camera) : _camera(camera) {
	_lastMousePos = ds::getMousePosition();
	_speed = 10.0f;
	buildView();
}

FPSCamera::~FPSCamera() {

}

void FPSCamera::setPosition(const ds::vec3& pos, const ds::vec3& target) {
	_camera->position = pos;
	_camera->target = target;
	buildView();
}

void FPSCamera::setPosition(const ds::vec3& pos) {
	_camera->position = pos;
	buildView();
}

void FPSCamera::move(float unit) {
	_camera->position += _camera->target * unit;
	buildView();
}

void FPSCamera::strafe(float unit) {
	_camera->position += _camera->right * unit;
	buildView();
}

void FPSCamera::up(float unit) {
	ds::vec3 tmp = _camera->up * unit;
	_camera->position = _camera->position + tmp;
	buildView();
}

void FPSCamera::setPitch(float angle) {
	ds::matrix R = ds::matRotation(_camera->right,angle);
	_camera->up = ds::matTransformNormal(_camera->up, R);
	_camera->target = ds::matTransformNormal(_camera->target, R);
	buildView();
}

void FPSCamera::resetYaw(float angle) {
	_camera->yaw = angle;
	ds::matrix R = ds::matRotationZ(_camera->yaw);
	_camera->right = R * ds::vec3(1, 0, 0);
	_camera->target = R * ds::vec3(0, 0, 1);
	buildView();
}

void FPSCamera::setYaw(float angle) {
	ds::matrix R = ds::matRotationY(angle);
	_camera->right = ds::matTransformNormal(_camera->right, R);
	_camera->up = ds::matTransformNormal(_camera->up, R);
	_camera->target = ds::matTransformNormal(_camera->target, R);
	buildView();
}

void FPSCamera::resetPitch(float angle) {
	_camera->pitch = angle;
	ds::matrix R = ds::matRotationY(_camera->pitch);
	_camera->right = R * ds::vec3(1, 0, 0);
	_camera->target = R * ds::vec3(0, 0, 1);
	buildView();
}

void FPSCamera::update(float elapsedTime) {
	if (ds::isKeyPressed('W')) {
		move(5.0f*elapsedTime);
	}
	if (ds::isKeyPressed('S')) {
		move(-5.0f*elapsedTime);
	}
	if (ds::isKeyPressed('A')) {
		strafe(-5.0f*elapsedTime);
	}
	if (ds::isKeyPressed('D')) {
		strafe(5.0f*elapsedTime);
	}
	if (ds::isKeyPressed('Q')) {
		up(5.0f*elapsedTime);
	}
	if (ds::isKeyPressed('E')) {
		up(-5.0f*elapsedTime);
	}
	ds::vec2 mp = ds::getMousePosition();
	if (ds::isMouseButtonPressed(0)) {
		// Make each pixel correspond to a quarter of a degree.
		//float dx = DEGTORAD(0.25f*(mp.x - _lastMousePos.x));
		//float dy = DEGTORAD(0.25f*(mp.y - _lastMousePos.y));
		float dx = DEGTORAD(0.25f*(_lastMousePos.x - mp.x));
		float dy = DEGTORAD(0.25f*(mp.y - _lastMousePos.y));
		setPitch(dy);
		setYaw(dx);
	}
	_lastMousePos.x = mp.x;
	_lastMousePos.y = mp.y;

}

void FPSCamera::buildView() {
	ds::rebuildCamera(_camera);
}


text: Smartenit ZBMSKT1 Model #4035A


text:
/* Private Variables */

var isReady = false,
	styleAnchor,
	ensureQueues = {},
	readyQueue = new Palo.Queue(),
	requests = [],
	handlers = [];

/* Private Functions */

/**
 * Handle document ready events.
 */
function onReady() {
	// Prevent running more than once
	if ( !isReady ) {
		// Callbacks passed to Palo.ready during this loop will be executed when the loop's done
		isReady = true;
		// Execute queued callbacks
		readyQueue.execute();
	}
}

/**
 * Add a CSS stylesheet to the document.
 *
 * @param {string} cssText CSS text to add
 * @param {string} [media] Media to apply stylesheet to
 */
function addStylesheet( css, media ) {
	var element = document.createElement( 'style' );

	styleAnchor.parentNode.insertBefore( element, styleAnchor );
	element.rel = 'stylesheet';
	if ( media && media !== 'all' ) {
		element.media = media;
	}
	if ( element.styleSheet ) {
		// IE
		element.styleSheet.cssText = css;
	} else {
		// Other browsers.
		// (Safari sometimes borks on non-string values,
		// play safe by casting to a string, just in case.)
		element.appendChild( document.createTextNode( String( css ) ) );
	}
}

/**
 * Add a stylesheet link to the document.
 *
 * @param {string} href URL of stylesheet
 * @param {string} [media] Media to apply stylesheet to
 */
function addStylesheetLink( href, media ) {
	var element = document.createElement( 'link' );

	// For IE: Insert in document *before* setting href
	styleAnchor.parentNode.insertBefore( element, styleAnchor );
	element.rel = 'stylesheet';
	if ( media && media !== 'all' ) {
		element.media = media;
	}
	// If you end up here from an IE exception "SCRIPT: Invalid property value.",
	// see #addEmbeddedCSS, wikimedia bug 31676, and wikimedia bug 47277 for details.
	element.href = href;
}

/**
 * Add a script to the document.
 *
 * Until the document is ready, scripts will be added using document.write; afterward the DOM API
 * will be used instead.
 *
 * @param {string} src URL of script
 */
function addScript( src ) {
	var element;

	if ( isReady ) {
		element = document.createElement( 'script' );
		element.src = src;
		document.body.appendChild( element );
	} else {
		/*jshint evil:true */
		document.write( '\u003Cscript src="' + src + '"\u003E\u003C/script\u003E' );
	}
}

/**
 * Request packages from server.
 *
 * Package requests are queued until the callstack clears, allowing clusters of calls to request to
 * be batched automatically.
 *
 * @param {string[]} names Names of packages to load from server
 */
function request( names ) {
	requests.push.apply( requests, names );
	setTimeout( fetch );
}

/**
 * Fetch packages from server.
 *
 * Called by `request` to carry out loading of packages from server after the callstack clears.
 * After calling this method `requests` will be cleared, making it safe to call it repeatedly.
 * Do not call this directly, use `request` instead.
 */
function fetch() {
	var i, time;

	if ( requests.length ) {
		// Calculate time of most recently changed initial package
		time = 0;
		i = requests.length;
		while ( i-- ) {
			time = Math.max( time, Palo.packages[requests[i]].time );
		}

		addScript( Palo.uri + '/packages/' + requests.join( ';' ) + '?t=' + time );
		requests = [];
	}
}

/**
 * Resolve a local module ID.
 *
 * Example:
 *     resolve( './a/b/c', './test' ) === './a/b/test'
 *     resolve( './a/b/c', '../test' ) === './a/test'
 *     resolve( './a/b/c', '../../test' ) === './test'
 *     resolve( './a/b/c', './c/d/e' ) === './a/b/c/d/e'
 *
 * @param {string} abs Absolute path
 * @param {string} rel Relative path
 * @return {string} Resolved path
 */
function resolveModuleId( abs, rel ) {
	var i, len, pos,
		a = abs.replace( '/^', '' ).split( '/' ),
		b = rel.replace( '/^', '' ).split( '/' );

	a.pop();
	for ( i = 0, len = b.length; i < len; i++ ) {
		if ( b[i] === '..' ) {
			a.pop();
		} else if ( b[i] !== '.' ) {
			a.push( b[i] );
		}
	}
	return a.join( '/' );
}

function require( name, id, parent ) {
	id = id !== undefined ? id : '.';

	var factory,
		pkg = Palo.packages[name],
		mod = pkg && pkg.res.modules && pkg.res.modules[id];

	if ( !pkg ) {
		throw new Error(
			'Cannot require; package has not been registered: ' +
			[ name, id ].join( '/' )
		);
	}

	if ( !mod ) {
		throw new Error(
			'Cannot execute; module not implemented: ' +
			[ name, id ].join( '/' )
		);
	}

	if ( !Palo.done[name] ) {
		throw new Error( 'Cannot execute; package dependencies have not been met: ' + name );
	}

	if ( typeof mod === 'function' ) {
		factory = mod;
		pkg.res.modules[id] = mod = {
			exports: {},
			id: id,
			parent: Palo.packages[parent],
			children: [],
			main: id === '.',
			loaded: false,
			require: function ( rel ) {
				rel = rel.split( '/' );
				return rel[0] === '.' || rel[0] === '..' ?
					// Module in this package
					require( name, resolveModuleId( id, rel.join( '/' ) ) ) :
					// Module in another package
					require( rel.pop(), rel.length ? rel.join( '/' ) : undefined );
			}
		};
		mod.require.ensure = Palo.ensure;
		if ( parent ) {
			Palo.packages[parent].children.push( mod );
		}
		factory( mod.require, mod.exports, mod, window );
		mod.loaded = true;
	}

	return mod.exports;
}

/* Methods */

/**
 * Add a resource handler to be executed during package implementation.
 *
 * Handlers are used before stylesheets are added and the main module of a package is executed.
 *
 * @param {Function} callback Resource handling function
 * @param {Object} [callback.package] Package being implemented
 */
Palo.use = function ( callback ) {
	handlers.push( callback );
};

/**
 * Run a callback when the document is ready.
 *
 * @param {Function} callback Callback to execute
 */
Palo.ready = function ( callback ) {
	if ( isReady ) {
		// Run immediately when ready has already completed
		setTimeout( callback );
	} else {
		// Queue callback for later
		readyQueue.add( callback );
		if ( document.readyState === 'complete' ) {
			// Fire ready since document appears to be ready now
			setTimeout( onReady );
		}
	}
};

/**
 * Define a package.
 *
 * Packages that are not provided by the server must be defined before being used. If the `res`
 * argument is used, the package will also be implemented.
 *
 * @param {string} name Name of package being defined
 * @param {string[]} deps Names of packages the package being defined depends on
 * @param {Object} [res] Package resources being implemented
 * @throws {Error} If package name has already been registered
 */
Palo.define = function ( name, deps, res ) {
	var i, len;

	if ( Palo.packages[name] ) {
		throw new Error( 'Cannot register; package has already been registered: ' + name );
	}

	// Store meta information
	Palo.packages[name] = { name: name, time: Date.now(), deps: deps };

	// Add package to dependent lists
	for ( i = 0, len = deps.length; i < len; i++ ) {
		if ( !Palo.dependents[deps[i]] ) {
			Palo.dependents[deps[i]] = [ name ];
		} else {
			Palo.dependents[deps[i]].push( name );
		}
	}

	if ( res ) {
		Palo.implement( name, res );
	}
};

/**
 * Implemented resources for a registered package.
 *
 * @param {[type]} name [description]
 * @param {[type]} res [description]
 * @return {[type]} [description]
 */
Palo.implement = function ( name, res ) {
	var pkg = Palo.packages[name];

	if ( !pkg ) {
		throw new Error( 'Cannot implement; package has not been registered: ' + name );
	}
	if ( pkg.res ) {
		throw new Error( 'Cannot implement; package has already been implemented: ' + name );
	}

	// Store resources
	pkg.res = res;

	// Mark as resolving
	delete Palo.loading[name];
	Palo.resolving[name] = true;

	// Execute when all dependencies are met
	Palo.ensure( pkg.deps, function () {
		var i, len, media, modules, stylesheets,
			res = pkg && pkg.res;

		if ( !pkg ) {
			throw new Error( 'Cannot execute; package has not been registered: ' + name );
		}

		if ( !res ) {
			throw new Error( 'Cannot execute; package has not been implemented: ' + name );
		}

		// Mark as done
		delete Palo.resolving[name];
		Palo.done[name] = true;

		// Handle package resources
		for ( i = 0, len = handlers.length; i < len; i++ ) {
			handlers[i]( pkg );
		}

		// Add stylesheets
		stylesheets = pkg.res.stylesheets;
		if ( stylesheets ) {
			for ( media in stylesheets ) {
				addStylesheet( stylesheets[media], media );
			}
		}

		// Execute main module
		modules = pkg.res.modules;
		if ( modules ) {
			require( pkg.name );
		}

		// Resolve dependent pacakages
		if ( ensureQueues[name] ) {
			ensureQueues[name].execute( name );
			delete ensureQueues[name];
		}
	} );
};

/**
 * Ensure modules are accessible before executing a callback.
 *
 * The callback will be given an argument that is equivilent to calling require() with each of the
 * requested package names in the `names` argument, in the same order.
 *
 * @param {string[]} names Names of modules
 * @param {Function} callback Function to call
 */
Palo.ensure = function ( names, callback ) {
	var i, len, name,
		req = names.slice(),
		wait = [],
		load = [];

	// Collect packages needing to be loaded
	for ( i = 0, len = names.length; i < len; i++ ) {
		name = names[i];
		if ( !Palo.done[name] ) {
			// Prevent duplicates
			if ( wait.indexOf( name ) === -1 ) {
				wait.push( name );
			}
		}
		if ( Palo.available[name] ) {
			// Prevent duplicates
			if ( load.indexOf( name ) === -1 ) {
				load.push( name );
			}
			// Mark as loading
			delete Palo.available[name];
			Palo.loading[name] = true;
		}

		// Add dependencies - adjust `len` since `push` makes `names` longer
		len = names.push.apply( names, Palo.packages[name].deps );
	}

	function resolveRequestedPackages( name ) {
		var index;

		// Reduce wait list
		index = wait.indexOf( name );
		if ( index !== -1 ) {
			wait.splice( index, 1 );
		}

		// Callback when done
		if ( !wait.length ) {
			callback.apply( null, req.map( function ( name ) {
				return Palo.packages[name].res.modules ? require( name ) : null;
			} ) );
		}
	}

	if ( wait.length ) {
		// Setup queues to trigger resolution when dependencies are met
		for ( i = 0, len = wait.length; i < len; i++ ) {
			name = wait[i];
			if ( !ensureQueues[name] ) {
				ensureQueues[name] = new Palo.Queue();
			}
			ensureQueues[name].add( resolveRequestedPackages );
		}
		// Request packages that still need to be loaded
		if ( load.length ) {
			request( load.slice() );
		}
	} else {
		resolveRequestedPackages();
	}
};

/* Initialization */

( function init() {
	var i, len, pkg, name, element, elements, resources;

	// Find or create an insertion point for dynamically added stylesheets
	elements = document.getElementsByTagName( 'meta' );
	for ( i = 0, len = elements.length; i < len; i++ ) {
		element = elements[i];
		if ( element.getAttribute( 'name' ) === 'PaloDynamicStylesheets' ) {
			styleAnchor = element;
			break;
		}
	}
	if ( !styleAnchor ) {
		element = document.createElement( 'meta' );
		element.setAttribute( 'name', 'PaloDynamicStylesheets' );
		document.getElementsByTagName( 'head' )[0].appendChild( element );
		styleAnchor = element;
	}

	// Listen for the document becoming ready
	if ( document.addEventListener ) {
		// Use DOMContentLoaded event when possible
		document.addEventListener( 'DOMContentLoaded', onReady, false );
		// Use window load event as fallback
		window.addEventListener( 'load', onReady, false );
	} else {
		// IE
		document.attachEvent( 'onreadystatechange', function () {
			if ( document.readyState === 'complete' ) {
				onReady();
			}
		} );
		window.attachEvent( 'onload', onReady );
	}
} )();


text:
some base/utility classes for golang
  - logr -logging more like log4j built on top of `logrus` and a
  - config - rudimentary config file->map

### setup

    go get github.com/Sirupsen/logrus


text:
const lighthouse = require('lighthouse')
const chromeLauncher = require('chrome-launcher')

const TIME_FOR_LIGHTHOUSE_FULL_TEST = 60000
jest.setTimeout(TIME_FOR_LIGHTHOUSE_FULL_TEST)

const launchChromeAndRunLighthouse = async url => {
  const chrome = await chromeLauncher.launch({ chromeFlags: [] })
  const opts = { chromeFlags: [], port: chrome.port }
  const configJSON = null
  const results = await lighthouse(url, opts, configJSON)
  await chrome.kill()
  return results
}

const buildLighthouseReport = results => {
  const { categories } = results.lhr
  let rows = ''
  const scores = Object.values(categories).map(({ score }) => score * 100)
  const lighthouseScore = scores.reduce((a, b) => a + b, 0) / scores.length

  Object.values(categories).forEach(cat => {
    rows += `| ${cat.title} | ${cat.score * 100} |\n`
  })
  console.log('Total Lighthouse score is : ', lighthouseScore)
  console.log(rows)

  return { lighthouseScore, categories }
}

test('Article 85 : Meaningful first paint score', () =>
  launchChromeAndRunLighthouse('https://fr-recontact-test.netlify.app/articles/85')
    .then(buildLighthouseReport)
    .then(report => {
      const { categories, lighthouseScore } = report

      expect(lighthouseScore).toBeGreaterThanOrEqual(72) // 78, 74
      expect(categories.performance.score * 100).toBeGreaterThanOrEqual(40) // 64, 65, 64, 40 (-4 just in case)
      expect(categories.accessibility.score * 100).toBeGreaterThanOrEqual(84) // 84
      expect(categories['best-practices'].score * 100).toBeGreaterThanOrEqual(93) // 93
      expect(categories.seo.score * 100).toBeGreaterThanOrEqual(100) // 100
      expect(categories.pwa.score * 100).toBeGreaterThanOrEqual(44) // 56, 44
    }))

test('HomePage : Meaningful first paint score', () =>
  launchChromeAndRunLighthouse('https://en-recontact-test.netlify.app')
    .then(buildLighthouseReport)
    .then(report => {
      const { categories, lighthouseScore } = report

      expect(lighthouseScore).toBeGreaterThanOrEqual(83) // 86

      expect(categories.performance.score * 100).toBeGreaterThanOrEqual(70) // 78, 75, 71 => 70

      expect(categories.accessibility.score * 100).toBeGreaterThanOrEqual(98) // 96
      expect(categories['best-practices'].score * 100).toBeGreaterThanOrEqual(93) // 93
      expect(categories.seo.score * 100).toBeGreaterThanOrEqual(100) // 100
      expect(categories.pwa.score * 100).toBeGreaterThanOrEqual(100) // 100
    }))

test('Articles : Meaningful first paint score', () =>
  launchChromeAndRunLighthouse('https://en-recontact-test.netlify.app/articles')
    .then(buildLighthouseReport)
    .then(report => {
      const { categories, lighthouseScore } = report

      expect(lighthouseScore).toBeGreaterThanOrEqual(83) // 86

      expect(categories.performance.score * 100).toBeGreaterThanOrEqual(85) // 94, 93, 95, 90 (-10 just in case)
      expect(categories.accessibility.score * 100).toBeGreaterThanOrEqual(96) // 96
      expect(categories['best-practices'].score * 100).toBeGreaterThanOrEqual(100) // 100
      expect(categories.seo.score * 100).toBeGreaterThanOrEqual(100) // 100
      expect(categories.pwa.score * 100).toBeGreaterThanOrEqual(74) // 74
    }))