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

using Grasshopper.Kernel;
using Rhino.Geometry;
using Rhino.Runtime;
using Grasshopper.Kernel.Types;
using Rhino.Collections;
using System.Diagnostics;
using Grasshopper.Kernel.Parameters;
using System.Linq;

namespace UserDataUtils
{
    public class ExpandUserDataComponent : GH_Component, IGH_VariableParameterComponent
    {
        Dictionary<string, List<object>> global;
        Action expireComponent, setInputsAndExpireComponent;

        /// <summary>
        /// Initializes a new instance of the MyComponent1 class.
        /// </summary>
        public ExpandUserDataComponent()
          : base("Expand User Data", "EUD",
              "Expands user dictionaries into their component keys (if matching).",
              "Speckle", "User Data Utils")
        {
            expireComponent = () =>
            {
                this.ExpireSolution(true);
            };

            setInputsAndExpireComponent = () =>
            {
                for (int i = Params.Output.Count - 1; i >= 0; i--)
                {
                    var myParam = Params.Output[i];
                    if ((!global.Keys.Contains(myParam.Name)) || (!global.Keys.Contains(myParam.NickName)))
                    {
                        Params.UnregisterOutputParameter(myParam, true);
                    }
                }

                Params.OnParametersChanged();
                foreach (var key in global.Keys)
                {
                    var myparam = Params.Output.FirstOrDefault(q => q.Name == key);
                    if (myparam == null)
                    {
                        Param_GenericObject newParam = getGhParameter(key);
                        Params.RegisterOutputParam(newParam);
                    }
                }

                Params.OnParametersChanged();
                //end
                this.ExpireSolution(true);
            };
        }

        public override void AddedToDocument(GH_Document document)
        {
            base.AddedToDocument(document);
            Debug.WriteLine(this.Params.Output.Count);
        }

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
        {
            pManager.AddGenericParameter("Dictionaries", "D", "Dictionaries to expand.", GH_ParamAccess.tree);
        }

        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
        {
        }

        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<object> objs = new List<object>();
            objs = Params.Input[0].VolatileData.AllData(true).ToList<object>();
            if (objs.Count == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No dictionaries found.");
                return;
            }

            global = new Dictionary<string, List<object>>();
            var first = true;

            foreach (var obj in objs)
            {
                GH_ObjectWrapper goo = obj as GH_ObjectWrapper;
                if (goo == null)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Provided object not a dictionary.");
                    return;
                }
                ArchivableDictionary dict = goo.Value as ArchivableDictionary;
                if (dict != null)
                {
                    foreach (var key in dict.Keys)
                    {
                        if ((first))
                        {
                            global.Add(key, new List<object>());
                            global[key].Add(dict[key]);
                        }

                        else if (!global.Keys.Contains(key))
                        {
                            this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Object dictionaries do not match.");
                            return;
                        } else
                        {
                            global[key].Add(dict[key]);
                        }
                    }
                }
                first = false;
            }

            if (global.Keys.Count == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Empty dictionary.");
                return;
            }

            var changed = false;

            if (Params.Output.Count != global.Keys.Count)
            {
                changed = true;
            }

            Debug.WriteLine("changed:" + changed);

            if (changed)
            {
                Rhino.RhinoApp.MainApplicationWindow.Invoke(setInputsAndExpireComponent);
            }
            else
            {
                int k = 0;
                foreach (var key in global.Keys)
                {
                    Params.Output[k].Name = Params.Output[k].NickName = key;
                    DA.SetDataList(k++, global[key]);
                }
            }
        }

        private Param_GenericObject getGhParameter(string key)
        {
            Param_GenericObject newParam = new Param_GenericObject();
            newParam.Name = (string)key;
            newParam.NickName = (string)key;
            newParam.MutableNickName = false;
            newParam.Access = GH_ParamAccess.list;
            return newParam;
        }

        bool IGH_VariableParameterComponent.CanInsertParameter(GH_ParameterSide side, Int32 index)
        {
            return false;
        }
        bool IGH_VariableParameterComponent.CanRemoveParameter(GH_ParameterSide side, Int32 index)
        {
            return false;
        }
        bool IGH_VariableParameterComponent.DestroyParameter(GH_ParameterSide side, Int32 index)
        {
            return false;
        }
        IGH_Param IGH_VariableParameterComponent.CreateParameter(GH_ParameterSide side, Int32 index)
        {
            return null;
        }

        public void VariableParameterMaintenance()
        {
        }

        /// <summary>
        /// Provides an Icon for the component.
        /// </summary>
        protected override System.Drawing.Bitmap Icon
        {
            get
            {
                return Properties.Resources.ExpandUserData;
            }
        }

        /// <summary>
        /// Gets the unique ID for this component. Do not change this ID after release.
        /// </summary>
        public override Guid ComponentGuid
        {
            get { return new Guid("{b678aa1d-393b-4287-aa5a-9d8123cb033e}"); }
        }
    }
}


text:
package com.intellij.ide.actions.searcheverywhere;

import com.intellij.ide.util.gotoByName.ChooseByNameFilterConfiguration;
import com.intellij.util.containers.ContainerUtil;
import consulo.ui.image.Image;
import javax.annotation.Nonnull;

import java.util.List;
import java.util.function.Function;

public class PersistentSearchEverywhereContributorFilter<T> {

  private final ChooseByNameFilterConfiguration<? super T> myPersistentConfiguration;
  private final List<T> myElements;
  private final Function<? super T, String> myTextExtractor;
  private final Function<? super T, ? extends Image> myIconExtractor;

  public PersistentSearchEverywhereContributorFilter(@Nonnull List<T> elements,
                                                     @Nonnull ChooseByNameFilterConfiguration<? super T> configuration,
                                                     Function<? super T, String> textExtractor,
                                                     Function<? super T, ? extends Image> iconExtractor) {
    myElements = elements;
    myPersistentConfiguration = configuration;
    myTextExtractor = textExtractor;
    myIconExtractor = iconExtractor;
  }

  public List<T> getAllElements() {
    return myElements;
  }

  public List<T> getSelectedElements() {
    return ContainerUtil.filter(myElements, myPersistentConfiguration::isFileTypeVisible);
  }

  public boolean isSelected(T element) {
    return myPersistentConfiguration.isFileTypeVisible(element);
  }

  public void setSelected(T element, boolean selected) {
    myPersistentConfiguration.setVisible(element, selected);
  }

  public String getElementText(T element) {
    return myTextExtractor.apply(element);
  }

