text:
package org.apache.ignite.internal.processors.cache.distributed.dht.atomic;

import java.io.Externalizable;
import java.nio.ByteBuffer;
import java.util.UUID;
import javax.cache.processor.EntryProcessor;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.GridCacheDeployable;
import org.apache.ignite.internal.processors.cache.GridCacheIdMessage;
import org.apache.ignite.internal.processors.cache.GridCacheOperation;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 *
 */
public abstract class GridDhtAtomicAbstractUpdateRequest extends GridCacheIdMessage implements GridCacheDeployable {
    /** Skip store flag bit mask. */
    protected static final int DHT_ATOMIC_SKIP_STORE_FLAG_MASK = 0x01;

    /** Keep binary flag. */
    protected static final int DHT_ATOMIC_KEEP_BINARY_FLAG_MASK = 0x02;

    /** Near cache key flag. */
    protected static final int DHT_ATOMIC_NEAR_FLAG_MASK = 0x04;

    /** */
    static final int DHT_ATOMIC_HAS_RESULT_MASK = 0x08;

    /** */
    private static final int DHT_ATOMIC_REPLY_WITHOUT_DELAY = 0x10;

    /** */
    protected static final int DHT_ATOMIC_OBSOLETE_NEAR_KEY_FLAG_MASK = 0x20;

    /** Flag indicating transformation operation was performed. */
    protected static final int DHT_ATOMIC_TRANSFORM_OP_FLAG_MASK = 0x40;

    /** Message index. */
    public static final int CACHE_MSG_IDX = nextIndexId();

    /** Future ID on primary. */
    protected long futId;

    /** Write version. */
    protected GridCacheVersion writeVer;

    /** Write synchronization mode. */
    protected CacheWriteSynchronizationMode syncMode;

    /** Topology version. */
    protected AffinityTopologyVersion topVer;

    /** Subject ID. */
    protected UUID subjId;

    /** Task name hash. */
    protected int taskNameHash;

    /** Node ID. */
    @GridDirectTransient
    protected UUID nodeId;

    /** On response flag. Access should be synced on future. */
    @GridDirectTransient
    private boolean onRes;

    /** */
    private UUID nearNodeId;

    /** */
    private long nearFutId;

    /** Additional flags. */
    protected byte flags;

    /**
     * Empty constructor required by {@link Externalizable}.
     */
    protected GridDhtAtomicAbstractUpdateRequest() {
        // N-op.
    }

    /**
     * Constructor.
     *
     * @param cacheId Cache ID.
     * @param nodeId Node ID.
     */
    protected GridDhtAtomicAbstractUpdateRequest(int cacheId,
        UUID nodeId,
        long futId,
        GridCacheVersion writeVer,
        CacheWriteSynchronizationMode syncMode,
        @NotNull AffinityTopologyVersion topVer,
        UUID subjId,
        int taskNameHash,
        boolean addDepInfo,
        boolean keepBinary,
        boolean skipStore
    ) {
        assert topVer.topologyVersion() > 0 : topVer;

        this.cacheId = cacheId;
        this.nodeId = nodeId;
        this.futId = futId;
        this.writeVer = writeVer;
        this.syncMode = syncMode;
        this.topVer = topVer;
        this.subjId = subjId;
        this.taskNameHash = taskNameHash;
        this.addDepInfo = addDepInfo;

        if (skipStore)
            setFlag(true, DHT_ATOMIC_SKIP_STORE_FLAG_MASK);
        if (keepBinary)
            setFlag(true, DHT_ATOMIC_KEEP_BINARY_FLAG_MASK);
    }

    /** {@inheritDoc} */
    @Override public final AffinityTopologyVersion topologyVersion() {
        return topVer;
    }

    /**
     * @param nearNodeId Near node ID.
     * @param nearFutId Future ID on near node.
     */
    void nearReplyInfo(UUID nearNodeId, long nearFutId) {
        assert nearNodeId != null;

        this.nearNodeId = nearNodeId;
        this.nearFutId = nearFutId;
    }

    /**
     * @return {@code True} if backups should reply immediately.
     */
    boolean replyWithoutDelay() {
        return isFlag(DHT_ATOMIC_REPLY_WITHOUT_DELAY);
    }

    /**
     * @param replyWithoutDelay {@code True} if backups should reply immediately.
     */
    void replyWithoutDelay(boolean replyWithoutDelay) {
        setFlag(replyWithoutDelay, DHT_ATOMIC_REPLY_WITHOUT_DELAY);
    }

    /**
     * @param res Result flag.
     */
    void hasResult(boolean res) {
        setFlag(res, DHT_ATOMIC_HAS_RESULT_MASK);
    }

    /**
     * @return Result flag.
     */
    private boolean hasResult() {
        return isFlag(DHT_ATOMIC_HAS_RESULT_MASK);
    }

    /**
     * @return Near node ID.
     */
    public UUID nearNodeId() {
        return nearNodeId;
    }

    /** {@inheritDoc} */
    @Override public int lookupIndex() {
        return CACHE_MSG_IDX;
    }

    /**
     * @return Node ID.
     */
    public UUID nodeId() {
        return nodeId;
    }

    /**
     * @return Flags.
     */
    public final byte flags() {
        return flags;
    }

    /**
     * @return Keep binary flag.
     */
    public final boolean keepBinary() {
        return isFlag(DHT_ATOMIC_KEEP_BINARY_FLAG_MASK);
    }

    /**
     * @return Skip write-through to a persistent storage.
     */
    public final boolean skipStore() {
        return isFlag(DHT_ATOMIC_SKIP_STORE_FLAG_MASK);
    }

    /**
     * @return {@code True} if transformation operation was performed.
     */
    public final boolean transformOperation() {
        return isFlag(DHT_ATOMIC_TRANSFORM_OP_FLAG_MASK);
    }

    /**
     * @return {@code True} if on response flag changed.
     */
    public boolean onResponse() {
        return !onRes && (onRes = true);
    }

    /**
     * @return {@code True} if response was received.
     */
    boolean hasResponse() {
        return onRes;
    }

    /** {@inheritDoc} */
    @Override public boolean addDeploymentInfo() {
        return addDepInfo;
    }

    /**
     * @return Force transform backups flag.
     */
    public abstract boolean forceTransformBackups();

    /** {@inheritDoc} */
    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
        return ctx.atomicMessageLogger();
    }

    /** {@inheritDoc} */
    @Override public void onAckReceived() {
        cleanup();
    }

    /**
     * @param key Key to add.
     * @param val Value, {@code null} if should be removed.
     * @param entryProcessor Entry processor.
     * @param ttl TTL (optional).
     * @param conflictExpireTime Conflict expire time (optional).
     * @param conflictVer Conflict version (optional).
     * @param addPrevVal If {@code true} adds previous value.
     * @param prevVal Previous value.
     * @param updateCntr Update counter.
     * @param cacheOp Corresponding cache operation.
     */
    public abstract void addWriteValue(KeyCacheObject key,
        @Nullable CacheObject val,
        EntryProcessor<Object, Object, Object> entryProcessor,
        long ttl,
        long conflictExpireTime,
        @Nullable GridCacheVersion conflictVer,
        boolean addPrevVal,
        @Nullable CacheObject prevVal,
        long updateCntr,
        GridCacheOperation cacheOp);

    /**
     * @param key Key to add.
     * @param val Value, {@code null} if should be removed.
     * @param entryProcessor Entry processor.
     * @param ttl TTL.
     * @param expireTime Expire time.
     */
    public abstract void addNearWriteValue(KeyCacheObject key,
        @Nullable CacheObject val,
        EntryProcessor<Object, Object, Object> entryProcessor,
        long ttl,
        long expireTime);

    /**
     * Cleanup values not needed after message was sent.
     */
    protected abstract void cleanup();

    /**
     * @return Subject ID.
     */
    public final UUID subjectId() {
        return subjId;
    }

    /**
     * @return Task name.
     */
    public final int taskNameHash() {
        return taskNameHash;
    }

    /**
     * @return Future ID on primary node.
     */
    public final long futureId() {
        return futId;
    }

    /**
     * @return Future ID on near node.
     */
    public final long nearFutureId() {
        return nearFutId;
    }

    /**
     * @return Write version.
     */
    public final GridCacheVersion writeVersion() {
        return writeVer;
    }

    /**
     * @return Cache write synchronization mode.
     */
    public final CacheWriteSynchronizationMode writeSynchronizationMode() {
        return syncMode;
    }

    /**
     * @return Keys size.
     */
    public abstract int size();

    /**
     * @return Keys size.
     */
    public abstract int nearSize();

    /**
     * @param key Key to check.
     * @return {@code true} if request keys contain key.
     */
    public abstract boolean hasKey(KeyCacheObject key);

    /**
     * @param idx Key index.
     * @return Key.
     */
    public abstract KeyCacheObject key(int idx);

    /**
     * @return Obsolete near cache keys size.
     */
    public abstract int obsoleteNearKeysSize();

    /**
     * @param idx Obsolete near cache key index.
     * @return Obsolete near cache key.
     */
    public abstract KeyCacheObject obsoleteNearKey(int idx);

    /**
     * @param updCntr Update counter.
     * @return Update counter.
     */
    public abstract Long updateCounter(int updCntr);

    /**
     * @param idx Near key index.
     * @return Key.
     */
    public abstract KeyCacheObject nearKey(int idx);

    /**
     * @param idx Key index.
     * @return Value.
     */
    @Nullable public abstract CacheObject value(int idx);

    /**
     * @param idx Key index.
     * @return Value.
     */
    @Nullable public abstract CacheObject previousValue(int idx);

    /**
     * @param idx Key index.
     * @return Entry processor.
     */
    @Nullable public abstract EntryProcessor<Object, Object, Object> entryProcessor(int idx);

    /**
     * @param idx Near key index.
     * @return Value.
     */
    @Nullable public abstract CacheObject nearValue(int idx);

    /**
     * @param idx Key index.
     * @return Transform closure.
     */
    @Nullable public abstract EntryProcessor<Object, Object, Object> nearEntryProcessor(int idx);

    /**
     * @param idx Index.
     * @return Conflict version.
     */
    @Nullable public abstract GridCacheVersion conflictVersion(int idx);

    /**
     * @param idx Index.
     * @return TTL.
     */
    public abstract long ttl(int idx);

    /**
     * @param idx Index.
     * @return TTL for near cache update.
     */
    public abstract long nearTtl(int idx);

    /**
     * @param idx Index.
     * @return Conflict expire time.
     */
    public abstract long conflictExpireTime(int idx);

    /**
     * @param idx Index.
     * @return Expire time for near cache update.
     */
    public abstract long nearExpireTime(int idx);

    /**
     * @return Optional arguments for entry processor.
     */
    @Nullable public abstract Object[] invokeArguments();

    /**
     * Sets flag mask.
     *
     * @param flag Set or clear.
     * @param mask Mask.
     */
    protected final void setFlag(boolean flag, int mask) {
        flags = flag ? (byte)(flags | mask) : (byte)(flags & ~mask);
    }

    /**
     * Reags flag mask.
     *
     * @param mask Mask to read.
     * @return Flag value.
     */
    final boolean isFlag(int mask) {
        return (flags & mask) != 0;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 12;
    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!super.writeTo(buf, writer))
            return false;

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 3:
                if (!writer.writeByte("flags", flags))
                    return false;

                writer.incrementState();

            case 4:
                if (!writer.writeLong("futId", futId))
                    return false;

                writer.incrementState();

            case 5:
                if (!writer.writeLong("nearFutId", nearFutId))
                    return false;

                writer.incrementState();

            case 6:
                if (!writer.writeUuid("nearNodeId", nearNodeId))
                    return false;

                writer.incrementState();

            case 7:
                if (!writer.writeUuid("subjId", subjId))
                    return false;

                writer.incrementState();

            case 8:
                if (!writer.writeByte("syncMode", syncMode != null ? (byte)syncMode.ordinal() : -1))
                    return false;

                writer.incrementState();

            case 9:
                if (!writer.writeInt("taskNameHash", taskNameHash))
                    return false;

                writer.incrementState();

            case 10:
                if (!writer.writeMessage("topVer", topVer))
                    return false;

                writer.incrementState();

            case 11:
                if (!writer.writeMessage("writeVer", writeVer))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        if (!super.readFrom(buf, reader))
            return false;

        switch (reader.state()) {
            case 3:
                flags = reader.readByte("flags");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 4:
                futId = reader.readLong("futId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 5:
                nearFutId = reader.readLong("nearFutId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 6:
                nearNodeId = reader.readUuid("nearNodeId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 7:
                subjId = reader.readUuid("subjId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 8:
                byte syncModeOrd;

                syncModeOrd = reader.readByte("syncMode");

                if (!reader.isLastRead())
                    return false;

                syncMode = CacheWriteSynchronizationMode.fromOrdinal(syncModeOrd);

                reader.incrementState();

            case 9:
                taskNameHash = reader.readInt("taskNameHash");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 10:
                topVer = reader.readMessage("topVer");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 11:
                writeVer = reader.readMessage("writeVer");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(GridDhtAtomicAbstractUpdateRequest.class);
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        StringBuilder flags = new StringBuilder();

        if (skipStore())
            appendFlag(flags, "skipStore");
        if (keepBinary())
            appendFlag(flags, "keepBinary");
        if (isFlag(DHT_ATOMIC_NEAR_FLAG_MASK))
            appendFlag(flags, "near");
        if (hasResult())
            appendFlag(flags, "hasRes");
        if (replyWithoutDelay())
            appendFlag(flags, "resNoDelay");

        return S.toString(GridDhtAtomicAbstractUpdateRequest.class, this,
            "flags", flags.toString());
    }
}


text:
const calculateStyles = ({bbCodes}) => {
    const {common, quote} = bbCodes;
    return {
        author: {
            fontWeight: 'bold'
        },
        quote: {
            backgroundColor: quote.backgroundColor,
            borderColor: quote.borderColor,
            borderStyle: 'solid',
            borderWidth: common.borderWidth,
            padding: common.padding,
            marginLeft: common.marginHorizontal,
            marginRight: common.marginHorizontal,
            marginTop: common.marginVertical,
            marginBottom: common.marginVertical
        }
    };
};

export default calculateStyles;

redpajama_set_name: RedPajamaGithub


text:
namespace MvcApi//System.Web.Mvc.Async
{
    #region Using Directives
    using System;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime.CompilerServices;
    using System.Threading;
    using System.Web.Mvc;
    using System.Web.Mvc.Async;
    using MvcApi;
    #endregion

    internal static class AsyncResultWrapper
    {
        #region Nested Type

        [DebuggerNonUserCode, SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The Timer will be disposed of either when it fires or when the operation completes successfully.")]
        private sealed class WrappedAsyncResult<TResult> : IAsyncResult
        {
            private readonly BeginInvokeDelegate _beginDelegate;
            private readonly object _beginDelegateLockObj;
            private readonly EndInvokeDelegate<TResult> _endDelegate;
            private readonly SingleEntryGate _endExecutedGate;
            private readonly SingleEntryGate _handleCallbackGate;
            private IAsyncResult _innerAsyncResult;
            private AsyncCallback _originalCallback;
            private readonly object _tag;
            private volatile bool _timedOut;
            private Timer _timer;

            public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag)
            {
                this._beginDelegateLockObj = new object();
                this._endExecutedGate = new SingleEntryGate();
                this._handleCallbackGate = new SingleEntryGate();
                this._beginDelegate = beginDelegate;
                this._endDelegate = endDelegate;
                this._tag = tag;
            }

            public void Begin(AsyncCallback callback, object state, int timeout)
            {
                bool completedSynchronously;
                this._originalCallback = callback;
                lock (this._beginDelegateLockObj)
                {
                    this._innerAsyncResult = this._beginDelegate(new AsyncCallback(this.HandleAsynchronousCompletion), state);
                    completedSynchronously = this._innerAsyncResult.CompletedSynchronously;
                    if (!completedSynchronously && (timeout > -1))
                    {
                        this.CreateTimer(timeout);
                    }
                }
                if (completedSynchronously && (callback != null))
                {
                    callback(this);
                }
            }

            public static AsyncResultWrapper.WrappedAsyncResult<TResult> Cast(IAsyncResult asyncResult, object tag)
            {
                if (asyncResult == null)
                {
                    throw new ArgumentNullException("asyncResult");
                }
                AsyncResultWrapper.WrappedAsyncResult<TResult> result = asyncResult as AsyncResultWrapper.WrappedAsyncResult<TResult>;
                if ((result == null) || !object.Equals(result._tag, tag))
                {
                    throw Error.AsyncCommon_InvalidAsyncResult("asyncResult");
                }
                return result;
            }

            private void CreateTimer(int timeout)
            {
                this._timer = new Timer(new TimerCallback(this.HandleTimeout), null, timeout, -1);
            }

            public TResult End()
            {
                if (!this._endExecutedGate.TryEnter())
                {
                    throw Error.AsyncCommon_AsyncResultAlreadyConsumed();
                }
                if (this._timedOut)
                {
                    throw new TimeoutException();
                }
                this.WaitForBeginToCompleteAndDestroyTimer();
                return this._endDelegate(this._innerAsyncResult);
            }

            private void ExecuteAsynchronousCallback(bool timedOut)
            {
                this.WaitForBeginToCompleteAndDestroyTimer();
                if (this._handleCallbackGate.TryEnter())
                {
                    this._timedOut = timedOut;
                    if (this._originalCallback != null)
                    {
                        this._originalCallback(this);
                    }
                }
            }

            private void HandleAsynchronousCompletion(IAsyncResult asyncResult)
            {
                if (!asyncResult.CompletedSynchronously)
                {
                    this.ExecuteAsynchronousCallback(false);
                }
            }

            private void HandleTimeout(object state)
            {
                this.ExecuteAsynchronousCallback(true);
            }

            private void WaitForBeginToCompleteAndDestroyTimer()
            {
                lock (this._beginDelegateLockObj)
                {
                    if (this._timer != null)
                    {
                        this._timer.Dispose();
                    }
                    this._timer = null;
                }
            }

            public object AsyncState
            {
                get
                {
                    return this._innerAsyncResult.AsyncState;
                }
            }

            public WaitHandle AsyncWaitHandle
            {
                get
                {
                    return this._innerAsyncResult.AsyncWaitHandle;
                }
            }

            public bool CompletedSynchronously
            {
                get
                {
                    return this._innerAsyncResult.CompletedSynchronously;
                }
            }

            public bool IsCompleted
            {
                get
                {
                    return this._innerAsyncResult.IsCompleted;
                }
            }
        }

        #endregion

        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag)
        {
            return Begin(callback, state, beginDelegate, endDelegate, tag, -1);
        }

        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag, int timeout)
        {
            return Begin<AsyncVoid>(callback, state, beginDelegate, MakeVoidDelegate(endDelegate), tag, timeout);
        }

        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag)
        {
            return Begin<TResult>(callback, state, beginDelegate, endDelegate, tag, -1);
        }

        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag, int timeout)
        {
            WrappedAsyncResult<TResult> result = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag);
            result.Begin(callback, state, timeout);
            return result;
        }

        public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action, object tag)
        {
            return BeginSynchronous<AsyncVoid>(callback, state, MakeVoidDelegate(action), tag);
        }

        public static IAsyncResult BeginSynchronous<TResult>(AsyncCallback callback, object state, Func<TResult> func, object tag)
        {
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                SimpleAsyncResult simpleAsyncResult = new SimpleAsyncResult(asyncState);
                simpleAsyncResult.MarkCompleted(true, asyncCallback);
                return simpleAsyncResult;
            }
            ;
            EndInvokeDelegate<TResult> endDelegate = (IAsyncResult _) => func();
            AsyncResultWrapper.WrappedAsyncResult<TResult> wrappedAsyncResult = new AsyncResultWrapper.WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag);
            wrappedAsyncResult.Begin(callback, state, -1);
            return wrappedAsyncResult;
        }

        public static void End(IAsyncResult asyncResult, object tag)
        {
            End<AsyncVoid>(asyncResult, tag);
        }

        public static TResult End<TResult>(IAsyncResult asyncResult, object tag)
        {
            return WrappedAsyncResult<TResult>.Cast(asyncResult, tag).End();
        }

        private static Func<AsyncVoid> MakeVoidDelegate(Action action)
        {
            return delegate
            {
                action();
                return new AsyncVoid();
            };
        }

        private static EndInvokeDelegate<AsyncVoid> MakeVoidDelegate(EndInvokeDelegate endDelegate)
        {
            return delegate(IAsyncResult ar)
            {
                endDelegate(ar);
                return new AsyncVoid();
            };
        }

    }
}