  public Image getElementIcon(T element) {
    return myIconExtractor.apply(element);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.catalina.tribes.tipis;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.catalina.tribes.Channel;
import org.apache.catalina.tribes.ChannelException;
import org.apache.catalina.tribes.ChannelException.FaultyMember;
import org.apache.catalina.tribes.ChannelListener;
import org.apache.catalina.tribes.Heartbeat;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.MembershipListener;
import org.apache.catalina.tribes.group.Response;
import org.apache.catalina.tribes.group.RpcCallback;
import org.apache.catalina.tribes.group.RpcChannel;
import org.apache.catalina.tribes.io.XByteBuffer;
import org.apache.catalina.tribes.membership.MemberImpl;
import org.apache.catalina.tribes.util.Arrays;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

/**
 *
 * @author Filip Hanik
 * @version 1.0
 */
public abstract class AbstractReplicatedMap extends ConcurrentHashMap implements RpcCallback, ChannelListener, MembershipListener, Heartbeat {
    private static final long serialVersionUID = 1L;

    private static final Log log = LogFactory.getLog(AbstractReplicatedMap.class);

    /**
     * The default initial capacity - MUST be a power of two.
     */
    public static final int DEFAULT_INITIAL_CAPACITY = 16;

    /**
     * The load factor used when none specified in constructor.
     **/
    public static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * Used to identify the map
     */
    private static final Charset CHARSET_ISO_8859_1 =
        Charset.forName("ISO-8859-1");

//------------------------------------------------------------------------------
//              INSTANCE VARIABLES
//------------------------------------------------------------------------------
    protected abstract int getStateMessageType();

    /**
     * Timeout for RPC messages, how long we will wait for a reply
     */
    protected transient long rpcTimeout = 5000;
    /**
     * Reference to the channel for sending messages
     */
    protected transient Channel channel;
    /**
     * The RpcChannel to send RPC messages through
     */
    protected transient RpcChannel rpcChannel;
    /**
     * The Map context name makes this map unique, this
     * allows us to have more than one map shared
     * through one channel
     */
    protected transient byte[] mapContextName;
    /**
     * Has the state been transferred
     */
    protected transient boolean stateTransferred = false;
    /**
     * Simple lock object for transfers
     */
    protected transient Object stateMutex = new Object();
    /**
     * A list of members in our map
     */
    protected transient HashMap<Member, Long> mapMembers = new HashMap<Member, Long>();
    /**
     * Our default send options
     */
    protected transient int channelSendOptions = Channel.SEND_OPTIONS_DEFAULT;
    /**
     * The owner of this map, ala a SessionManager for example
     */
    protected transient MapOwner mapOwner;
    /**
     * External class loaders if serialization and deserialization is to be performed successfully.
     */
    protected transient ClassLoader[] externalLoaders;

    /**
     * The node we are currently backing up data to, this index will rotate
     * on a round robin basis
     */
    protected transient int currentNode = 0;

    /**
     * Since the map keeps internal membership
     * this is the timeout for a ping message to be responded to
     * If a remote map doesn't respond within this timeframe,
     * its considered dead.
     */
    protected transient long accessTimeout = 5000;

    /**
     * Readable string of the mapContextName value
     */
    protected transient String mapname = "";

//------------------------------------------------------------------------------
//              map owner interface
//------------------------------------------------------------------------------

    public static interface MapOwner {
        // a typo, should have been "objectMadePrimary"
        public void objectMadePrimay(Object key, Object value);
    }

//------------------------------------------------------------------------------
//              CONSTRUCTORS
//------------------------------------------------------------------------------

    /**
     * Creates a new map
     * @param channel The channel to use for communication
     * @param timeout long - timeout for RPC messags
     * @param mapContextName String - unique name for this map, to allow multiple maps per channel
     * @param initialCapacity int - the size of this map, see HashMap
     * @param loadFactor float - load factor, see HashMap
     * @param cls - a list of classloaders to be used for deserialization of objects.
     */
    public AbstractReplicatedMap(MapOwner owner,
                                 Channel channel,
                                 long timeout,
                                 String mapContextName,
                                 int initialCapacity,
                                 float loadFactor,
                                 int channelSendOptions,
                                 ClassLoader[] cls) {
        super(initialCapacity, loadFactor, 15);
        init(owner, channel, mapContextName, timeout, channelSendOptions, cls);

    }

    /**
     * Helper methods, wraps a single member in an array
     * @param m Member
     * @return Member[]
     */
    protected Member[] wrap(Member m) {
        if ( m == null ) return new Member[0];
        else return new Member[] {m};
    }

    /**
     * Initializes the map by creating the RPC channel, registering itself as a channel listener
     * This method is also responsible for initiating the state transfer
     * @param owner Object
     * @param channel Channel
     * @param mapContextName String
     * @param timeout long
     * @param channelSendOptions int
     * @param cls ClassLoader[]
     */
    protected void init(MapOwner owner, Channel channel, String mapContextName, long timeout, int channelSendOptions,ClassLoader[] cls) {
        log.info("Initializing AbstractReplicatedMap with context name:"+mapContextName);
        this.mapOwner = owner;
        this.externalLoaders = cls;
        this.channelSendOptions = channelSendOptions;
        this.channel = channel;
        this.rpcTimeout = timeout;

        this.mapname = mapContextName;
        //unique context is more efficient if it is stored as bytes
        this.mapContextName = mapContextName.getBytes(CHARSET_ISO_8859_1);
        if ( log.isTraceEnabled() ) log.trace("Created Lazy Map with name:"+mapContextName+", bytes:"+Arrays.toString(this.mapContextName));

        //create an rpc channel and add the map as a listener
        this.rpcChannel = new RpcChannel(this.mapContextName, channel, this);
        //add this map as a message listener
        this.channel.addChannelListener(this);
        //listen for membership notifications
        this.channel.addMembershipListener(this);

        try {
            //broadcast our map, this just notifies other members of our existence
            broadcast(MapMessage.MSG_INIT, true);
            //transfer state from another map
            transferState();
            //state is transferred, we are ready for messaging
            broadcast(MapMessage.MSG_START, true);
        } catch (ChannelException x) {
            log.warn("Unable to send map start message.");
            // remove listener from channel
            this.rpcChannel.breakdown();
            this.channel.removeChannelListener(this);
            this.channel.removeMembershipListener(this);
            throw new RuntimeException("Unable to start replicated map.",x);
        }
    }

    /**
     * Sends a ping out to all the members in the cluster, not just map members
     * that this map is alive.
     * @param timeout long
     * @throws ChannelException
     */
    protected void ping(long timeout) throws ChannelException {
        //send out a map membership message, only wait for the first reply
        MapMessage msg = new MapMessage(this.mapContextName,
                                        MapMessage.MSG_INIT,
                                        false,
                                        null,
                                        null,
                                        null,
                                        channel.getLocalMember(false),
                                        null);
        if ( channel.getMembers().length > 0 ) {
            try {
                //send a ping, wait for all nodes to reply
                Response[] resp = rpcChannel.send(channel.getMembers(),
                                                  msg, RpcChannel.ALL_REPLY,
                                                  (channelSendOptions),
                                                  (int) accessTimeout);
                for (int i = 0; i < resp.length; i++) {
                    memberAlive(resp[i].getSource());
                }
            } catch (ChannelException ce) {
                // Handle known failed members
                FaultyMember[] faultyMembers = ce.getFaultyMembers();
                for (FaultyMember faultyMember : faultyMembers) {
                    memberDisappeared(faultyMember.getMember());
                }
            }
        }
        //update our map of members, expire some if we didn't receive a ping back
        synchronized (mapMembers) {
            Iterator<Map.Entry<Member, Long>> it = mapMembers.entrySet().iterator();
            long now = System.currentTimeMillis();
            while ( it.hasNext() ) {
                Map.Entry<Member,Long> entry = it.next();
                long access = entry.getValue().longValue();
                if ( (now - access) > timeout ) {
                    it.remove();
                    memberDisappeared(entry.getKey());
                }
            }
        }//synch
    }

    /**
     * We have received a member alive notification
     * @param member Member
     */
    protected void memberAlive(Member member) {
        synchronized (mapMembers) {
            if (!mapMembers.containsKey(member)) {
                mapMemberAdded(member);
            } //end if
            mapMembers.put(member, new Long(System.currentTimeMillis()));
        }
    }

    /**
     * Helper method to broadcast a message to all members in a channel
     * @param msgtype int
     * @param rpc boolean
     * @throws ChannelException
     */
    protected void broadcast(int msgtype, boolean rpc) throws ChannelException {
        Member[] members = channel.getMembers();
        // No destination.
        if (members.length == 0 ) return;
        //send out a map membership message, only wait for the first reply
        MapMessage msg = new MapMessage(this.mapContextName, msgtype,
                                        false, null, null, null, channel.getLocalMember(false), null);
        if ( rpc) {
            Response[] resp = rpcChannel.send(members, msg,
                    RpcChannel.FIRST_REPLY, (channelSendOptions), rpcTimeout);
            if (resp.length > 0) {
                for (int i = 0; i < resp.length; i++) {
                    mapMemberAdded(resp[i].getSource());
                    messageReceived(resp[i].getMessage(), resp[i].getSource());
                }
            } else {
                log.warn("broadcast received 0 replies, probably a timeout.");
            }
        } else {
            channel.send(channel.getMembers(),msg,channelSendOptions);
        }
    }

    public void breakdown() {
        finalize();
    }

    @Override
    public void finalize() {
        try {broadcast(MapMessage.MSG_STOP,false); }catch ( Exception ignore){}
        //cleanup
        if (this.rpcChannel != null) {
            this.rpcChannel.breakdown();
        }
        if (this.channel != null) {
            this.channel.removeChannelListener(this);
            this.channel.removeMembershipListener(this);
        }
        this.rpcChannel = null;
        this.channel = null;
        this.mapMembers.clear();
        super.clear();
        this.stateTransferred = false;
        this.externalLoaders = null;
    }

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

    @Override
    public boolean equals(Object o) {
        if ( !(o instanceof AbstractReplicatedMap)) return false;
        if ( !(o.getClass().equals(this.getClass())) ) return false;
        AbstractReplicatedMap other = (AbstractReplicatedMap)o;
        return Arrays.equals(mapContextName,other.mapContextName);
    }

//------------------------------------------------------------------------------
//              GROUP COM INTERFACES
//------------------------------------------------------------------------------
    public Member[] getMapMembers(HashMap<Member, Long> members) {
        synchronized (members) {
            Member[] result = new Member[members.size()];
            members.keySet().toArray(result);
            return result;
        }
    }
    public Member[] getMapMembers() {
        return getMapMembers(this.mapMembers);
    }

    public Member[] getMapMembersExcl(Member[] exclude) {
        synchronized (mapMembers) {
            @SuppressWarnings("unchecked") // mapMembers has the correct type
            HashMap<Member, Long> list = (HashMap<Member, Long>)mapMembers.clone();
            for (int i=0; i<exclude.length;i++) list.remove(exclude[i]);
            return getMapMembers(list);
        }
    }

    /**
     * Replicates any changes to the object since the last time
     * The object has to be primary, ie, if the object is a proxy or a backup, it will not be replicated<br>
     * @param complete - if set to true, the object is replicated to its backup
     * if set to false, only objects that implement ReplicatedMapEntry and the isDirty() returns true will
     * be replicated
     */
    public void replicate(Object key, boolean complete) {
        if ( log.isTraceEnabled() )
            log.trace("Replicate invoked on key:"+key);
        MapEntry entry = (MapEntry)super.get(key);
        if ( entry == null ) return;
        if ( !entry.isSerializable() ) return;
        if (entry.isPrimary() && entry.getBackupNodes()!= null && entry.getBackupNodes().length > 0) {
            Object value = entry.getValue();
            //check to see if we need to replicate this object isDirty()||complete
            boolean repl = complete || ( (value instanceof ReplicatedMapEntry) && ( (ReplicatedMapEntry) value).isDirty());

            if (!repl) {
                if ( log.isTraceEnabled() )
                    log.trace("Not replicating:"+key+", no change made");

                return;
            }
            //check to see if the message is diffable
            boolean diff = ( (value instanceof ReplicatedMapEntry) && ( (ReplicatedMapEntry) value).isDiffable());
            MapMessage msg = null;
            if (diff) {
                ReplicatedMapEntry rentry = (ReplicatedMapEntry)entry.getValue();
                try {
                    rentry.lock();
                    //construct a diff message
                    msg = new MapMessage(mapContextName, MapMessage.MSG_BACKUP,
                                         true, (Serializable) entry.getKey(), null,
                                         rentry.getDiff(),
                                         entry.getPrimary(),
                                         entry.getBackupNodes());
                    rentry.resetDiff();
                } catch (IOException x) {
                    log.error("Unable to diff object. Will replicate the entire object instead.", x);
                } finally {
                    rentry.unlock();
                }

            }
            if (msg == null) {
                //construct a complete
                msg = new MapMessage(mapContextName, MapMessage.MSG_BACKUP,
                                     false, (Serializable) entry.getKey(),
                                     (Serializable) entry.getValue(),
                                     null, entry.getPrimary(),entry.getBackupNodes());

            }
            try {
                if ( channel!=null && entry.getBackupNodes()!= null && entry.getBackupNodes().length > 0 ) {
                    channel.send(entry.getBackupNodes(), msg, channelSendOptions);
                }
            } catch (ChannelException x) {
                log.error("Unable to replicate data.", x);
            }
        } //end if

    }

    /**
     * This can be invoked by a periodic thread to replicate out any changes.
     * For maps that don't store objects that implement ReplicatedMapEntry, this
     * method should be used infrequently to avoid large amounts of data transfer
     * @param complete boolean
     */
    public void replicate(boolean complete) {
        Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<?,?> e = i.next();
            replicate(e.getKey(), complete);
        } //while

    }

    public void transferState() {
        try {
            Member[] members = getMapMembers();
            Member backup = members.length > 0 ? (Member) members[0] : null;
            if (backup != null) {
                MapMessage msg = new MapMessage(mapContextName, getStateMessageType(), false,
                                                null, null, null, null, null);
                Response[] resp = rpcChannel.send(new Member[] {backup}, msg, RpcChannel.FIRST_REPLY, channelSendOptions, rpcTimeout);
                if (resp.length > 0) {
                    synchronized (stateMutex) {
                        msg = (MapMessage) resp[0].getMessage();
                        msg.deserialize(getExternalLoaders());
                        ArrayList<?> list = (ArrayList<?>) msg.getValue();
                        for (int i = 0; i < list.size(); i++) {
                            messageReceived( (Serializable) list.get(i), resp[0].getSource());
                        } //for
                    }
                } else {
                    log.warn("Transfer state, 0 replies, probably a timeout.");
                }
            }
        } catch (ChannelException x) {
            log.error("Unable to transfer LazyReplicatedMap state.", x);
        } catch (IOException x) {
            log.error("Unable to transfer LazyReplicatedMap state.", x);
        } catch (ClassNotFoundException x) {
            log.error("Unable to transfer LazyReplicatedMap state.", x);
        }
        stateTransferred = true;
    }

    /**
     * TODO implement state transfer
     * @param msg Serializable
     * @return Serializable - null if no reply should be sent
     */
    @Override
    public Serializable replyRequest(Serializable msg, final Member sender) {
        if (! (msg instanceof MapMessage))return null;
        MapMessage mapmsg = (MapMessage) msg;

        //map init request
        if (mapmsg.getMsgType() == MapMessage.MSG_INIT) {
            mapmsg.setPrimary(channel.getLocalMember(false));
            return mapmsg;
        }

        //map start request
        if (mapmsg.getMsgType() == MapMessage.MSG_START) {
            mapmsg.setPrimary(channel.getLocalMember(false));
            mapMemberAdded(sender);
            return mapmsg;
        }

        //backup request
        if (mapmsg.getMsgType() == MapMessage.MSG_RETRIEVE_BACKUP) {
            MapEntry entry = (MapEntry)super.get(mapmsg.getKey());
            if (entry == null || (!entry.isSerializable()) )return null;
            mapmsg.setValue( (Serializable) entry.getValue());
            return mapmsg;
        }

        //state transfer request
        if (mapmsg.getMsgType() == MapMessage.MSG_STATE || mapmsg.getMsgType() == MapMessage.MSG_STATE_COPY) {
            synchronized (stateMutex) { //make sure we dont do two things at the same time
                ArrayList<MapMessage> list = new ArrayList<MapMessage>();
                Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry<?,?> e = i.next();
                    MapEntry entry = (MapEntry) super.get(e.getKey());
                    if ( entry != null && entry.isSerializable() ) {
                        boolean copy = (mapmsg.getMsgType() == MapMessage.MSG_STATE_COPY);
                        MapMessage me = new MapMessage(mapContextName,
                                                       copy?MapMessage.MSG_COPY:MapMessage.MSG_PROXY,
                            false, (Serializable) entry.getKey(), copy?(Serializable) entry.getValue():null, null, entry.getPrimary(),entry.getBackupNodes());
                        list.add(me);
                    }
                }
                mapmsg.setValue(list);
                return mapmsg;

            } //synchronized
        }

        return null;

    }