text:
package com.zurrox.zybot.hitbox.workers;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A factory class for creating Workers when they are required.
 */
public class WorkerFactory {
    TaskQueue queue;
    List<Worker> workers = new CopyOnWriteArrayList<>();

    public WorkerFactory(TaskQueue queue) {
        this.queue = queue;
        newWorker(); //Initialize the factory with one worker.
    }

    /**
     * Starts a worker which currently is not running or creates one if none are available.
     */
    public void newWorker() {
        for (Worker worker : workers) {
            if (!worker.isRunning()) {
                worker.setRunning(true);
                worker.run();
                return;
            }
        }

        Worker worker = new Worker(queue);
        workers.add(worker);
        worker.start();
    }

    /**
     * Stop the last worker if there is at least one running.
     */
    public void stopWorker() {
        if (workers.size() > 2) workers.get(workers.size()).setRunning(false);
    }

    /**
     * Removes excess workers from the list of workers.
     */
    public void cleanupWorkers() {
        long inactiveWorkers;
        inactiveWorkers = workers.stream().filter(w -> !w.isRunning()).count();

        for (int i = 1; i < inactiveWorkers; i++) workers.remove(workers.size());
    }
}


text:
<?php

require __DIR__.'/Breadcrumbs/Backend/Backend.php';


text:
name: Bug report
about: Create a report to help us improve

---

<!--
Thanks for taking the time to open an issue!
Please provide a general summary of the issue in the title above .
-->

- [ ] I've looked at the [documentation](http://leafletjs.com/reference.html) to make sure the behavior is documented and expected
- [ ] I'm sure this is a Leaflet code issue, not an issue with my own code nor with the framework I'm using (Cordova, Ionic, Angular, React…)
- [ ] I've searched through the issues to make sure it's not yet reported

**Steps to reproduce**
Steps to reproduce the behavior:
- step 1
- step 2
- ...

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Current behavior**
<!-- A clear and concise description of what is actually happening. -->

**Environment**
- Leaflet version:
- Browser (with version):
- OS/Platform (with version):

**Additional context**
<!-- Add any other context about the problem here. -->

**Minimal example reproducing the issue**

Please create an example using https://leafletjs.com/edit.html or any other jsfiddle-like site.

- [ ] this example is as simple as possible
- [ ] this example does not rely on any third party code


text:
<?php

use yii\db\Migration;

class m170409_134020_add_colum_status_id_to_log extends Migration
{
    public function up()
    {
      $this->addColumn('log','status_id',$this->integer()->defaultValue(0));
      $this->alterColumn('log','description',$this->string(256));
    }