    /**
     * If the reply has already been sent to the requesting thread,
     * the rpc callback can handle any data that comes in after the fact.
     * @param msg Serializable
     * @param sender Member
     */
    @Override
    public void leftOver(Serializable msg, Member sender) {
        //left over membership messages
        if (! (msg instanceof MapMessage))return;

        MapMessage mapmsg = (MapMessage) msg;
        try {
            mapmsg.deserialize(getExternalLoaders());
            if (mapmsg.getMsgType() == MapMessage.MSG_START) {
                mapMemberAdded(mapmsg.getPrimary());
            } else if (mapmsg.getMsgType() == MapMessage.MSG_INIT) {
                memberAlive(mapmsg.getPrimary());
            }
        } catch (IOException x ) {
            log.error("Unable to deserialize MapMessage.",x);
        } catch (ClassNotFoundException x ) {
            log.error("Unable to deserialize MapMessage.",x);
        }
    }

    @Override
    public void messageReceived(Serializable msg, Member sender) {
        if (! (msg instanceof MapMessage)) return;

        MapMessage mapmsg = (MapMessage) msg;
        if ( log.isTraceEnabled() ) {
            log.trace("Map["+mapname+"] received message:"+mapmsg);
        }

        try {
            mapmsg.deserialize(getExternalLoaders());
        } catch (IOException x) {
            log.error("Unable to deserialize MapMessage.", x);
            return;
        } catch (ClassNotFoundException x) {
            log.error("Unable to deserialize MapMessage.", x);
            return;
        }
        if ( log.isTraceEnabled() )
            log.trace("Map message received from:"+sender.getName()+" msg:"+mapmsg);
        if (mapmsg.getMsgType() == MapMessage.MSG_START) {
            mapMemberAdded(mapmsg.getPrimary());
        }

        if (mapmsg.getMsgType() == MapMessage.MSG_STOP) {
            memberDisappeared(mapmsg.getPrimary());
        }

        if (mapmsg.getMsgType() == MapMessage.MSG_PROXY) {
            MapEntry entry = (MapEntry)super.get(mapmsg.getKey());
            if ( entry==null ) {
                entry = new MapEntry(mapmsg.getKey(), mapmsg.getValue());
                entry.setBackup(false);
                entry.setProxy(true);
                entry.setBackupNodes(mapmsg.getBackupNodes());
                entry.setPrimary(mapmsg.getPrimary());
                super.put(entry.getKey(), entry);
            } else {
                entry.setProxy(true);
                entry.setBackup(false);
                entry.setBackupNodes(mapmsg.getBackupNodes());
                entry.setPrimary(mapmsg.getPrimary());
            }
        }

        if (mapmsg.getMsgType() == MapMessage.MSG_REMOVE) {
            super.remove(mapmsg.getKey());
        }

        if (mapmsg.getMsgType() == MapMessage.MSG_BACKUP || mapmsg.getMsgType() == MapMessage.MSG_COPY) {
            MapEntry entry = (MapEntry)super.get(mapmsg.getKey());
            if (entry == null) {
                entry = new MapEntry(mapmsg.getKey(), mapmsg.getValue());
                entry.setBackup(mapmsg.getMsgType() == MapMessage.MSG_BACKUP);
                entry.setProxy(false);
                entry.setBackupNodes(mapmsg.getBackupNodes());
                entry.setPrimary(mapmsg.getPrimary());
                if (mapmsg.getValue()!=null && mapmsg.getValue() instanceof ReplicatedMapEntry ) {
                    ((ReplicatedMapEntry)mapmsg.getValue()).setOwner(getMapOwner());
                }
            } else {
                entry.setBackup(mapmsg.getMsgType() == MapMessage.MSG_BACKUP);
                entry.setProxy(false);
                entry.setBackupNodes(mapmsg.getBackupNodes());
                entry.setPrimary(mapmsg.getPrimary());
                if (entry.getValue() instanceof ReplicatedMapEntry) {
                    ReplicatedMapEntry diff = (ReplicatedMapEntry) entry.getValue();
                    if (mapmsg.isDiff()) {
                        try {
                            diff.lock();
                            diff.applyDiff(mapmsg.getDiffValue(), 0, mapmsg.getDiffValue().length);
                        } catch (Exception x) {
                            log.error("Unable to apply diff to key:" + entry.getKey(), x);
                        } finally {
                            diff.unlock();
                        }
                    } else {
                        if ( mapmsg.getValue()!=null ) entry.setValue(mapmsg.getValue());
                        ((ReplicatedMapEntry)entry.getValue()).setOwner(getMapOwner());
                    } //end if
                } else if  (mapmsg.getValue() instanceof ReplicatedMapEntry) {
                    ReplicatedMapEntry re = (ReplicatedMapEntry)mapmsg.getValue();
                    re.setOwner(getMapOwner());
                    entry.setValue(re);
                } else {
                    if ( mapmsg.getValue()!=null ) entry.setValue(mapmsg.getValue());
                } //end if
            } //end if
            super.put(entry.getKey(), entry);
        } //end if
    }