    public function down()
    {
      echo "m170409_134020_add_colum_status_id_to_log cannot be reverted.\n";
      $this->dropColumn('log', 'status_id');
      $this->alterColumn('log','description',$this->string(32));
      return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
namespace flutter {

class FlutterWindowsEngine;

// The Win32 implementation of AccessibilityBridgeDelegate.
//
// Handles requests from the accessibility bridge to interact with Windows
// accessibility APIs. This includes routing accessibility events fired from
// the framework to Windows, routing native Windows accessibility events to the
// framework, and creating Windows-specific FlutterPlatformNodeDelegate objects
// for each node in the semantics tree.
class AccessibilityBridgeDelegateWindows
    : public AccessibilityBridge::AccessibilityBridgeDelegate {
 public:
  explicit AccessibilityBridgeDelegateWindows(FlutterWindowsEngine* engine);
  virtual ~AccessibilityBridgeDelegateWindows() = default;

  // |AccessibilityBridge::AccessibilityBridgeDelegate|
  void OnAccessibilityEvent(
      ui::AXEventGenerator::TargetedEvent targeted_event) override;

  // |AccessibilityBridge::AccessibilityBridgeDelegate|
  void DispatchAccessibilityAction(AccessibilityNodeId target,
                                   FlutterSemanticsAction action,
                                   fml::MallocMapping data) override;

  // |AccessibilityBridge::AccessibilityBridgeDelegate|
  std::shared_ptr<FlutterPlatformNodeDelegate>
  CreateFlutterPlatformNodeDelegate() override;

  // Dispatches a Windows accessibility event of the specified type, generated
  // by the accessibility node associated with the specified semantics node.
  virtual void DispatchWinAccessibilityEvent(
      std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate,
      DWORD event_type);

  // Sets the accessibility focus to the accessibility node associated with the
  // specified semantics node.
  virtual void SetFocus(
      std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate);

 private:
  FlutterWindowsEngine* engine_;
};

}  // namespace flutter

#endif  // FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_BRIDGE_DELEGATE_H_


text:
module ArelExtension
  VERSION = "2.0.1"
end


text:
import { RemoteFunction, RemoteFunctionRole } from 'src/util/webextensionRPC'

export interface InPageUIInterface<Role extends RemoteFunctionRole> {
    showSidebar: RemoteFunction<Role, {}>
    openDashboard: RemoteFunction<Role, void>
    updateContextMenuEntries: RemoteFunction<Role, void>
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using LanguageExt.Common;
using LanguageExt.TypeClasses;
using static LanguageExt.Prelude;

namespace LanguageExt.ClassInstances
{
    public static class EqAsyncClass
    {
        public static Task<bool> EqualsAsync<A>(A x, A y) => EqAsyncClass<A>.EqualsAsync(x, y);
        public static Task<int> GetHashCodeAsync<A>(A x, A y) => EqAsyncClass<A>.GetHashCodeAsync(x);
    }

    public static class EqAsyncClass<A>
    {
        public static readonly Option<Error> Error;
        public static readonly Func<A, A, Task<bool>> EqualsAsync;

        static EqAsyncClass()
        {
            try
            {
                var (fullName, name, gens) = ClassFunctions.GetTypeInfo<A>();
                name = ClassFunctions.RemoveAsync(name);

                EqualsAsync = ClassFunctions.MakeFunc2<A, A, Task<bool>>(name, "EqualsAsync", gens,
                    ("Eq", "Async"), ("Ord", "Async"),
                    ("Eq", ""), ("Ord", "")
                    );

                if (EqualsAsync == null && EqClass<A>.Error.IsNone)
                {
                    EqualsAsync = EqClass<A>.EqualsAsync;
                }

                if (EqualsAsync == null)
                {
                    EqualsAsync = (A x, A y) => throw new NotSupportedException(
                        $"Neither Eq{name}Async, Ord{name}Async, Eq{name}, nor Ord{name} instance found for {fullName} (EqualsAsync)"
                    );
                }
            }
            catch (Exception e)
            {
                Error = Some(Common.Error.New(e));
                EqualsAsync = (A x, A y) => throw e;
            }
        }

        public static Task<int> GetHashCodeAsync(A x) =>
            HashableAsyncClass<A>.GetHashCodeAsync(x);
    }
}


text: Schematic Symbols for KiCad


text:
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.Tag;

import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriteriumCreator;
import com.google.security.zynamics.binnavi.Tagging.ITagManager;

/**
 * Factory class for Tag state criteria objects.
 */
public final class CTagCriteriumCreator implements ICriteriumCreator {
  /**
   * Tag manager that provides tagging information.
   */
  private final ITagManager m_tagManager;

  /**
   * Creates a new creator object.
   *
   * @param tagManager Tag manager that provides tagging information.
   */
  public CTagCriteriumCreator(final ITagManager tagManager) {
    m_tagManager = tagManager;
  }

  @Override
  public ICriterium createCriterium() {
    return new CTagCriterium(m_tagManager);
  }

  @Override
  public String getCriteriumDescription() {
    return "Select Nodes by Tag";
  }
}


text:
package gudusoft.gsqlparser.sql2xml.model;

public class host_parameter_declaration_list
{

}


text:
package training.maven.quick;

import org.apache.commons.lang3.StringUtils;

public class Application {

    public Application() {

    }

    public int countWords(String words) {
        String[] separateWords = StringUtils.split(words, ' ');
        return (separateWords == null) ? 0 : separateWords.length;
    }
}


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from hashedindex import __version__

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

test_requirements = [
    'wheel',
    'pytest',
]

setup(
    name='hashedindex',
    version=__version__,
    description="InvertedIndex implementation using hash lists (dictionaries)",
    long_description=readme + '\n\n' + history,
    author="Michael Aquilina",
    author_email='michaelaquilina@gmail.com',
    url='https://github.com/MichaelAquilina/hashedindex',
    packages=[
        'hashedindex',
    ],
    package_dir={'hashedindex':
                 'hashedindex'},
    include_package_data=True,
    license="BSD",
    zip_safe=False,
    keywords='hashedindex',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    test_suite='tests',
    setup_requires=['pytest-runner'],
    tests_require=test_requirements
)


text:
<?php

namespace Oro\Bundle\CalendarBundle\Tests\Unit\Manager;

use Doctrine\Persistence\ManagerRegistry;
use Oro\Bundle\CalendarBundle\Entity\Attendee as AttendeeEntity;
use Oro\Bundle\CalendarBundle\Manager\AttendeeRelationManager;
use Oro\Bundle\CalendarBundle\Tests\Unit\Fixtures\Entity\Attendee;
use Oro\Bundle\CalendarBundle\Tests\Unit\Fixtures\Entity\User;
use Oro\Bundle\LocaleBundle\DQL\DQLNameFormatter;
use Oro\Bundle\LocaleBundle\Formatter\NameFormatter;
use Oro\Bundle\UserBundle\Entity\Email;
use Oro\Bundle\UserBundle\Entity\Repository\UserRepository;

class AttendeeRelationManagerTest extends \PHPUnit\Framework\TestCase
{
    /** @var User[] */
    private $users;

    /** @var AttendeeRelationManager */
    private $attendeeRelationManager;

    protected function setUp(): void
    {
        $this->users = [
            'u1@example.com' => (new User())->setEmail('u1@example.com'),
            'u2@example.com' => (new User())->addEmail((new Email())->setEmail('u2@example.com')),
            'u3@example.com' => (new User())->setEmail('u3@example.com'),
            'u4@example.com' => (new User())->setEmail('u4@example.com'),
        ];

        $userRepository = $this->createMock(UserRepository::class);
        $userRepository->expects($this->any())
            ->method('findUsersByEmailsAndOrganization')
            ->willReturnCallback(function (array $emails) {
                return array_values(array_intersect_key($this->users, array_flip($emails)));
            });

        $registry = $this->createMock(ManagerRegistry::class);
        $registry->expects($this->any())
            ->method('getRepository')
            ->with('OroUserBundle:User')
            ->willReturn($userRepository);

        $nameFormatter = $this->createMock(NameFormatter::class);
        $nameFormatter->expects($this->any())
            ->method('format')
            ->willReturnCallback(function ($person) {
                return $person->getFullName();
            });

        $dqlNameFormatter = $this->createMock(DQLNameFormatter::class);

        $this->attendeeRelationManager = new AttendeeRelationManager(
            $registry,
            $nameFormatter,
            $dqlNameFormatter
        );
    }

    public function testSetRelatedEntityWithUserWorks()
    {
        $attendee = new Attendee();

        $user = new User();
        $user
            ->setFirstName('John')
            ->setLastName('Doe')
            ->setEmail('john.doe@example.com');

        $this->attendeeRelationManager->setRelatedEntity($attendee, $user);

        $this->assertEquals('John Doe', $attendee->getDisplayName());
        $this->assertEquals('john.doe@example.com', $attendee->getEmail());
        $this->assertSame($user, $attendee->getUser());
    }

    public function testSetRelatedEntityWithIncorrectTypeFails()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage(
            'Related entity must be an instance of "Oro\Bundle\UserBundle\Entity\User", "stdClass" is given.'
        );

        $attendee = new Attendee();

        $entity = new \stdClass();

        $this->attendeeRelationManager->setRelatedEntity($attendee, $entity);
    }

    public function setRelatedEntityDataProvider(): array
    {
        $attendee = new Attendee();
        $user = (new User())
            ->setFirstName('first')
            ->setLastName('last')
            ->setEmail('email@example.com');

        return [
            [
                null,
                $attendee
            ],
            [
                $user,
                $attendee,
                (new AttendeeEntity())
                    ->setDisplayName('first last')
                    ->setEmail('email@example.com')
                    ->setUser($user),
            ]
        ];
    }

    public function testGetRelatedEntity()
    {
        $user = new User();
        $attendee = (new Attendee())
            ->setUser($user);

        $this->assertSame($user, $this->attendeeRelationManager->getRelatedEntity($attendee));
    }

    /**
     * @dataProvider getDisplayNameProvider
     */
    public function testGetDisplayName(Attendee $attendee, string $expectedDisplayName)
    {
        $this->assertEquals($expectedDisplayName, $this->attendeeRelationManager->getDisplayName($attendee));
    }

    public function getDisplayNameProvider(): array
    {
        return [
            [
                (new Attendee())
                    ->setDisplayName('display name'),
                'display name'
            ],
            [
                (new Attendee())
                    ->setUser(
                        (new User())
                            ->setFirstName('first')
                            ->setLastName('last')
                    ),
                'first last'
            ],
            [
                (new Attendee())
                    ->setDisplayName('display name')
                    ->setUser(
                        (new User())
                            ->setFirstName('first')
                            ->setLastName('last')
                    ),
                'first last'
            ],
        ];
    }

    public function testBindAttendees()
    {
        $attendees = $this->getInitialAttendees();
        $this->attendeeRelationManager->bindAttendees($attendees);

        $this->assertEquals($this->getExpectedAttendees(), $attendees);
    }

    private function getInitialAttendees(): array
    {
        return [
            (new Attendee(1))
                ->setEmail('u1@example.com'),
            (new Attendee())
                ->setEmail('u2@example.com'),
            (new Attendee())
                ->setEmail('u3@example.com'),
            (new Attendee())
                ->setEmail('nonExisting@example.com'),
            (new Attendee())
                ->setEmail('u4@example.com')
                ->setUser(new User()),
        ];
    }

    private function getExpectedAttendees(): array
    {
        return [
            (new Attendee(1))
                ->setEmail('u1@example.com')
                 ->setUser($this->users['u1@example.com'])
                 ->setDisplayName($this->users['u1@example.com']->getFullName()),
            (new Attendee())
                ->setEmail('u2@example.com')
                ->setUser($this->users['u2@example.com'])
                ->setDisplayName($this->users['u2@example.com']->getFullName()),
            (new Attendee())
                ->setEmail('u3@example.com')
                ->setUser($this->users['u3@example.com'])
                ->setDisplayName($this->users['u3@example.com']->getFullName()),
            (new Attendee())
                ->setEmail('nonExisting@example.com'),
            (new Attendee())
                ->setEmail('u4@example.com')
                ->setUser(new User()),
        ];
    }
}


text:
var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('styles', function() {
  gulp.src('./content/themes/casper/assets/sass/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./content/themes/casper/assets/css'));
});

gulp.task('default', function() {
  gulp.watch('./content/themes/casper/assets/**/*.scss', ['styles']);
});


text:
package net.wolfgangwerner.kata.set;

public class Game {
    public static void main(String[] args) {
        Stack d = new Stack();

        System.out.println(d);
    }
}


text:
package com.bolyartech.forge.admin.units.user.users;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;

import com.bolyartech.forge.admin.R;

public class DfNoUserFound extends DialogFragment {
    public static final String DIALOG_TAG = "Df_NoUserFound";

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
        b.setMessage(R.string.dlg__no_user_found_msg);
        b.setCancelable(false);
        b.setNeutralButton(R.string.global_btn_close, null);
        return b.create();
    }
}