    @Override
    public boolean accept(Serializable msg, Member sender) {
        boolean result = false;
        if (msg instanceof MapMessage) {
            if ( log.isTraceEnabled() ) log.trace("Map["+mapname+"] accepting...."+msg);
            result = Arrays.equals(mapContextName, ( (MapMessage) msg).getMapId());
            if ( log.isTraceEnabled() ) log.trace("Msg["+mapname+"] accepted["+result+"]...."+msg);
        }
        return result;
    }

    public void mapMemberAdded(Member member) {
        if ( member.equals(getChannel().getLocalMember(false)) ) return;
        boolean memberAdded = false;
        //select a backup node if we don't have one
        synchronized (mapMembers) {
            if (!mapMembers.containsKey(member) ) {
                mapMembers.put(member, new Long(System.currentTimeMillis()));
                memberAdded = true;
            }
        }
        if ( memberAdded ) {
            synchronized (stateMutex) {
                Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry<?,?> e = i.next();
                    MapEntry entry = (MapEntry) super.get(e.getKey());
                    if ( entry == null ) continue;
                    if (entry.isPrimary() && (entry.getBackupNodes() == null || entry.getBackupNodes().length == 0)) {
                        try {
                            Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue());
                            entry.setBackupNodes(backup);
                            entry.setPrimary(channel.getLocalMember(false));
                        } catch (ChannelException x) {
                            log.error("Unable to select backup node.", x);
                        } //catch
                    } //end if
                } //while
            } //synchronized
        }//end if
    }

    public boolean inSet(Member m, Member[] set) {
        if ( set == null ) return false;
        boolean result = false;
        for (int i=0; i<set.length && (!result); i++ )
            if ( m.equals(set[i]) ) result = true;
        return result;
    }

    public Member[] excludeFromSet(Member[] mbrs, Member[] set) {
        ArrayList<Member> result = new ArrayList<Member>();
        for (int i=0; i<set.length; i++ ) {
            boolean include = true;
            for (int j=0; j<mbrs.length; j++ )
                if ( mbrs[j].equals(set[i]) ) include = false;
            if ( include ) result.add(set[i]);
        }
        return result.toArray(new Member[result.size()]);
    }

    @Override
    public void memberAdded(Member member) {
        //do nothing
    }

    @Override
    public void memberDisappeared(Member member) {
        boolean removed = false;
        synchronized (mapMembers) {
            removed = (mapMembers.remove(member) != null );
            if (!removed) {
                if (log.isDebugEnabled()) log.debug("Member["+member+"] disappeared, but was not present in the map.");
                return; //the member was not part of our map.
            }
        }

        Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<?,?> e = i.next();
            MapEntry entry = (MapEntry) super.get(e.getKey());
            if (entry==null) continue;
            if (entry.isPrimary() && inSet(member,entry.getBackupNodes())) {
                if (log.isDebugEnabled()) log.debug("[1] Primary choosing a new backup");
                try {
                    Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue());
                    entry.setBackupNodes(backup);
                    entry.setPrimary(channel.getLocalMember(false));
                } catch (ChannelException x) {
                    log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x);
                }
            } else if (member.equals(entry.getPrimary())) {
                if (log.isDebugEnabled()) log.debug("[2] Primary disappeared");
                entry.setPrimary(null);
            } //end if

            if ( entry.isProxy() &&
                 entry.getPrimary() == null &&
                 entry.getBackupNodes()!=null &&
                 entry.getBackupNodes().length == 1 &&
                 entry.getBackupNodes()[0].equals(member) ) {
                //remove proxies that have no backup nor primaries
                if (log.isDebugEnabled()) log.debug("[3] Removing orphaned proxy");
                i.remove();
            } else if ( entry.getPrimary() == null &&
                        entry.isBackup() &&
                        entry.getBackupNodes()!=null &&
                        entry.getBackupNodes().length == 1 &&
                        entry.getBackupNodes()[0].equals(channel.getLocalMember(false)) ) {
                try {
                    if (log.isDebugEnabled()) log.debug("[4] Backup becoming primary");
                    entry.setPrimary(channel.getLocalMember(false));
                    entry.setBackup(false);
                    entry.setProxy(false);
                    Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue());
                    entry.setBackupNodes(backup);
                    if ( mapOwner!=null ) mapOwner.objectMadePrimay(entry.getKey(),entry.getValue());

                } catch (ChannelException x) {
                    log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x);
                }
            }

        } //while
    }

    public int getNextBackupIndex() {
        int size = mapMembers.size();
        if (mapMembers.size() == 0)return -1;
        int node = currentNode++;
        if (node >= size) {
            node = 0;
            currentNode = 0;
        }
        return node;
    }
    public Member getNextBackupNode() {
        Member[] members = getMapMembers();
        int node = getNextBackupIndex();
        if ( members.length == 0 || node==-1) return null;
        if ( node >= members.length ) node = 0;
        return members[node];
    }

    protected abstract Member[] publishEntryInfo(Object key, Object value) throws ChannelException;

    @Override
    public void heartbeat() {
        try {
            ping(accessTimeout);
        }catch ( Exception x ) {
            log.error("Unable to send AbstractReplicatedMap.ping message",x);
        }
    }