text:
"""Support for LCN sensors."""
import pypck

from homeassistant.const import CONF_ADDRESS, CONF_SOURCE, CONF_UNIT_OF_MEASUREMENT

from . import LcnEntity
from .const import (
    CONF_CONNECTIONS,
    DATA_LCN,
    LED_PORTS,
    S0_INPUTS,
    SETPOINTS,
    THRESHOLDS,
    VARIABLES,
)
from .helpers import get_connection

async def async_setup_platform(
    hass, hass_config, async_add_entities, discovery_info=None
):
    """Set up the LCN sensor platform."""
    if discovery_info is None:
        return

    devices = []
    for config in discovery_info:
        address, connection_id = config[CONF_ADDRESS]
        addr = pypck.lcn_addr.LcnAddr(*address)
        connections = hass.data[DATA_LCN][CONF_CONNECTIONS]
        connection = get_connection(connections, connection_id)
        device_connection = connection.get_address_conn(addr)

        if config[CONF_SOURCE] in VARIABLES + SETPOINTS + THRESHOLDS + S0_INPUTS:
            device = LcnVariableSensor(config, device_connection)
        else:  # in LED_PORTS + LOGICOP_PORTS
            device = LcnLedLogicSensor(config, device_connection)

        devices.append(device)

    async_add_entities(devices)

class LcnVariableSensor(LcnEntity):
    """Representation of a LCN sensor for variables."""

    def __init__(self, config, device_connection):
        """Initialize the LCN sensor."""
        super().__init__(config, device_connection)

        self.variable = pypck.lcn_defs.Var[config[CONF_SOURCE]]
        self.unit = pypck.lcn_defs.VarUnit.parse(config[CONF_UNIT_OF_MEASUREMENT])

        self._value = None

    async def async_added_to_hass(self):
        """Run when entity about to be added to hass."""
        await super().async_added_to_hass()
        if not self.device_connection.is_group:
            await self.device_connection.activate_status_request_handler(self.variable)

    @property
    def state(self):
        """Return the state of the entity."""
        return self._value

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        return self.unit.value

    def input_received(self, input_obj):
        """Set sensor value when LCN input object (command) is received."""
        if (
            not isinstance(input_obj, pypck.inputs.ModStatusVar)
            or input_obj.get_var() != self.variable
        ):
            return

        self._value = input_obj.get_value().to_var_unit(self.unit)
        self.async_write_ha_state()

class LcnLedLogicSensor(LcnEntity):
    """Representation of a LCN sensor for leds and logicops."""

    def __init__(self, config, device_connection):
        """Initialize the LCN sensor."""
        super().__init__(config, device_connection)

        if config[CONF_SOURCE] in LED_PORTS:
            self.source = pypck.lcn_defs.LedPort[config[CONF_SOURCE]]
        else:
            self.source = pypck.lcn_defs.LogicOpPort[config[CONF_SOURCE]]

        self._value = None

    async def async_added_to_hass(self):
        """Run when entity about to be added to hass."""
        await super().async_added_to_hass()
        if not self.device_connection.is_group:
            await self.device_connection.activate_status_request_handler(self.source)

    @property
    def state(self):
        """Return the state of the entity."""
        return self._value

    def input_received(self, input_obj):
        """Set sensor value when LCN input object (command) is received."""
        if not isinstance(input_obj, pypck.inputs.ModStatusLedsAndLogicOps):
            return

        if self.source in pypck.lcn_defs.LedPort:
            self._value = input_obj.get_led_state(self.source.value).name.lower()
        elif self.source in pypck.lcn_defs.LogicOpPort:
            self._value = input_obj.get_logic_op_state(self.source.value).name.lower()

        self.async_write_ha_state()


text:
.spreadsheet table, .spreadsheet tr, .spreadsheet td, .spreadsheet input {
  margin: 0 auto;
  padding: 0;
  border: 0;
}

.spreadsheet table {
    border-collapse: collapse;
}

.spreadsheet td, .spreadsheet input {
    background-color: white;
    color: black;
}

.spreadsheet td {
    border: solid black 1px;
}

.spreadsheet input {
     background-color: transparent;
}

.spreadsheet tr:first-child td, .spreadsheet td:first-child {
    background-color: darkgray;
    padding: 1px 3px;
    font-weight: bold;
    text-align: center;
}

.spreadsheet td:hover {
    background-color: whitesmoke;
}

.spreadsheet input:not(:focus) {
    text-align: right;
}

.spreadsheet td.formula:not(:hover)  {
    background-color: lightgray;
}

.spreadsheet td.error:not(:hover)  {
    background-color: red;
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.webapps;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;

import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.ShortcutHelper;

/**
 * Stores data about an installed web app. Uses SharedPreferences to persist the data to disk.
 * Before this class is used, the web app must be registered in {@link WebappRegistry}.
 *
 * EXAMPLE USAGE:
 *
 * (1) UPDATING/RETRIEVING THE ICON (web app MUST have been registered in WebappRegistry)
 * WebappDataStorage storage = WebappDataStorage.open(context, id);
 * storage.updateSplashScreenImage(bitmap);
 * storage.getSplashScreenImage(callback);
 */
public class WebappDataStorage {

    static final String SHARED_PREFS_FILE_PREFIX = "webapp_";
    static final String KEY_SPLASH_ICON = "splash_icon";
    static final String KEY_LAST_USED = "last_used";
    static final long INVALID_LAST_USED = -1;

    private static Factory sFactory = new Factory();

    private final SharedPreferences mPreferences;

    /**
     * Opens an instance of WebappDataStorage for the web app specified.
     * @param context  The context to open the SharedPreferences.
     * @param webappId The ID of the web app which is being opened.
     */
    public static WebappDataStorage open(final Context context, final String webappId) {
        final WebappDataStorage storage = sFactory.create(context, webappId);
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected final Void doInBackground(Void... nothing) {
                assert storage.getLastUsedTime() != INVALID_LAST_USED;
                storage.updateLastUsedTime();
                return null;
            }
        }.execute();
        return storage;
    }

    /**
     * Asynchronously retrieves the time which this WebappDataStorage was last
     * opened using {@link WebappDataStorage#open(Context, String)}.
     * @param context  The context to read the SharedPreferences file.
     * @param webappId The ID of the web app the used time is being read for.
     * @param callback Called when the last used time has been retrieved.
     */
    public static void getLastUsedTime(final Context context, final String webappId,
            final FetchCallback<Long> callback) {
        new AsyncTask<Void, Void, Long>() {
            @Override
            protected final Long doInBackground(Void... nothing) {
                long lastUsed = new WebappDataStorage(context.getApplicationContext(), webappId)
                        .getLastUsedTime();
                assert lastUsed != INVALID_LAST_USED;
                return lastUsed;
            }

            @Override
            protected final void onPostExecute(Long lastUsed) {
                callback.onDataRetrieved(lastUsed);
            }
        }.execute();
    }

    /**
     * Deletes the data for a web app by clearing all the information inside the SharedPreferences
     * file. This does NOT delete the file itself but the file is left empty.
     * @param context  The context to read the SharedPreferences file.
     * @param webappId The ID of the web app being deleted.
     */
    static void deleteDataForWebapp(final Context context, final String webappId) {
        assert !ThreadUtils.runningOnUiThread();
        openSharedPreferences(context, webappId).edit().clear().commit();
    }

    /**
     * Sets the factory used to generate WebappDataStorage objects.
     */
    @VisibleForTesting
    public static void setFactoryForTests(Factory factory) {
        sFactory = factory;
    }

    private static SharedPreferences openSharedPreferences(Context context, String webappId) {
        return context.getApplicationContext().getSharedPreferences(
                SHARED_PREFS_FILE_PREFIX + webappId, Context.MODE_PRIVATE);
    }

    protected WebappDataStorage(Context context, String webappId) {
        mPreferences = openSharedPreferences(context, webappId);
    }

    /*
     * Asynchronously retrieves the splash screen image associated with the
     * current web app.
     * @param callback Called when the splash screen image has been retrieved.
     *                 May be null if no image was found.
     */
    public void getSplashScreenImage(FetchCallback<Bitmap> callback) {
        new BitmapFetchTask(KEY_SPLASH_ICON, callback).execute();
    }

    /*
     * Update the information associated with the web app with the specified data.
     * @param splashScreenImage The image which should be shown on the splash screen of the web app.
     */
    public void updateSplashScreenImage(Bitmap splashScreenImage) {
        new UpdateTask(splashScreenImage).execute();
    }

    /** Package private for use by WebappRegistry */
    void updateLastUsedTime() {
        assert !ThreadUtils.runningOnUiThread();
        mPreferences.edit().putLong(KEY_LAST_USED, System.currentTimeMillis()).commit();
    }

    private long getLastUsedTime() {
        assert !ThreadUtils.runningOnUiThread();
        return mPreferences.getLong(KEY_LAST_USED, INVALID_LAST_USED);
    }

    /**
     * Called after data has been retrieved from storage.
     */
    public interface FetchCallback<T> {
        public void onDataRetrieved(T readObject);
    }

    /**
     * Factory used to generate WebappDataStorage objects.
     *
     * It is used in tests to override methods in WebappDataStorage and inject the mocked objects.
     */
    public static class Factory {

        /**
         * Generates a WebappDataStorage class for a specified web app.
         */
        public WebappDataStorage create(final Context context, final String webappId) {
            return new WebappDataStorage(context, webappId);
        }
    }

    private final class BitmapFetchTask extends AsyncTask<Void, Void, Bitmap> {

        private final String mKey;
        private final FetchCallback<Bitmap> mCallback;

        public BitmapFetchTask(String key, FetchCallback<Bitmap> callback) {
            mKey = key;
            mCallback = callback;
        }

        @Override
        protected final Bitmap doInBackground(Void... nothing) {
            return ShortcutHelper.decodeBitmapFromString(mPreferences.getString(mKey, null));
        }

        @Override
        protected final void onPostExecute(Bitmap result) {
            mCallback.onDataRetrieved(result);
        }
    }

    private final class UpdateTask extends AsyncTask<Void, Void, Void> {

        private final Bitmap mSplashImage;

        public UpdateTask(Bitmap splashImage) {
            mSplashImage = splashImage;
        }

        @Override
        protected Void doInBackground(Void... nothing) {
            mPreferences.edit()
                    .putString(KEY_SPLASH_ICON, ShortcutHelper.encodeBitmapAsString(mSplashImage))
                    .commit();
            return null;
        }
    }
}