//------------------------------------------------------------------------------
//              METHODS TO OVERRIDE
//------------------------------------------------------------------------------

    /**
     * Removes an object from this map, it will also remove it from
     *
     * @param key Object
     * @return Object
     */
    @Override
    public Object remove(Object key) {
        return remove(key,true);
    }
    public Object remove(Object key, boolean notify) {
        MapEntry entry = (MapEntry)super.remove(key);

        try {
            if (getMapMembers().length > 0 && notify) {
                MapMessage msg = new MapMessage(getMapContextName(), MapMessage.MSG_REMOVE, false, (Serializable) key, null, null, null,null);
                getChannel().send(getMapMembers(), msg, getChannelSendOptions());
            }
        } catch ( ChannelException x ) {
            log.error("Unable to replicate out data for a LazyReplicatedMap.remove operation",x);
        }
        return entry!=null?entry.getValue():null;
    }

    public MapEntry getInternal(Object key) {
        return (MapEntry)super.get(key);
    }

    @Override
    public Object get(Object key) {
        MapEntry entry = (MapEntry)super.get(key);
        if (log.isTraceEnabled()) log.trace("Requesting id:"+key+" entry:"+entry);
        if ( entry == null ) return null;
        if ( !entry.isPrimary() ) {
            //if the message is not primary, we need to retrieve the latest value
            try {
                Member[] backup = null;
                MapMessage msg = null;
                if ( !entry.isBackup() ) {
                    //make sure we don't retrieve from ourselves
                    msg = new MapMessage(getMapContextName(), MapMessage.MSG_RETRIEVE_BACKUP, false,
                                         (Serializable) key, null, null, null,null);
                    Response[] resp = getRpcChannel().send(entry.getBackupNodes(),msg, RpcChannel.FIRST_REPLY, Channel.SEND_OPTIONS_DEFAULT, getRpcTimeout());
                    if (resp == null || resp.length == 0) {
                        //no responses
                        log.warn("Unable to retrieve remote object for key:" + key);
                        return null;
                    }
                    msg = (MapMessage) resp[0].getMessage();
                    msg.deserialize(getExternalLoaders());
                    backup = entry.getBackupNodes();
                    if ( entry.getValue() instanceof ReplicatedMapEntry ) {
                        ReplicatedMapEntry val = (ReplicatedMapEntry)entry.getValue();
                        val.setOwner(getMapOwner());
                    }
                    if ( msg.getValue()!=null ) entry.setValue(msg.getValue());
                }
                if (entry.isBackup()) {
                    //select a new backup node
                    backup = publishEntryInfo(key, entry.getValue());
                } else if ( entry.isProxy() ) {
                    //invalidate the previous primary
                    msg = new MapMessage(getMapContextName(),MapMessage.MSG_PROXY,false,(Serializable)key,null,null,channel.getLocalMember(false),backup);
                    Member[] dest = getMapMembersExcl(backup);
                    if ( dest!=null && dest.length >0) {
                        getChannel().send(dest, msg, getChannelSendOptions());
                    }
                    if ( entry.getValue() != null && entry.getValue() instanceof ReplicatedMapEntry ) {
                        ReplicatedMapEntry val = (ReplicatedMapEntry)entry.getValue();
                        val.setOwner(getMapOwner());
                    }
                }
                entry.setPrimary(channel.getLocalMember(false));
                entry.setBackupNodes(backup);
                entry.setBackup(false);
                entry.setProxy(false);
                if ( getMapOwner()!=null ) getMapOwner().objectMadePrimay(key, entry.getValue());

            } catch (Exception x) {
                log.error("Unable to replicate out data for a LazyReplicatedMap.get operation", x);
                return null;
            }
        }
        if (log.isTraceEnabled()) log.trace("Requesting id:"+key+" result:"+entry.getValue());
        return entry.getValue();
    }

    protected void printMap(String header) {
        try {
            System.out.println("\nDEBUG MAP:"+header);
            System.out.println("Map[" +
                    new String(mapContextName, CHARSET_ISO_8859_1) +
                    ", Map Size:" + super.size());
            Member[] mbrs = getMapMembers();
            for ( int i=0; i<mbrs.length;i++ ) {
                System.out.println("Mbr["+(i+1)+"="+mbrs[i].getName());
            }
            Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
            int cnt = 0;

            while (i.hasNext()) {
                Map.Entry<?,?> e = i.next();
                System.out.println( (++cnt) + ". " + super.get(e.getKey()));
            }
            System.out.println("EndMap]\n\n");
        }catch ( Exception ignore) {
            ignore.printStackTrace();
        }
    }

    /**
         * Returns true if the key has an entry in the map.
         * The entry can be a proxy or a backup entry, invoking <code>get(key)</code>
         * will make this entry primary for the group
         * @param key Object
         * @return boolean
         */
        @Override
        public boolean containsKey(Object key) {
            return super.containsKey(key);
        }

        @Override
        public Object put(Object key, Object value) {
            return put(key,value,true);
        }

        public Object put(Object key, Object value, boolean notify) {
            MapEntry entry = new MapEntry(key,value);
            entry.setBackup(false);
            entry.setProxy(false);
            entry.setPrimary(channel.getLocalMember(false));

            Object old = null;

            //make sure that any old values get removed
            if ( containsKey(key) ) old = remove(key);
            try {
                if ( notify ) {
                    Member[] backup = publishEntryInfo(key, value);
                    entry.setBackupNodes(backup);
                }
            } catch (ChannelException x) {
                log.error("Unable to replicate out data for a LazyReplicatedMap.put operation", x);
            }
            super.put(key,entry);
            return old;
        }

        /**
         * Copies all values from one map to this instance
         * @param m Map
         */
        @Override
        public void putAll(Map m) {
            Iterator<Map.Entry<?,?>> i = m.entrySet().iterator();
            while ( i.hasNext() ) {
                Map.Entry<?,?> entry = i.next();
                put(entry.getKey(),entry.getValue());
            }
        }

        @Override
        public void clear() {
            clear(true);
        }

        public void clear(boolean notify) {
            if ( notify ) {
                //only delete active keys
                Iterator<Object> keys = keySet().iterator();
                while (keys.hasNext())
                    remove(keys.next());
            } else {
                super.clear();
            }
        }

        @Override
        public boolean containsValue(Object value) {
            if ( value == null ) {
                return super.containsValue(value);
            } else {
                Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry<?,?> e = i.next();
                    MapEntry entry = (MapEntry) super.get(e.getKey());
                    if (entry!=null && entry.isActive() && value.equals(entry.getValue())) return true;
                }//while
                return false;
            }//end if
        }

        @Override
        public Object clone() {
            throw new UnsupportedOperationException("This operation is not valid on a replicated map");
        }

        /**
         * Returns the entire contents of the map
         * Map.Entry.getValue() will return a LazyReplicatedMap.MapEntry object containing all the information
         * about the object.
         * @return Set
         */
        public Set entrySetFull() {
            return super.entrySet();
        }

        public Set keySetFull() {
            return super.keySet();
        }

        public int sizeFull() {
            return super.size();
        }

        @Override
        public Set<MapEntry> entrySet() {
            LinkedHashSet<MapEntry> set = new LinkedHashSet<MapEntry>(super.size());
            Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
            while ( i.hasNext() ) {
                Map.Entry<?,?> e = i.next();
                Object key = e.getKey();
                MapEntry entry = (MapEntry)super.get(key);
                if ( entry != null && entry.isActive() ) {
                    set.add(new MapEntry(key, entry.getValue()));
                }
            }
            return Collections.unmodifiableSet(set);
        }

        @Override
        public Set<Object> keySet() {
            //todo implement
            //should only return keys where this is active.
            LinkedHashSet<Object> set = new LinkedHashSet<Object>(super.size());
            Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
            while ( i.hasNext() ) {
                Map.Entry<?,?> e = i.next();
                Object key = e.getKey();
                MapEntry entry = (MapEntry)super.get(key);
                if ( entry!=null && entry.isActive() ) set.add(key);
            }
            return Collections.unmodifiableSet(set);

        }

        @Override
        public int size() {
            //todo, implement a counter variable instead
            //only count active members in this node
            int counter = 0;
            Iterator<Map.Entry<?,?>> it = super.entrySet().iterator();
            while (it!=null && it.hasNext() ) {
                Map.Entry<?,?> e = it.next();
                if ( e != null ) {
                    MapEntry entry = (MapEntry) super.get(e.getKey());
                    if (entry!=null && entry.isActive() && entry.getValue() != null) counter++;
                }
            }
            return counter;
        }

        @Override
        public boolean isEmpty() {
            return size()==0;
        }

        @Override
        public Collection<Object> values() {
            ArrayList<Object> values = new ArrayList<Object>();
            Iterator<Map.Entry<?,?>> i = super.entrySet().iterator();
            while ( i.hasNext() ) {
                Map.Entry<?,?> e = i.next();
                MapEntry entry = (MapEntry)super.get(e.getKey());
                if (entry!=null && entry.isActive() && entry.getValue()!=null) values.add(entry.getValue());
            }
            return Collections.unmodifiableCollection(values);
        }

//------------------------------------------------------------------------------
//                Map Entry class
//------------------------------------------------------------------------------
    public static class MapEntry implements Map.Entry<Object,Object> {
        private boolean backup;
        private boolean proxy;
        private Member[] backupNodes;
        private Member primary;
        private Object key;
        private Object value;

        public MapEntry(Object key, Object value) {
            setKey(key);
            setValue(value);

        }

        public boolean isKeySerializable() {
            return (key == null) || (key instanceof Serializable);
        }

        public boolean isValueSerializable() {
            return (value==null) || (value instanceof Serializable);
        }

        public boolean isSerializable() {
            return isKeySerializable() && isValueSerializable();
        }

        public boolean isBackup() {
            return backup;
        }

        public void setBackup(boolean backup) {
            this.backup = backup;
        }

        public boolean isProxy() {
            return proxy;
        }

        public boolean isPrimary() {
            return (!proxy && !backup);
        }

        public boolean isActive() {
            return !proxy;
        }

        public void setProxy(boolean proxy) {
            this.proxy = proxy;
        }

        public boolean isDiffable() {
            return (value instanceof ReplicatedMapEntry) &&
                   ((ReplicatedMapEntry)value).isDiffable();
        }

        public void setBackupNodes(Member[] nodes) {
            this.backupNodes = nodes;
        }

        public Member[] getBackupNodes() {
            return backupNodes;
        }

        public void setPrimary(Member m) {
            primary = m;
        }

        public Member getPrimary() {
            return primary;
        }

        @Override
        public Object getValue() {
            return value;
        }

        @Override
        public Object setValue(Object value) {
            Object old = this.value;
            this.value = value;
            return old;
        }

        @Override
        public Object getKey() {
            return key;
        }

        public Object setKey(Object key) {
            Object old = this.key;
            this.key = key;
            return old;
        }

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

        @Override
        public boolean equals(Object o) {
            return key.equals(o);
        }

        /**
         * apply a diff, or an entire object
         * @param data byte[]
         * @param offset int
         * @param length int
         * @param diff boolean
         * @throws IOException
         * @throws ClassNotFoundException
         */
        public void apply(byte[] data, int offset, int length, boolean diff) throws IOException, ClassNotFoundException {
            if (isDiffable() && diff) {
                ReplicatedMapEntry rentry = (ReplicatedMapEntry) value;
                try {
                    rentry.lock();
                    rentry.applyDiff(data, offset, length);
                } finally {
                    rentry.unlock();
                }
            } else if (length == 0) {
                value = null;
                proxy = true;
            } else {
                value = XByteBuffer.deserialize(data, offset, length);
            }
        }

        @Override
        public String toString() {
            StringBuilder buf = new StringBuilder("MapEntry[key:");
            buf.append(getKey()).append("; ");
            buf.append("value:").append(getValue()).append("; ");
            buf.append("primary:").append(isPrimary()).append("; ");
            buf.append("backup:").append(isBackup()).append("; ");
            buf.append("proxy:").append(isProxy()).append(";]");
            return buf.toString();
        }

    }

//------------------------------------------------------------------------------
//                map message to send to and from other maps
//------------------------------------------------------------------------------

    public static class MapMessage implements Serializable {
        private static final long serialVersionUID = 1L;
        public static final int MSG_BACKUP = 1;
        public static final int MSG_RETRIEVE_BACKUP = 2;
        public static final int MSG_PROXY = 3;
        public static final int MSG_REMOVE = 4;
        public static final int MSG_STATE = 5;
        public static final int MSG_START = 6;
        public static final int MSG_STOP = 7;
        public static final int MSG_INIT = 8;
        public static final int MSG_COPY = 9;
        public static final int MSG_STATE_COPY = 10;

        private byte[] mapId;
        private int msgtype;
        private boolean diff;
        private transient Serializable key;
        private transient Serializable value;
        private byte[] valuedata;
        private byte[] keydata;
        private byte[] diffvalue;
        private Member[] nodes;
        private Member primary;

        @Override
        public String toString() {
            StringBuilder buf = new StringBuilder("MapMessage[context=");
            buf.append(new String(mapId));
            buf.append("; type=");
            buf.append(getTypeDesc());
            buf.append("; key=");
            buf.append(key);
            buf.append("; value=");
            buf.append(value);
            return buf.toString();
        }

        public String getTypeDesc() {
            switch (msgtype) {
                case MSG_BACKUP: return "MSG_BACKUP";
                case MSG_RETRIEVE_BACKUP: return "MSG_RETRIEVE_BACKUP";
                case MSG_PROXY: return "MSG_PROXY";
                case MSG_REMOVE: return "MSG_REMOVE";
                case MSG_STATE: return "MSG_STATE";
                case MSG_START: return "MSG_START";
                case MSG_STOP: return "MSG_STOP";
                case MSG_INIT: return "MSG_INIT";
                case MSG_STATE_COPY: return "MSG_STATE_COPY";
                case MSG_COPY: return "MSG_COPY";
                default : return "UNKNOWN";
            }
        }

        public MapMessage() {}

        public MapMessage(byte[] mapId,int msgtype, boolean diff,
                          Serializable key, Serializable value,
                          byte[] diffvalue, Member primary, Member[] nodes)  {
            this.mapId = mapId;
            this.msgtype = msgtype;
            this.diff = diff;
            this.key = key;
            this.value = value;
            this.diffvalue = diffvalue;
            this.nodes = nodes;
            this.primary = primary;
            setValue(value);
            setKey(key);
        }

        public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException {
            key(cls);
            value(cls);
        }

        public int getMsgType() {
            return msgtype;
        }

        public boolean isDiff() {
            return diff;
        }

        public Serializable getKey() {
            try {
                return key(null);
            } catch ( Exception x ) {
                log.error("Deserialization error of the MapMessage.key",x);
                return null;
            }
        }

        public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException {
            if ( key!=null ) return key;
            if ( keydata == null || keydata.length == 0 ) return null;
            key = XByteBuffer.deserialize(keydata,0,keydata.length,cls);
            keydata = null;
            return key;
        }

        public byte[] getKeyData() {
            return keydata;
        }

        public Serializable getValue() {
            try {
                return value(null);
            } catch ( Exception x ) {
                log.error("Deserialization error of the MapMessage.value",x);
                return null;
            }
        }

        public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException  {
            if ( value!=null ) return value;
            if ( valuedata == null || valuedata.length == 0 ) return null;
            value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls);
            valuedata = null;
            return value;
        }

        public byte[] getValueData() {
            return valuedata;
        }

        public byte[] getDiffValue() {
            return diffvalue;
        }

        public Member[] getBackupNodes() {
            return nodes;
        }

        public Member getPrimary() {
            return primary;
        }

        private void setPrimary(Member m) {
            primary = m;
        }

        public byte[] getMapId() {
            return mapId;
        }

        public void setValue(Serializable value) {
            try {
                if ( value != null ) valuedata = XByteBuffer.serialize(value);
                this.value = value;
            }catch ( IOException x ) {
                throw new RuntimeException(x);
            }
        }

        public void setKey(Serializable key) {
            try {
                if (key != null) keydata = XByteBuffer.serialize(key);
                this.key = key;
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }

        protected Member[] readMembers(ObjectInput in) throws IOException, ClassNotFoundException {
            int nodecount = in.readInt();
            Member[] members = new Member[nodecount];
            for ( int i=0; i<members.length; i++ ) {
                byte[] d = new byte[in.readInt()];
                in.readFully(d);
                if (d.length > 0) members[i] = MemberImpl.getMember(d);
            }
            return members;
        }

        protected void writeMembers(ObjectOutput out,Member[] members) throws IOException {
            if ( members == null ) members = new Member[0];
            out.writeInt(members.length);
            for (int i=0; i<members.length; i++ ) {
                if ( members[i] != null ) {
                    byte[] d = members[i] != null ? ( (MemberImpl)members[i]).getData(false) : new byte[0];
                    out.writeInt(d.length);
                    out.write(d);
                }
            }
        }

        /**
         * shallow clone
         * @return Object
         */
        @Override
        public Object clone() {
            MapMessage msg = new MapMessage(this.mapId, this.msgtype, this.diff, this.key, this.value, this.diffvalue, this.primary, this.nodes);
            msg.keydata = this.keydata;
            msg.valuedata = this.valuedata;
            return msg;
        }
    } //MapMessage

    public Channel getChannel() {
        return channel;
    }

    public byte[] getMapContextName() {
        return mapContextName;
    }

    public RpcChannel getRpcChannel() {
        return rpcChannel;
    }

    public long getRpcTimeout() {
        return rpcTimeout;
    }

    public Object getStateMutex() {
        return stateMutex;
    }

    public boolean isStateTransferred() {
        return stateTransferred;
    }

    public MapOwner getMapOwner() {
        return mapOwner;
    }

    public ClassLoader[] getExternalLoaders() {
        return externalLoaders;
    }

    public int getChannelSendOptions() {
        return channelSendOptions;
    }

    public long getAccessTimeout() {
        return accessTimeout;
    }

    public void setMapOwner(MapOwner mapOwner) {
        this.mapOwner = mapOwner;
    }

    public void setExternalLoaders(ClassLoader[] externalLoaders) {
        this.externalLoaders = externalLoaders;
    }

    public void setChannelSendOptions(int channelSendOptions) {
        this.channelSendOptions = channelSendOptions;
    }

    public void setAccessTimeout(long accessTimeout) {
        this.accessTimeout = accessTimeout;
    }

}


text:
package es.caib.zkib.jxpath.ri.model;

import es.caib.zkib.jxpath.JXPathContext;
import es.caib.zkib.jxpath.JXPathTestCase;
import es.caib.zkib.jxpath.xml.DocumentContainer;

/**
 * Test for text trimming from JXPATH-83.
 *
 * @author Matt Benson
 * @version $Revision: 1.1 $ $Date: 2009-04-03 08:13:14 $
 */
public class XMLSpaceTest extends JXPathTestCase {
    protected JXPathContext context;

    protected DocumentContainer createDocumentContainer(String model) {
        return new DocumentContainer(JXPathTestCase.class
                .getResource("XmlSpace.xml"), model);
    }

    protected JXPathContext createContext(String model) {
        JXPathContext context = JXPathContext
                .newContext(createDocumentContainer(model));
        return context;
    }

    protected void doTest(String id, String model, String expectedValue) {
        JXPathContext context = JXPathContext
                .newContext(createDocumentContainer(model));
        assertEquals(context.getValue("test/text[@id='" + id + "']"), expectedValue);
    }

    public void testUnspecifiedDOM() {
        doTest("unspecified", DocumentContainer.MODEL_DOM, "foo");
    }

    public void testDefaultDOM() {
        doTest("default", DocumentContainer.MODEL_DOM, "foo");
    }

    public void testPreserveDOM() {
        doTest("preserve", DocumentContainer.MODEL_DOM, " foo ");
    }

    public void testNestedDOM() {
        doTest("nested", DocumentContainer.MODEL_DOM, "foo;bar; baz ");
    }

    public void testNestedWithCommentsDOM() {
        doTest("nested-with-comments", DocumentContainer.MODEL_DOM, "foo;bar; baz ");
    }

    public void testUnspecifiedJDOM() {
        doTest("unspecified", DocumentContainer.MODEL_JDOM, "foo");
    }

    public void testDefaultJDOM() {
        doTest("default", DocumentContainer.MODEL_JDOM, "foo");
    }

    public void testPreserveJDOM() {
        doTest("preserve", DocumentContainer.MODEL_JDOM, " foo ");
    }

    public void testNestedJDOM() {
        doTest("nested", DocumentContainer.MODEL_JDOM, "foo;bar; baz ");
    }

    public void testNestedWithCommentsJDOM() {
        doTest("nested-with-comments", DocumentContainer.MODEL_JDOM, "foo;bar; baz ");
    }
}


text:
Search by:

        <input type='text' [(ngModel)]='searchCriteria'/>

      Full Name
      Alias
      Race
      Location
      Age
      Level
      Rank
      Details
      Edit
      Delete

      {{hero.name}}
      {{hero.alias}}
      {{hero.race}}
      {{hero.location}}
      {{hero.age}}
      {{hero.level}}
      {{hero.rank}}
      <button [routerLink]="['/hero', hero.id]">See Details </button>
      <button [routerLink]="['/updateHero', hero.id]">Edit </button>

      <button  (click) = deleteHero(hero.id)>Delete </button>


text:
import React from 'react';
import styled from 'styled-components';

import SocialIcons from './SocialIcons';

const Container = styled.footer`
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem 0.5rem;
`;

export default function Footer() {
  const colors = {
    color: `rgba(255, 255, 255, 0.6)`,
    hoverColor: `rgba(255, 255, 255, 1)`
  }
  return (
    <Container>
      <SocialIcons flexDirection="row" width="240px" {...colors} />
    </Container>
  );
}


text:
namespace EdNetApi.Journal.JournalEntries
{
    using System;
    using System.ComponentModel;

    using EdNetApi.Common;
    using EdNetApi.Journal.Enums;

    using Newtonsoft.Json;

    public class ShipyardSwapJournalEntry : JournalEntry
    {
        public const JournalEventType EventConst = JournalEventType.ShipyardSwap;

        internal ShipyardSwapJournalEntry()
        {
        }

        [JsonIgnore]
        public override JournalEventType Event => EventConst;

        [JsonProperty("timestamp")]
        public override DateTime Timestamp { get; internal set; }

        [JsonProperty("ShipType")]
        [Description("type of ship being switched to")]
        public string ShipTypeRaw { get; internal set; }

        [JsonIgnore]
        [Description("type of ship being switched to")]
        public ShipType ShipType => ShipTypeRaw.GetEnumValue<ShipType>();

        [JsonProperty("ShipID")]
        [Description("")]
        public int ShipId { get; internal set; }

        [JsonProperty("StoreOldShip")]
        [Description("(if storing old ship) type of ship being stored")]
        public string StoreOldShip { get; internal set; }

        [JsonProperty("StoreShipID")]
        [Description("")]
        public int StoreShipId { get; internal set; }
    }
}


text:
\mainpage Project Chrono API/SDK documentation

@subpage introduction_chrono

High level overview of Chrono's features and capabilities.

---

@subpage tutorial_table_of_content_install

Instructions for configuring, building, and installing Chrono and its optional modules.