text:
import { TranslateService } from '@ngx-translate/core';
import { GridOption as UniversalGridOption } from '@slickgrid-universal/common';

import { RowDetailView } from './index';

export interface GridOption extends UniversalGridOption {
  /** ngx-translate i18n translation service instance */
  i18n?: TranslateService;

  /** Row Detail View Plugin options & events (columnId, cssClass, toolTip, width) */
  rowDetailView?: RowDetailView;
}


text:
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour
{

	// Count
	public int currentScore;
	public int highscore;
	public int tokenCount;
	private int totalTokenCount;
	public int currentLevel = 0;
	public int unlockedLevel;

	// Timer variables
	public Rect timerRect;
	public Color warningColorTimer;
	public Color defaultColorTimer;
	public float startTime;
	private string currentTime;

	// GUI SKIN
	public GUISkin skin;

	// References
	public GameObject tokenParent;

	private bool completed = false;
	private bool showWinScreen = false;
	public int winScreenWidth, winScreenHeight;

	void Update()
	{
		if (!completed)
		{
			startTime -= Time.deltaTime;
			currentTime = string.Format("{0:0.0}", startTime);
			if (startTime <= 0)
			{
				startTime = 0;
				Application.LoadLevel("MainMenu");
			}
		}
	}

	void Start()
	{
		totalTokenCount = tokenParent.transform.childCount;

		if (PlayerPrefs.GetInt("Level Completed") > 0)
		{
			currentLevel = PlayerPrefs.GetInt("Level Completed");
		}
		else
		{
			currentLevel = 0;
		}

	}

	public void CompleteLevel()
	{
		showWinScreen = true;
		completed = true;
	}

	void LoadNextLevel()
	{
		Time.timeScale = 1f;
		if (currentLevel < 3)
		{
			currentLevel += 1;
			print (currentLevel);
			SaveGame();
			Application.LoadLevel(currentLevel);
		}
		else
		{
			print ("You win!");
		}
	}

	void SaveGame()
	{
		PlayerPrefs.SetInt("Level Completed", currentLevel);
		PlayerPrefs.SetInt("Level " + currentLevel.ToString() + " score", currentScore);
	}

	void OnGUI()
	{
		GUI.skin = skin;
		if (startTime < 5f)
		{
			skin.GetStyle("Timer").normal.textColor = warningColorTimer;
		} else {
			skin.GetStyle("Timer").normal.textColor = defaultColorTimer;
		}
		GUI.Label (timerRect, currentTime, skin.GetStyle ("Timer"));
		GUI.Label (new Rect(45,100,200,200), tokenCount.ToString() + "/" + totalTokenCount.ToString());

		if (showWinScreen)
		{
			Rect winScreenRect = new Rect(Screen.width/2 - (Screen.width *.5f/2), Screen.height/2 - (Screen.height *.5f/2), Screen.width *.5f, Screen.height *.5f);
			GUI.Box(winScreenRect, "Yeah");

			int gameTime = (int)startTime;
			currentScore = tokenCount * gameTime;
			if (GUI.Button(new Rect(winScreenRect.x + winScreenRect.width - 170, winScreenRect.y + winScreenRect.height - 60, 150, 40), "Continue"))
			{
				LoadNextLevel();
			}
			if (GUI.Button(new Rect(winScreenRect.x + 20, winScreenRect.y + winScreenRect.height - 60, 100, 40), "Quit"))
			{
				Application.LoadLevel("MainMenu");
				Time.timeScale = 1f;
			}

			//GUI.Label(new Rect(winScreenRect.x + 20, winScreenRect.y + 40, 300, 50), currentScore.ToString() + " Score");
			//GUI.Label(new Rect(winScreenRect.x + 20, winScreenRect.y + 70, 300, 50), "Completed Level " + currentLevel);

		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.juan.test.spring.oauth2</groupId>
	<artifactId>sample-authorization-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>sample-authorization-server</name>
	<description>Demo project for Spring Security OAuth 2</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<start-class>com.juan.test.spring.oauth2.SampleAuthorizationServerApplication</start-class>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-oauth2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb-j5</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-parent</artifactId>
				<version>1.0.1.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
import {PageMetadata} from "./pageMetadata";
import {TodoItem} from "./todoItem";
import {LinkItem} from "./linkItem";
import {AccessedItem} from "./accessedItem";
/**
 * TodoResource - defines a TodoResource
 * Created by bnjm on 2/4/17.
 */
export interface TodoResource {
  todoResources: TodoItem[];
  _links: LinkItem;
  accessed: AccessedItem;
  page: PageMetadata;
}


text:
function popWin(url) {
  var win = window.open(url, 'win',
              'location=yes,directories=yes,menubar=yes,toolbar=yes,status=yes,scrollbars=yes,resizable=yes,width=800,height=600');
  win.focus();
}

function openTab(type, device) {
  var url = rootURL;
  switch (type) {
    case 0: url = rootURL; break;
    case 1:
      if (device.indexOf('XC2') != -1) url += prodURL + xbrURL;
      else if (device.indexOf('XA2') != -1) url += prodURL + acr2URL;
      else if (device.indexOf('XCR3') != -1) url += prodURL + xpla3URL;
      else if (device.indexOf('XV') != -1) url += prodURL + xc9500xvURL;
      else if (device.indexOf('XL') != -1) url += prodURL + xc9500xlURL;
      else if (device.indexOf('XA') != -1) url += prodURL + xa9500xlURL;
      else url += prodURL + xc9500URL;
      break;
    case 2: url += marketURL; break;
    case 3: url = supportURL; break;
    case 4: url += educationURL; break;
    case 5: url = buyURL; break;
    case 6: url += contactURL; break;
    case 7: url += searchURL; break;
    default: url = rootURL;
  }

  popWin(url);
}


text:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Constraints\NotBlank;

class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
          // Obligatoire; longueur max : 200 chars;
            ->add('author', TextType::class, [
                'required' => false,
                'label' => 'Nom'
            ])
            // Obligatoire
            ->add('content', TextareaType::class, [
                'required' => false,
                'label' => 'Votre commentaire',
                'attr' => ['class' => 'materialize-textarea']
            ])
            ->add('submit', SubmitType::class)
        ;
    }
}


text:
namespace base {
class FilePath;
}

namespace storage {

class FileSystemContext;

// Generic FileStreamReader implementation for FileSystem files.
// Note: This generic implementation would work for any filesystems but
// remote filesystem should implement its own reader rather than relying
// on FileSystemOperation::GetSnapshotFile() which may force downloading
// the entire contents for remote files.
class COMPONENT_EXPORT(STORAGE_BROWSER) FileSystemFileStreamReader
    : public FileStreamReader {
 public:
  ~FileSystemFileStreamReader() override;

  // FileStreamReader overrides.
  int Read(net::IOBuffer* buf,
           int buf_len,
           net::CompletionOnceCallback callback) override;
  int64_t GetLength(net::Int64CompletionOnceCallback callback) override;

 private:
  friend class FileStreamReader;
  friend class FileSystemFileStreamReaderTest;

  FileSystemFileStreamReader(FileSystemContext* file_system_context,
                             const FileSystemURL& url,
                             int64_t initial_offset,
                             const base::Time& expected_modification_time);

  int CreateSnapshot();
  void DidCreateSnapshot(base::File::Error file_error,
                         const base::File::Info& file_info,
                         const base::FilePath& platform_path,
                         scoped_refptr<ShareableFileReference> file_ref);
  void OnRead(int rv);
  void OnGetLength(int64_t rv);

  net::IOBuffer* read_buf_;
  int read_buf_len_;
  net::CompletionOnceCallback read_callback_;
  net::Int64CompletionOnceCallback get_length_callback_;
  scoped_refptr<FileSystemContext> file_system_context_;
  FileSystemURL url_;
  const int64_t initial_offset_;
  const base::Time expected_modification_time_;
  std::unique_ptr<FileStreamReader> file_reader_;
  scoped_refptr<ShareableFileReference> snapshot_ref_;
  bool has_pending_create_snapshot_;
  base::WeakPtrFactory<FileSystemFileStreamReader> weak_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(FileSystemFileStreamReader);
};

}  // namespace storage

#endif  // STORAGE_BROWSER_FILE_SYSTEM_FILE_SYSTEM_FILE_STREAM_READER_H_


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>BDRN4</station_id>
	<observation_time>Last Updated on Jan 4 2016, 10:30 pm AST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 22:30:00 -0400</observation_time_rfc822>
	<temperature_string>15.8 F (-9.0 C)</temperature_string>
	<temp_f>15.8</temp_f>
	<temp_c>-9.0</temp_c>
	<water_temp_f>40.3</water_temp_f>
	<water_temp_c>4.6</water_temp_c>
	<wind_string>North at 6.9 MPH (6.03 KT)</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>360</wind_degrees>
	<wind_mph>6.9</wind_mph>
	<wind_gust_mph>0.0</wind_gust_mph>
	<wind_kt>6.03</wind_kt>
	<pressure_string>1027.5 mb</pressure_string>
	<pressure_mb>1027.5</pressure_mb>
	<windchill_string>6 F (-14 C)</windchill_string>
      	<windchill_f>6</windchill_f>
      	<windchill_c>-14</windchill_c>
	<mean_wave_dir>Northeast</mean_wave_dir>
	<mean_wave_degrees></mean_wave_degrees>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
import { RouteLocationNormalized } from 'vue-router';
import { Game } from '../../../../_common/game/game.model';

export class GameListingContainer {
	constructor({
		loadInfinitely = true,
	}: {
		loadInfinitely?: boolean;
	} = {}) {
		this.loadInfinitely = loadInfinitely;
	}

	/**
	 * Whether or not this listing container should load games in infinitely as
	 * you scroll.
	 */
	readonly loadInfinitely: boolean;

	isBootstrapped = false;
	games: Game[] = [];
	gameIds = new Set<number>();
	gamesCount = 0;
	perPage = 10;
	currentPage = 1;
	section = 'featured';
	isLoadingMore = false;
	reachedEnd = false;

	processPayload(route: RouteLocationNormalized, payload: any) {
		this.isBootstrapped = true;
		this.gamesCount = payload.gamesCount;
		this.perPage = payload.perPage;

		this.resetGames();
		this.addGames(Game.populate(payload.games));

		this.currentPage = route.query.page ? parseInt(route.query.page + '', 10) : 1;
		this.section = (route.params.section as string) ?? 'featured';
	}

	processPagePayload(page: number, payload: any) {
		if (!this.loadInfinitely) {
			this.resetGames();
		}

		const addedGames = this.addGames(Game.populate(payload.games));

		if (!addedGames.length) {
			this.reachedEnd = true;
			return;
		}

		this.gamesCount = payload.gamesCount;
		this.currentPage = page;
	}

	private resetGames() {
		this.games = [];
		this.gameIds = new Set();
	}

	private addGames(newGames: Game[]) {
		const addedGames: Game[] = [];

		for (const game of newGames) {
			// Only add each game once, in case of dupes.
			if (this.gameIds.has(game.id)) {
				continue;
			}

			this.gameIds.add(game.id);
			this.games.push(game);
			addedGames.push(game);
		}

		return addedGames;
	}
}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="font_size_hint">16sp</dimen>
    <dimen name="font_size">13sp</dimen>
    <dimen name="edit_text_height">40dp</dimen>
    <dimen name="text_input_layout">70dp</dimen>
    <dimen name="edit_text_gap">7dp</dimen>
    <dimen name="button_gap">27dp</dimen>
    <dimen name="textview_login_gap">47dp</dimen>
    <dimen name="textview_signup_gap">17dp</dimen>

</resources>


text:
using GuiLabs.Utils.Commands;

namespace GuiLabs.Editor.UI.Commands
{
	public class BlockCommand : Command
	{
		public BlockCommand(string text)
			: base(text)
		{

		}
	}
}


text:
package com.asha.vrlib.strategy.display;

import com.asha.vrlib.SharkLibrary;
import com.asha.vrlib.common.SharkGLHandler;
import com.asha.vrlib.model.BarrelDistortionConfig;
import com.asha.vrlib.strategy.ModeManager;

/**
 * Created by hzqiujiadi on 16/3/19.
 * hzqiujiadi ashqalcn@gmail.com
 */
public class DisplayModeManager extends ModeManager<AbsDisplayStrategy> implements IDisplayMode {

    public static int[] sModes = {SharkLibrary.DISPLAY_MODE_NORMAL, SharkLibrary.DISPLAY_MODE_GLASS};

    private boolean antiDistortionEnabled;
    private BarrelDistortionConfig barrelDistortionConfig;

    public DisplayModeManager(int mode, SharkGLHandler handler) {
        super(mode, handler);
    }

    @Override
    protected int[] getModes() {
        return sModes;
    }

    @Override
    protected AbsDisplayStrategy createStrategy(int mode) {
        switch (mode){
            case SharkLibrary.DISPLAY_MODE_GLASS:
                return new GlassStrategy();
            case SharkLibrary.DISPLAY_MODE_NORMAL:
            default:
                return new NormalStrategy();
        }
    }

    @Override
    public int getVisibleSize() {
        return getStrategy().getVisibleSize();
    }

    public void setAntiDistortionEnabled(boolean antiDistortionEnabled) {
        this.antiDistortionEnabled = antiDistortionEnabled;
    }

    public boolean isAntiDistortionEnabled() {
        return antiDistortionEnabled;
    }

    public void setBarrelDistortionConfig(BarrelDistortionConfig barrelDistortionConfig) {
        this.barrelDistortionConfig = barrelDistortionConfig;
    }

    public BarrelDistortionConfig getBarrelDistortionConfig() {
        return barrelDistortionConfig;
    }
}


text:
@implementation NUILoader (StructuresLoading)

- (BOOL)loadCGSizePropertyOfObject:(id)object setter:(SEL)setter value:(NUIStatement *)value
    error:(NUIError **)error
{
    if (value.statementType != NUIStatementType_Array) {
        *error = [NUIError errorWithStatement:value message:@"Expecting an array."];
        return NO;
    }
    NSArray *array = [self calculateArrayOfNumericExpressions:value containingObject:object];
    if (!array) {
        *error = self.lastError;
        return NO;
    }
    if (array.count != 2) {
        *error = [NUIError errorWithStatement:value message:@"Expecting 2 numbers."];
        return NO;
    }
    CGSize sz = CGSizeMake([[array objectAtIndex:0] floatValue],
        [[array objectAtIndex:1] floatValue]);
    objc_msgSend(object, setter, sz);
    return YES;
}

- (BOOL)loadCGRectPropertyOfObject:(id)object setter:(SEL)setter value:(NUIStatement *)value
    error:(NUIError **)error
{
    if (value.statementType != NUIStatementType_Array) {
        *error = [NUIError errorWithStatement:value message:@"Expecting an array."];
        return NO;
    }
    NSArray *array = [self calculateArrayOfNumericExpressions:value containingObject:object];
    if (!array) {
        *error = self.lastError;
        return NO;
    }
    if (array.count != 4) {
        *error = [NUIError errorWithStatement:value message:@"Expecting 4 numbers."];
        return NO;
    }
    CGRect rc = CGRectMake([[array objectAtIndex:0] floatValue],
        [[array objectAtIndex:1] floatValue], [[array objectAtIndex:2] floatValue],
        [[array objectAtIndex:3] floatValue]);
    objc_msgSend(object, setter, rc);
    return YES;
}

- (BOOL)loadNSRangePropertyOfObject:(id)object setter:(SEL)setter value:(NUIStatement *)value
    error:(NUIError **)error
{
    if (value.statementType != NUIStatementType_Array) {
        *error = [NUIError errorWithStatement:value message:@"Expecting an array."];
        return NO;
    }
    NSArray *array = [self calculateArrayOfNumericExpressions:value containingObject:object];
    if (!array) {
        *error = self.lastError;
        return NO;
    }
    if (array.count != 2) {
        *error = [NUIError errorWithStatement:value message:@"Expecting 2 numbers."];
        return NO;
    }
    NSRange range = (NSRange){ [[array objectAtIndex:0] floatValue],
        [[array objectAtIndex:1] floatValue] };
    objc_msgSend(object, setter, range);
    return YES;
}

- (BOOL)load_NSRangePropertyOfObject:(id)object setter:(SEL)setter value:(NUIStatement *)value
    error:(NUIError **)error
{
    return [self loadNSRangePropertyOfObject:object setter:setter value:value error:error];
}

- (BOOL)loadUIEdgeInsetsPropertyOfObject:(id)object setter:(SEL)setter value:(NUIStatement *)value
    error:(NUIError **)error
{
    if (value.statementType != NUIStatementType_Array) {
        *error = [NUIError errorWithStatement:value message:@"Expecting an array."];
        return NO;
    }
    NSArray *array = [self calculateArrayOfNumericExpressions:value containingObject:object];
    if (!array) {
        *error = self.lastError;
        return NO;
    }
    if (array.count != 4) {
        *error = [NUIError errorWithStatement:value message:@"Expecting 4 numbers."];
        return NO;
    }
    UIEdgeInsets insets = UIEdgeInsetsMake([[array objectAtIndex:0] floatValue],
        [[array objectAtIndex:1] floatValue], [[array objectAtIndex:2] floatValue],
        [[array objectAtIndex:3] floatValue]);
    objc_msgSend(object, setter, insets);
    return YES;
}

- (BOOL)loadCGAffineTransformPropertyOfObject:(id)object setter:(SEL)setter
    value:(NUIStatement *)value error:(NUIError **)error
{
    if (value.statementType != NUIStatementType_Array) {
        *error = [NUIError errorWithStatement:value message:@"Expecting an array."];
        return NO;
    }
    NSArray *array = [self calculateArrayOfNumericExpressions:value containingObject:object];
    if (!array) {
        *error = self.lastError;
        return NO;
    }
    if (array.count != 6) {
        *error = [NUIError errorWithStatement:value message:@"Expecting 6 numbers."];
        return NO;
    }
    CGAffineTransform transform =
        CGAffineTransformMake([[array objectAtIndex:0] floatValue],
        [[array objectAtIndex:1] floatValue],
        [[array objectAtIndex:2] floatValue],
        [[array objectAtIndex:3] floatValue],
        [[array objectAtIndex:4] floatValue],
        [[array objectAtIndex:5] floatValue]);
    objc_msgSend(object, setter, transform);
    return YES;
}

@end


text:
#include "core/cross/precompile.h"
#include "core/cross/semantic_manager.h"
#include "core/cross/standard_param.h"

namespace o3d {

const InterfaceId SemanticManager::kInterfaceId =
    InterfaceTraits<SemanticManager>::kInterfaceId;

SemanticManager::SemanticManager(ServiceLocator* service_locator)
    : service_(service_locator, this) {
  // Create an object to hold one of each type of sas param.
  sas_param_object_ = ParamObject::Ref(new ParamObject(service_locator));
  sas_param_object_->set_name(O3D_STRING_CONSTANT("sasParamObject"));

  // Initializes the static map between SAS parameter names and the
  // corresponding StandardParamMatrix4 type and adds one of each SAS
  // param type of the sas_param_object_ by class name.
#undef O3D_STANDARD_ANNOTATION_ENTRY
#define O3D_STANDARD_ANNOTATION_ENTRY(enum_name, class_name)              \
  sas_map_[#class_name] = class_name ## ParamMatrix4::GetApparentClass(); \
  sas_param_object_->CreateParamByClass(                                  \
      class_name ## ParamMatrix4::GetApparentClass()->name(),             \
      class_name ## ParamMatrix4::GetApparentClass());

  // Create the standard annotations (this uses the above ENTRY macro).
  O3D_STANDARD_ANNOTATIONS;
}

SemanticManager::~SemanticManager() {
  sas_param_object_.Reset();
}

// Looks up an SAS transform semantic by name, and returns the Semantic enum.
const ObjectBase::Class* SemanticManager::LookupSemantic(
    const String& semantic) const {
  SasMap::const_iterator iter = sas_map_.find(semantic);
  return (iter != sas_map_.end()) ? iter->second : NULL;
}
}  // namespace o3d


text:
package org.opencloudb.route.function;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;

import org.opencloudb.config.model.rule.RuleAlgorithm;

/**
 * auto partition by Long
 *
 * @author hexiaobin
 */
public class PartitionByPattern implements RuleAlgorithm {
	private static final int PARTITION_LENGTH = 1024;
	private int patternValue = PARTITION_LENGTH;// 分区长度,取模数值
	private String mapFile;
	private LongRange[] longRongs;

	@Override
	public void init() {

		initialize();
	}

	public void setMapFile(String mapFile) {
		this.mapFile = mapFile;
	}

	public void setPatternValue(int patternValue) {
		this.patternValue = patternValue;
	}

	@Override
	public Integer calculate(String columnValue) {
		long value = Long.valueOf(columnValue);
		Integer rst = null;
		for (LongRange longRang : this.longRongs) {
			long hash = value % patternValue;
			if (hash <= longRang.valueEnd && hash >= longRang.valueStart) {
				return longRang.nodeIndx;
			}
		}
		return rst;
	}

	private void initialize() {
		BufferedReader in = null;
		try {
			// FileInputStream fin = new FileInputStream(new File(fileMapPath));
			InputStream fin = this.getClass().getClassLoader()
					.getResourceAsStream(mapFile);
			if (fin == null) {
				throw new RuntimeException("can't find class resource file "
						+ mapFile);
			}
			in = new BufferedReader(new InputStreamReader(fin));
			LinkedList<LongRange> longRangeList = new LinkedList<LongRange>();

			for (String line = null; (line = in.readLine()) != null;) {
				line = line.trim();
				if (line.startsWith("#") || line.startsWith("//"))
					continue;
				int ind = line.indexOf('=');
				if (ind < 0) {
					System.out.println(" warn: bad line int " + mapFile + " :"
							+ line);
					continue;
				}
				try {
					String pairs[] = line.substring(0, ind).trim().split("-");
					long longStart = Long.parseLong(pairs[0].trim());
					long longEnd = Long.parseLong(pairs[1].trim());
					int nodeId = Integer.parseInt(line.substring(ind + 1)
							.trim());
					longRangeList
							.add(new LongRange(nodeId, longStart, longEnd));

				} catch (Exception e) {
				}
			}
			longRongs = longRangeList.toArray(new LongRange[longRangeList
					.size()]);
		} catch (Exception e) {
			if (e instanceof RuntimeException) {
				throw (RuntimeException) e;
			} else {
				throw new RuntimeException(e);
			}

		} finally {
			try {
				in.close();
			} catch (Exception e2) {
			}
		}
	}

	static class LongRange {
		public final int nodeIndx;
		public final long valueStart;
		public final long valueEnd;

		public LongRange(int nodeIndx, long valueStart, long valueEnd) {
			super();
			this.nodeIndx = nodeIndx;
			this.valueStart = valueStart;
			this.valueEnd = valueEnd;
		}

	}
}


text:
> Simple production-ready text editor using [React](http://facebook.github.io/react/) and tests with Jest.

## Install

Clone repository and run:

```sh
$ npm install
```

## Development

node 4+

```sh
$ npm start
```

Go to [http://localhost:3001](http://localhost:3001) and see the magic happen.

## Production

If you want to run the project in production, set the `NODE_ENV` environment variable to `production`.

```sh
$ NODE_ENV=production npm start
```

Also build the production bundle:

```sh
$ npm run dist
```

## Tests

```sh
$ npm test
```

Only run specific tests

```sh
$ npm test -- NotFoundComponent
```

Coverage

```sh
$ npm test -- --coverage
```


text:
package net.erikkarlsson.smashapp.base;

import android.support.annotation.NonNull;

import net.erikkarlsson.smashapp.base.injector.component.ApplicationComponent;
import net.erikkarlsson.smashapp.base.injector.component.DaggerApplicationComponent;
import net.erikkarlsson.smashapp.base.injector.module.BaseApplicationModule;
import net.erikkarlsson.smashapp.base.injector.module.NetModule;
import net.erikkarlsson.smashapp.feature.tournament.presentation.TournamentService;

import java.io.File;

import timber.log.Timber;

/**
 * Creates ApplicationComponent and injects itself.
 * Does app initialization and starts background service.
 *
 * In addition TestableApplication contains some helper methods
 * for controlling the app during Espresso testing.
 */

public class SmashApplication extends BaseApplication implements TestableApplication {

    @NonNull
    public ApplicationComponent getApplicationComponent() {
        return applicationComponent;
    }

    @Override public void bypassLogin(@NonNull String name) {
        applicationComponent.userSession().login(name);
    }

    @Override public void logOutBetweenTests() {
        applicationComponent.userSession().logOut();
        clearCache(applicationComponent.cacheDir());
    }

    @Override
    public void reInitDependencyInjection(@NonNull String baseUrl) {
        applicationComponent = DaggerApplicationComponent.builder()
                                                         .baseApplicationModule(new BaseApplicationModule(this))
                                                         .netModule(new NetModule(baseUrl, baseUrl))
                                                         .build();

        stopService(TournamentService.getServiceIntent(this)); // Stop service so that it will get re-injected when started.
        applicationComponent.inject(this);
        smashApplicationController.doAppInit();
    }

    private void clearCache(@NonNull final File cacheDir) {
        File[] files = cacheDir.listFiles();

        if (files == null) {
            return;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                continue;
            }

            boolean deleted = file.delete();

            if (!deleted) {
                Timber.e("Failed to delete cache file: %s", file.toString());
            }
        }
    }
}