Instructions on how to set up a project that uses Chrono.

---

@subpage tutorial_root

Basic example code for various features in Chrono. Rather verbose, good place to get started on how to use Chrono.

---

@subpage manual_root

More detailed documentation of Chrono's main features.

Download the reference manual as a single [PDF](refman.pdf) file.

---

Plugins

- Overview of [Chrono::PyEngine](@ref introduction_chrono_pyengine)

- Overview of [Chrono::SolidWorks](@ref introduction_chrono_solidworks)


text:
#include <string>

#include "modsecurity/actions/action.h"

#ifndef SRC_ACTIONS_MULTI_MATCH_H_
#define SRC_ACTIONS_MULTI_MATCH_H_

#ifdef __cplusplus
class Transaction;

namespace modsecurity {
class Transaction;
class Rule;

namespace actions {

class MultiMatch : public Action {
 public:
    explicit MultiMatch(std::string action)
        : Action(action, RunTimeOnlyIfMatchKind) { }

    bool evaluate(Rule *rule, Transaction *transaction) override;
};

}  // namespace actions
}  // namespace modsecurity
#endif

#endif  // SRC_ACTIONS_MULTI_MATCH_H_


text:
package com.intellij.psi.impl;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.IdFilter;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Set;

public class CompositeShortNamesCache extends PsiShortNamesCache {
  private final PsiShortNamesCache[] myCaches;

  public CompositeShortNamesCache(Project project) {
    myCaches = project.isDefault() ? new PsiShortNamesCache[0] : project.getExtensions(PsiShortNamesCache.EP_NAME);
  }

  @Override
  @NotNull
  public PsiFile[] getFilesByName(@NotNull String name) {
    Merger<PsiFile> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiFile[] classes = cache.getFilesByName(name);
      if (classes.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(classes);
      }
    }
    PsiFile[] result = merger == null ? null : merger.getResult();
    return result != null ? result : PsiFile.EMPTY_ARRAY;
  }

  @Override
  @NotNull
  public String[] getAllFileNames() {
    Merger<String> merger = new Merger<>();
    for (PsiShortNamesCache cache : myCaches) {
      merger.add(cache.getAllFileNames());
    }
    String[] result = merger.getResult();
    return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
  }

  @Override
  @NotNull
  public PsiClass[] getClassesByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
    Merger<PsiClass> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiClass[] classes = cache.getClassesByName(name, scope);
      if (classes.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(classes);
      }
    }
    PsiClass[] result = merger == null ? null : merger.getResult();
    return result != null ? result : PsiClass.EMPTY_ARRAY;
  }

  @Override
  @NotNull
  public String[] getAllClassNames() {
    Merger<String> merger = new Merger<>();
    for (PsiShortNamesCache cache : myCaches) {
      String[] names = cache.getAllClassNames();
      merger.add(names);
    }
    String[] result = merger.getResult();
    return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
  }

  @Override
  public boolean processAllClassNames(@NotNull Processor<String> processor) {
    CommonProcessors.UniqueProcessor<String> uniqueProcessor = new CommonProcessors.UniqueProcessor<>(processor);
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processAllClassNames(uniqueProcessor)) {
        return false;
      }
    }
    return true;
  }

  @Override
  public boolean processAllClassNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processAllClassNames(processor, scope, filter)) {
        return false;
      }
    }
    return true;
  }

  @Override
  public boolean processAllMethodNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processAllMethodNames(processor, scope, filter)) {
        return false;
      }
    }
    return true;
  }

  @Override
  public boolean processAllFieldNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processAllFieldNames(processor, scope, filter)) {
        return false;
      }
    }
    return true;
  }

  @Override
  @NotNull
  public PsiMethod[] getMethodsByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
    Merger<PsiMethod> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiMethod[] methods = cache.getMethodsByName(name, scope);
      if (methods.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(methods);
      }
    }
    PsiMethod[] result = merger == null ? null : merger.getResult();
    return result == null ? PsiMethod.EMPTY_ARRAY : result;
  }

  @Override
  @NotNull
  public PsiMethod[] getMethodsByNameIfNotMoreThan(@NonNls @NotNull final String name, @NotNull final GlobalSearchScope scope, final int maxCount) {
    Merger<PsiMethod> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(name, scope, maxCount);
      if (methods.length == maxCount) return methods;
      if (methods.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(methods);
      }
    }
    PsiMethod[] result = merger == null ? null : merger.getResult();
    return result == null ? PsiMethod.EMPTY_ARRAY : result;
  }

  @NotNull
  @Override
  public PsiField[] getFieldsByNameIfNotMoreThan(@NonNls @NotNull String name, @NotNull GlobalSearchScope scope, int maxCount) {
    Merger<PsiField> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiField[] fields = cache.getFieldsByNameIfNotMoreThan(name, scope, maxCount);
      if (fields.length == maxCount) return fields;
      if (fields.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(fields);
      }
    }
    PsiField[] result = merger == null ? null : merger.getResult();
    return result == null ? PsiField.EMPTY_ARRAY : result;
  }

  @Override
  public boolean processMethodsWithName(@NonNls @NotNull String name,
                                        @NotNull GlobalSearchScope scope,
                                        @NotNull Processor<PsiMethod> processor) {
    return processMethodsWithName(name, processor, scope, null);
  }

  @Override
  public boolean processMethodsWithName(@NonNls @NotNull String name,
                                        @NotNull Processor<? super PsiMethod> processor,
                                        @NotNull GlobalSearchScope scope,
                                        @Nullable IdFilter idFilter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processMethodsWithName(name, processor, scope, idFilter)) return false;
    }
    return true;
  }

  @Override
  @NotNull
  public String[] getAllMethodNames() {
    Merger<String> merger = new Merger<>();
    for (PsiShortNamesCache cache : myCaches) {
      merger.add(cache.getAllMethodNames());
    }
    String[] result = merger.getResult();
    return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
  }

  @Override
  @NotNull
  public PsiField[] getFieldsByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
    Merger<PsiField> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      PsiField[] classes = cache.getFieldsByName(name, scope);
      if (classes.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(classes);
      }
    }
    PsiField[] result = merger == null ? null : merger.getResult();
    return result == null ? PsiField.EMPTY_ARRAY : result;
  }

  @Override
  @NotNull
  public String[] getAllFieldNames() {
    Merger<String> merger = null;
    for (PsiShortNamesCache cache : myCaches) {
      String[] classes = cache.getAllFieldNames();
      if (classes.length != 0) {
        if (merger == null) merger = new Merger<>();
        merger.add(classes);
      }
    }
    String[] result = merger == null ? null : merger.getResult();
    return result == null ? ArrayUtil.EMPTY_STRING_ARRAY : result;
  }

  @Override
  public boolean processFieldsWithName(@NotNull String key,
                                       @NotNull Processor<? super PsiField> processor,
                                       @NotNull GlobalSearchScope scope,
                                       @Nullable IdFilter filter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processFieldsWithName(key, processor, scope, filter)) return false;
    }
    return true;
  }

  @Override
  public boolean processClassesWithName(@NotNull String key,
                                        @NotNull Processor<? super PsiClass> processor,
                                        @NotNull GlobalSearchScope scope,
                                        @Nullable IdFilter filter) {
    for (PsiShortNamesCache cache : myCaches) {
      if (!cache.processClassesWithName(key, processor, scope, filter)) return false;
    }
    return true;
  }

  private static class Merger<T> {
    private T[] mySingleItem;
    private Set<T> myAllItems;

    public void add(@NotNull T[] items) {
      if (items.length == 0) return;
      if (mySingleItem == null) {
        mySingleItem = items;
        return;
      }
      if (myAllItems == null) {
        T[] elements = mySingleItem;
        myAllItems = ContainerUtil.addAll(new THashSet<>(elements.length), elements);
      }
      ContainerUtil.addAll(myAllItems, items);
    }

    public T[] getResult() {
      if (myAllItems == null) return mySingleItem;
      return myAllItems.toArray(mySingleItem);
    }
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  @Override
  public String toString() {
    return "Composite cache: " + Arrays.asList(myCaches);
  }
}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
description: Invocation of `exec` method
es6id: 21.2.5.6
info: >
    [...]
    7. If global is false, then
       a. Return RegExpExec(rx, S).

    21.2.5.2.1 Runtime Semantics: RegExpExec ( R, S )

    [...]
    5. If IsCallable(exec) is true, then
       a. Let result be Call(exec, R, «S»).
features: [Symbol.match]
---*/

var r = /./;
var callCount = 0;
var arg = {
  toString: function() {
    return 'string form';
  }
};
var thisValue, args;

r.exec = function() {
  thisValue = this;
  args = arguments;
  callCount += 1;
  return null;
};

r[Symbol.match](arg);

assert.sameValue(callCount, 1);
assert.sameValue(thisValue, r);
assert.sameValue(args.length, 1);
assert.sameValue(args[0], 'string form');


text:
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:

    3GPP TS 26.073
    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
    Available from http://www.3gpp.org

(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*

 Filename: /audio/gsm_amr/c/include/qua_gain.h

------------------------------------------------------------------------------
 REVISION HISTORY

 Description: Placed header file in the proper template format.  Added
 parameter pOverflow for the basic math ops.

 Description: Moved _cplusplus #ifdef after Include section.

 Who:                       Date:
 Description:

------------------------------------------------------------------------------
 INCLUDE DESCRIPTION

 This file contains all the constant definitions and prototype definitions
 needed by the file, qua_gain.c

------------------------------------------------------------------------------
*/

/*----------------------------------------------------------------------------
; CONTINUE ONLY IF NOT ALREADY DEFINED
----------------------------------------------------------------------------*/
#ifndef qua_gain_h
#define qua_gain_h "$Id $"

/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "typedef.h"
#include "gc_pred.h"
#include "mode.h"

/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif

    /*----------------------------------------------------------------------------
    ; MACROS
    ; Define module specific macros here
    ----------------------------------------------------------------------------*/

    /*----------------------------------------------------------------------------
    ; DEFINES
    ; Include all pre-processor statements here.
    ----------------------------------------------------------------------------*/
#define VQ_SIZE_HIGHRATES 128
#define VQ_SIZE_LOWRATES 64

    /*----------------------------------------------------------------------------
    ; EXTERNAL VARIABLES REFERENCES
    ; Declare variables used in this module but defined elsewhere
    ----------------------------------------------------------------------------*/

    /*----------------------------------------------------------------------------
    ; SIMPLE TYPEDEF'S
    ----------------------------------------------------------------------------*/

    /*----------------------------------------------------------------------------
    ; ENUMERATED TYPEDEF'S
    ----------------------------------------------------------------------------*/

    /*----------------------------------------------------------------------------
    ; STRUCTURES TYPEDEF'S
    ----------------------------------------------------------------------------*/

    /*----------------------------------------------------------------------------
    ; GLOBAL FUNCTION DEFINITIONS
    ; Function Prototype declaration
    ----------------------------------------------------------------------------*/

    Word16
    Qua_gain(                   /* o  : index of quantization.                 */
        enum Mode mode,         /* i  : AMR mode                               */
        Word16 exp_gcode0,      /* i  : predicted CB gain (exponent),      Q0  */
        Word16 frac_gcode0,     /* i  : predicted CB gain (fraction),      Q15 */
        Word16 frac_coeff[],    /* i  : energy coeff. (5), fraction part,  Q15 */
        Word16 exp_coeff[],     /* i  : energy coeff. (5), exponent part,  Q0  */
        /*      (frac_coeff and exp_coeff computed in  */
        /*       calc_filt_energies())                 */
        Word16 gp_limit,        /* i  : pitch gain limit                       */
        Word16 *gain_pit,       /* o  : Pitch gain,                        Q14 */
        Word16 *gain_cod,       /* o  : Code gain,                         Q1  */
        Word16 *qua_ener_MR122, /* o  : quantized energy error,            Q10 */
        /*      (for MR122 MA predictor update)        */
        Word16 *qua_ener,       /* o  : quantized energy error,            Q10 */
        /*      (for other MA predictor update)        */
        Flag   *pOverflow       /* o  : overflow indicator                     */
    );
    /*----------------------------------------------------------------------------
    ; END
    ----------------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif

#endif /* qua_gain_h */


text:
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="openslide-tools" \
    base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
    container="openslide-tools" \
    about.summary="Manipulation and conversion tools for OpenSlide" \
    about.home="http://openslide.org" \
    software.version="3.4.1dfsg-4-deb" \
    upstream.version="3.4.1" \
    version="1" \
    about.copyright=" 2007-2015 Carnegie Mellon University" \
    about.license="LGPL-2.1" \
    about.license_file="/usr/share/doc/openslide-tools/copyright" \
    extra.binaries="/usr/bin/openslide-quickhash1sum,/usr/bin/openslide-show-properties,/usr/bin/openslide-write-png" \
    about.tags="role::program, scope::utility"

USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y openslide-tools || apt-get install -y openslide-tools) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
<Record>
<Term>Sodium lactate</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Sodium lactate</Synonym>
<Synonym>Sodium lactate 16 molar in plastic container</Synonym>
<Synonym>Sodium lactate 0.167 molar</Synonym>
<Synonym>Sodium lactate 16 molar</Synonym>
<Synonym>Sodium lactate 0.167 molar in plastic container</Synonym>
<Synonym>Sodium lactate in plastic container</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
package github.banana.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Zookeeper 简单调用
 */
@Slf4j
public class ZookeeperTest {

    // 信号量, 用户阻塞线程执行
    private static final CountDownLatch latch = new CountDownLatch(1);

    // zk 实例
    private static ZooKeeper zk = null;

    /**
     * 创建连接, 相当耗时
     *
     * @throws IOException IOException
     */
    private void connection() throws IOException {
        // Zookeeper 监听采用子线程方式, 需要确保主线程得到同步信息
        if (zk == null) {
            zk = new ZooKeeper("127.0.0.1:2181", 2000, (event) -> {
                // 当前zk状态
                Watcher.Event.KeeperState state = event.getState();
                // zk状态建立连接
                if (state == Watcher.Event.KeeperState.SyncConnected) {
                    // 当前连接路径
                    String path = event.getPath();
                    // 当前事件通知类型
                    Watcher.Event.EventType type = event.getType();
                    // 启动连接
                    if (type == Watcher.Event.EventType.None) {
                        log.info("Zookeeper 已经启动...");
                        latch.countDown();
                    } else if (type == Watcher.Event.EventType.NodeCreated) {
                        log.info("新建节点: " + path);
                    } else if (type == Watcher.Event.EventType.NodeDataChanged) {
                        log.info("节点发生变更: " + path);
                    } else if (type == Watcher.Event.EventType.NodeDeleted) {
                        log.info("节点被删除: " + path);
                    }
                }
            });
        }
    }

    private String createNode(String path, String content) throws KeeperException, InterruptedException {
        return zk.create(path, content.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    private Stat updateNode(String path, String content) throws KeeperException, InterruptedException {
        return zk.setData(path, content.getBytes(), -1);
    }

    private void deleteNode(String path) throws KeeperException, InterruptedException {
        zk.delete(path, -1);
    }

    private Stat exist(String path, boolean isWatcher) throws KeeperException, InterruptedException {
        return zk.exists(path, isWatcher);
    }

    private void close() throws InterruptedException {
        if (zk != null) {
            zk.close();
        }
    }

    public static void main(String[] args) {
        ZookeeperTest test = new ZookeeperTest();
        try {
            // 1. 创建 zk 连接
            log.info("1. 创建 zk 连接");
            test.connection();

            // 2. 确保 zk 创建完成
            log.info("2. 确保 zk 创建完成");
            latch.await();

            String path = "/test_node";
            String content = "this is a test node";
            boolean watcher = true;

            // 3. 删除节点如果存在
            // 如果节点存在则返回节点信息, 节点不存在返回null
            log.info("删除节点如果存在: {}", path);
            if (test.exist(path, watcher) != null) {
                test.deleteNode(path);
                log.info("节点 {} 删除完毕", path);
            }

            // 4. 新增节点
            log.info("4. 新增节点, path= {}, content= {}", path, content);
            Stat stat = test.exist(path, watcher);
            if (stat == null) {
                String nodeDesc = test.createNode(path, content);
                log.info("新增节点: {}", nodeDesc);
            }

            // 5. 修改节点
            String content1 = "update node";
            log.info("5. 修改节点, path= {}, update content= {}", path, content1);
            if (test.exist(path, watcher) != null) {
                Stat stat1 = test.updateNode(path, content1);
                log.info("更新后的节点信息: {}", stat1);
            }

            // 6. 关闭zk
            test.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
set -o errexit      # exit immediately if command exits with a non-zero status
set -x             # essentially debug mode

. ./pgpoolenv.sh

# Optionally over-ride default version of Postgres client which is provided locally.

POSTGRES_VERSION=${1:-${POSTGRES_VERSION}}

# Add the PostgreSQL PGP key to verify their Debian packages.
# It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc
sudo wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | \
      sudo apt-key add -

# Add PostgreSQL's repository. It contains the most recent stable release
#     of PostgreSQL, ``9.5``.
echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -sc)-pgdg main" | sudo tee --append /etc/apt/sources.list.d/pgdg.list

sudo sudo apt-get update

sudo sudo apt-get -y -q install postgresql-client-${POSTGRES_VERSION} libpq5 libpq-dev


text:
package com.test.repository;

import com.test.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;

/**
 * Created by rodbate on 2015/10/22.
 */
@Configuration
@EnableJpaRepositories
public interface UserRepository extends CrudRepository<User,Integer>{

}


text:
require 'rspec'
require 'i3/blocks/whats_playing'

describe I3::Blocks::WhatsPlaying do

end


text:
require 'chefspec'
require 'chefspec/berkshelf'

# rubocop:disable Metrics/BlockLength

ChefSpec::Coverage.start!

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
  config.order = 'random'
  config.platform = 'ubuntu'
  config.version = '16.04'
  ENV['USERNAME'] = 'foo'
  ENV['USER'] = 'foo'

  config.before(:each) do
    stub_data_bag_item('teamcity', 'buildagent_creds').and_return(
      username: 'teamcity',
      password: 'barword',
      domain_username: 'domain\user',
      domain_password: 'domain_pass',
      ssh_private_key: 'fookey',
      chef_ssh_private_key: 'barkey',
      github_username: 'foohub',
      github_email: 'barmail',
      github_token: 'fooward'
    )
    stub_data_bag_item('teamcity', 'npm_auth_token').and_return(
      auth_token: 'fake_auth_token'
    )
    stub_data_bag_item('docker', 'dockerhub').and_return(
      username: 'user',
      password: 'pass',
      email: 'user@email.com'
    )
    stub_data_bag_item('teamcity', 'npm_auth_token').and_return(
      auth_token: 'gobledeegook'
    )
    stub_command('getent group docker').and_return(true)
    stub_command('docker --help').and_return(true)
    stub_command("npm -v 2>&1 | grep '6.14.13'").and_return(true)
  end
end