text:
package com.liulishuo.filedownloader;

import com.liulishuo.filedownloader.message.MessageSnapshot;
import com.liulishuo.filedownloader.message.MessageSnapshotTaker;
import com.liulishuo.filedownloader.model.FileDownloadHeader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadHelper;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;

/**
 * The download task hunter.
 */

public class DownloadTaskHunter implements ITaskHunter, ITaskHunter.IStarter, ITaskHunter.IMessageHandler,
        BaseDownloadTask.LifeCycleCallback {

    private IFileDownloadMessenger mMessenger;
    private final Object mPauseLock;

    @Override
    public boolean updateKeepAhead(MessageSnapshot snapshot) {
        if (!FileDownloadStatus.isKeepAhead(getStatus(), snapshot.getStatus())) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(this, "can't update mStatus change by keep ahead, %d, but the" +
                        " current mStatus is %d, %d", mStatus, getStatus(), getId());
            }
            return false;
        }

        update(snapshot);
        return true;
    }

    @Override
    public boolean updateKeepFlow(MessageSnapshot snapshot) {
        final int currentStatus = getStatus();
        final int nextStatus = snapshot.getStatus();

        if (FileDownloadStatus.paused == currentStatus && FileDownloadStatus.isIng(nextStatus)) {
            if (FileDownloadLog.NEED_LOG) {
                /**
                 * Occur such situation, must be the running-mStatus waiting for turning up in flow
                 * thread pool(or binder thread) when there is someone invoked the {@link #pause()} .
                 *
                 * High concurrent cause.
                 */
                FileDownloadLog.d(this, "High concurrent cause, callback pending, but has already" +
                        " be paused %d", getId());
            }
            return true;
        }

        if (!FileDownloadStatus.isKeepFlow(currentStatus, nextStatus)) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(this, "can't update mStatus change by keep flow, %d, but the" +
                        " current mStatus is %d, %d", mStatus, getStatus(), getId());
            }

            return false;
        }

        update(snapshot);
        return true;
    }

    @Override
    public boolean updateMoreLikelyCompleted(MessageSnapshot snapshot) {
        if (!FileDownloadStatus.isMoreLikelyCompleted(mTask.getRunningTask().getOrigin())) {
            return false;
        }

        update(snapshot);
        return true;
    }

    @Override
    public boolean updateSameFilePathTaskRunning(MessageSnapshot snapshot) {
        if (!mTask.getRunningTask().getOrigin().isPathAsDirectory()) {
            return false;
        }

        if (snapshot.getStatus() != FileDownloadStatus.warn ||
                getStatus() != FileDownloadStatus.connected) {
            return false;
        }

        update(snapshot);
        return true;
    }

    @Override
    public IFileDownloadMessenger getMessenger() {
        return mMessenger;
    }

    @Override
    public MessageSnapshot prepareErrorMessage(Throwable cause) {
        mStatus = FileDownloadStatus.error;
        mThrowable = cause;
        return MessageSnapshotTaker.catchException(getId(), getSofarBytes(), cause);
    }

    private void update(final MessageSnapshot snapshot) {
        final BaseDownloadTask task = mTask.getRunningTask().getOrigin();
        final byte status = snapshot.getStatus();

        this.mStatus = status;
        this.mIsLargeFile = snapshot.isLargeFile();

        switch (status) {
            case FileDownloadStatus.pending:
                this.mSoFarBytes = snapshot.getLargeSofarBytes();
                this.mTotalBytes = snapshot.getLargeTotalBytes();

                // notify
                mMessenger.notifyPending(snapshot);
                break;
            case FileDownloadStatus.started:
                // notify
                mMessenger.notifyStarted(snapshot);
                break;
            case FileDownloadStatus.connected:
                this.mTotalBytes = snapshot.getLargeTotalBytes();
                this.mIsResuming = snapshot.isResuming();
                this.mEtag = snapshot.getEtag();

                final String filename = snapshot.getFileName();
                if (filename != null) {
                    if (task.getFilename() != null) {
                        FileDownloadLog.w(this, "already has mFilename[%s], but assign mFilename[%s] again",
                                task.getFilename(), filename);
                    }
                    mTask.setFileName(filename);
                }

                mSpeedMonitor.start(mSoFarBytes);

                // notify
                mMessenger.notifyConnected(snapshot);
                break;
            case FileDownloadStatus.progress:
                this.mSoFarBytes = snapshot.getLargeSofarBytes();
                mSpeedMonitor.update(snapshot.getLargeSofarBytes());

                // notify
                mMessenger.notifyProgress(snapshot);
                break;
//            case FileDownloadStatus.blockComplete:
            /**
             * Handled by {@link FileDownloadList#removeByCompleted(BaseDownloadTask)}
             */
//                break;
            case FileDownloadStatus.retry:
                this.mSoFarBytes = snapshot.getLargeSofarBytes();
                this.mThrowable = snapshot.getThrowable();
                mRetryingTimes = snapshot.getRetryingTimes();

                mSpeedMonitor.reset();

                // notify
                mMessenger.notifyRetry(snapshot);
                break;
            case FileDownloadStatus.error:
                this.mThrowable = snapshot.getThrowable();
                this.mSoFarBytes = snapshot.getLargeSofarBytes();

                // to FileDownloadList
                FileDownloadList.getImpl().remove(mTask.getRunningTask(), snapshot);

                break;
            case FileDownloadStatus.paused:
                /**
                 * Handled by {@link #pause()}
                 */
                break;
            case FileDownloadStatus.completed:
                this.mIsReusedOldFile = snapshot.isReusedDownloadedFile();
                // only carry total data back
                this.mSoFarBytes = snapshot.getLargeTotalBytes();
                this.mTotalBytes = snapshot.getLargeTotalBytes();

                // to FileDownloadList
                FileDownloadList.getImpl().remove(mTask.getRunningTask(), snapshot);

                break;
            case FileDownloadStatus.warn:
                mSpeedMonitor.reset();

                final int sameIdTaskCount = FileDownloadList.getImpl().count(task.getId());

                final int sameStoreTaskCount;
                // generate same task id.
                if (sameIdTaskCount <= 1 && task.isPathAsDirectory()) {
                    sameStoreTaskCount = FileDownloadList.getImpl().count(FileDownloadUtils.
                            generateId(task.getUrl(), task.getTargetFilePath()));
                } else {
                    sameStoreTaskCount = 0;
                }

                if (sameIdTaskCount + sameStoreTaskCount <= 1) {
                    // 1. this progress kill by sys and relive,
                    // for add at least one mListener
                    // or 2. pre downloading task has already completed/error/paused
                    // request mStatus
                    final int currentStatus = FileDownloadServiceProxy.getImpl().
                            getStatus(task.getId());
                    FileDownloadLog.w(this, "warn, but no mListener to receive, " +
                            "switch to pending %d %d", task.getId(), currentStatus);

                    //noinspection StatementWithEmptyBody
                    if (FileDownloadStatus.isIng(currentStatus)) {
                        // ing, has callbacks
                        // keep and wait callback

                        this.mStatus = FileDownloadStatus.pending;
                        this.mTotalBytes = snapshot.getLargeTotalBytes();
                        this.mSoFarBytes = snapshot.getLargeSofarBytes();

                        mSpeedMonitor.start(mSoFarBytes);

                        mMessenger.
                                notifyPending(((MessageSnapshot.IWarnMessageSnapshot) snapshot).
                                        turnToPending());
                        break;
                    } else {
                        // already over and no callback
                    }

                }

                // to FileDownloadList
                FileDownloadList.getImpl().remove(mTask.getRunningTask(), snapshot);
                break;
        }
    }

    @Override
    public void onBegin() {
        if (FileDownloadMonitor.isValid()) {
            FileDownloadMonitor.getMonitor().onTaskBegin(mTask.getRunningTask().getOrigin());
        }

        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.v(this, "filedownloader:lifecycle:start %s by %d ", toString(), getStatus());
        }
    }

    @Override
    public void onIng() {
        if (FileDownloadMonitor.isValid() && getStatus() == FileDownloadStatus.started) {
            FileDownloadMonitor.getMonitor().onTaskStarted(mTask.getRunningTask().getOrigin());
        }
    }

    @Override
    public void onOver() {
        final BaseDownloadTask origin = mTask.getRunningTask().getOrigin();

        if (FileDownloadMonitor.isValid()) {
            FileDownloadMonitor.getMonitor().onTaskOver(origin);
        }

        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.v(this, "filedownloader:lifecycle:over %s by %d ", toString(),
                    getStatus());
        }

        mSpeedMonitor.end(this.mSoFarBytes);
        if (mTask.getFinishListenerList() != null) {
            @SuppressWarnings("unchecked") final ArrayList<BaseDownloadTask.FinishListener>
                    listenersCopy =
                    (ArrayList<BaseDownloadTask.FinishListener>) mTask.getFinishListenerList().clone();
            final int numListeners = listenersCopy.size();
            for (int i = 0; i < numListeners; ++i) {
                listenersCopy.get(i).over(origin);
            }
        }

        FileDownloader.getImpl().getLostConnectedHandler().taskWorkFine(mTask.getRunningTask());
    }

    interface ICaptureTask {
        FileDownloadHeader getHeader();

        BaseDownloadTask.IRunningTask getRunningTask();

        void setFileName(String fileName);

        ArrayList<BaseDownloadTask.FinishListener> getFinishListenerList();
    }

    private final ICaptureTask mTask;
    private volatile byte mStatus = FileDownloadStatus.INVALID_STATUS;
    private Throwable mThrowable = null;

    private final IDownloadSpeed.Monitor mSpeedMonitor;
    private final IDownloadSpeed.Lookup mSpeedLookup;

    private long mSoFarBytes;
    private long mTotalBytes;

    private int mRetryingTimes;

    private boolean mIsLargeFile;

    private boolean mIsResuming;
    private String mEtag;

    private boolean mIsReusedOldFile = false;

    DownloadTaskHunter(ICaptureTask task, Object pauseLock) {
        mPauseLock = pauseLock;
        mTask = task;
        final DownloadSpeedMonitor monitor = new DownloadSpeedMonitor();
        mSpeedMonitor = monitor;
        mSpeedLookup = monitor;
        mMessenger = new FileDownloadMessenger(task.getRunningTask(), this);
    }

    @Override
    public void intoLaunchPool() {
        synchronized (mPauseLock) {
            if (mStatus != FileDownloadStatus.INVALID_STATUS) {
                FileDownloadLog.w(this, "High concurrent cause, this task %d will not input " +
                                "to launch pool, because of the status isn't idle : %d",
                        getId(), mStatus);
                return;
            }

            mStatus = FileDownloadStatus.toLaunchPool;
        }

        final BaseDownloadTask.IRunningTask runningTask = mTask.getRunningTask();
        final BaseDownloadTask origin = runningTask.getOrigin();

        if (FileDownloadMonitor.isValid()) {
            FileDownloadMonitor.getMonitor().onRequestStart(origin);
        }

        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.v(this, "call start " +
                            "Url[%s], Path[%s] Listener[%s], Tag[%s]",
                    origin.getUrl(), origin.getPath(), origin.getListener(), origin.getTag());
        }

        boolean ready = true;

        try {
            prepare();
        } catch (Throwable e) {
            ready = false;

            FileDownloadList.getImpl().add(runningTask);
            FileDownloadList.getImpl().remove(runningTask, prepareErrorMessage(e));
        }

        if (ready) {
            FileDownloadTaskLauncher.getImpl().launch(this);
        }

        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.v(this, "the task[%d] has been into the launch pool.", getId());
        }
    }

    @Override
    public boolean pause() {
        if (FileDownloadStatus.isOver(getStatus())) {
            if (FileDownloadLog.NEED_LOG) {
                /**
                 * The over-mStatus call-backed and set the over-mStatus to this task between here
                 * area and remove from the {@link FileDownloadList}.
                 *
                 * High concurrent cause.
                 */
                FileDownloadLog.d(this, "High concurrent cause, Already is over, can't pause " +
                        "again, %d %d", getStatus(), mTask.getRunningTask().getOrigin().getId());
            }
            return false;
        }
        this.mStatus = FileDownloadStatus.paused;

        final BaseDownloadTask.IRunningTask runningTask = mTask.getRunningTask();
        final BaseDownloadTask origin = runningTask.getOrigin();

        FileDownloadTaskLauncher.getImpl().expire(this);
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.v(this, "the task[%d] has been expired from the launch pool.", getId());
        }

        if (!FileDownloader.getImpl().isServiceConnected()) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(this, "request pause the task[%d] to the download service, but" +
                        " the download service isn't connected yet.", origin.getId());
            }
        } else {
            FileDownloadServiceProxy.getImpl().pause(origin.getId());
        }

        // For make sure already added event mListener for receive paused event
        FileDownloadList.getImpl().add(runningTask);
        FileDownloadList.getImpl().remove(runningTask, MessageSnapshotTaker.catchPause(origin));

        FileDownloader.getImpl().getLostConnectedHandler().taskWorkFine(runningTask);

        return true;
    }

    @Override
    public byte getStatus() {
        return mStatus;
    }

    @Override
    public void reset() {
        mThrowable = null;

        mEtag = null;
        mIsResuming = false;
        mRetryingTimes = 0;
        mIsReusedOldFile = false;
        mIsLargeFile = false;

        mSoFarBytes = 0;
        mTotalBytes = 0;

        mSpeedMonitor.reset();

        if (FileDownloadStatus.isOver(mStatus)) {
            mMessenger.discard();
            mMessenger = new FileDownloadMessenger(mTask.getRunningTask(), this);
        } else {
            mMessenger.reAppointment(mTask.getRunningTask(), this);
        }

        mStatus = FileDownloadStatus.INVALID_STATUS;
    }

    @Override
    public void setMinIntervalUpdateSpeed(int minIntervalUpdateSpeed) {
        mSpeedLookup.setMinIntervalUpdateSpeed(minIntervalUpdateSpeed);
    }

    @Override
    public int getSpeed() {
        return mSpeedLookup.getSpeed();
    }

    @Override
    public long getSofarBytes() {
        return mSoFarBytes;
    }

    @Override
    public long getTotalBytes() {
        return mTotalBytes;
    }

    @Override
    public Throwable getErrorCause() {
        return mThrowable;
    }

    @Override
    public int getRetryingTimes() {
        return mRetryingTimes;
    }

    @Override
    public boolean isReusedOldFile() {
        return mIsReusedOldFile;
    }

    @Override
    public boolean isResuming() {
        return mIsResuming;
    }

    @Override
    public String getEtag() {
        return mEtag;
    }

    @Override
    public boolean isLargeFile() {
        return mIsLargeFile;
    }

    @Override
    public void free() {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "free the task %d, when the status is %d", getId(), mStatus);
        }
        mStatus = FileDownloadStatus.INVALID_STATUS;
    }

    private void prepare() throws IOException {
        final BaseDownloadTask.IRunningTask runningTask = mTask.getRunningTask();
        final BaseDownloadTask origin = runningTask.getOrigin();

        if (origin.getPath() == null) {
            origin.setPath(FileDownloadUtils.getDefaultSaveFilePath(origin.getUrl()));
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(this, "save Path is null to %s", origin.getPath());
            }
        }

        final File dir;
        if (origin.isPathAsDirectory()) {
            dir = new File(origin.getPath());
        } else {
            final String dirString = FileDownloadUtils.getParent(origin.getPath());
            if (dirString == null) {
                throw new InvalidParameterException(
                        FileDownloadUtils.formatString("the provided mPath[%s] is invalid," +
                                " can't find its directory", origin.getPath()));
            }
            dir = new File(dirString);
        }

        if (!dir.exists()) {
            if (!dir.mkdirs() && !dir.exists()) {
                throw new IOException(FileDownloadUtils.
                        formatString("Create parent directory failed, please make sure " +
                                        "you have permission to create file or directory on the path: %s",
                                dir.getAbsolutePath()));
            }
        }
    }

    private int getId() {
        return mTask.getRunningTask().getOrigin().getId();
    }

    @Override
    public void start() {
        if (mStatus != FileDownloadStatus.toLaunchPool) {
            FileDownloadLog.w(this, "High concurrent cause, this task %d will not start," +
                            " because the of status isn't toLaunchPool: %d",
                    getId(), mStatus);
            return;
        }

        final BaseDownloadTask.IRunningTask runningTask = mTask.getRunningTask();
        final BaseDownloadTask origin = runningTask.getOrigin();

        final ILostServiceConnectedHandler lostConnectedHandler = FileDownloader.getImpl().
                getLostConnectedHandler();
        try {

            if (lostConnectedHandler.dispatchTaskStart(runningTask)) {
                return;
            }

            synchronized (mPauseLock) {
                if (mStatus != FileDownloadStatus.toLaunchPool) {
                    FileDownloadLog.w(this, "High concurrent cause, this task %d will not start," +
                                    " the status can't assign to toFileDownloadService, because the status" +
                                    " isn't toLaunchPool: %d",
                            getId(), mStatus);
                    return;
                }

                mStatus = FileDownloadStatus.toFileDownloadService;
            }

            FileDownloadList.getImpl().add(runningTask);
            if (FileDownloadHelper.inspectAndInflowDownloaded(
                    origin.getId(), origin.getTargetFilePath(), origin.isForceReDownload(), true)
                    ) {
                // Will be removed when the complete message is received in #update
                return;
            }

            final boolean succeed = FileDownloadServiceProxy.getImpl().
                    start(
                            origin.getUrl(),
                            origin.getPath(),
                            origin.isPathAsDirectory(),
                            origin.getCallbackProgressTimes(), origin.getCallbackProgressMinInterval(),
                            origin.getAutoRetryTimes(),
                            origin.isForceReDownload(),
                            mTask.getHeader(),
                            origin.isWifiRequired());

            if (mStatus == FileDownloadStatus.paused) {
                FileDownloadLog.w(this, "High concurrent cause, this task %d will be paused," +
                        "because of the status is paused, so the pause action must be applied", getId());
                if (succeed) {
                    FileDownloadServiceProxy.getImpl().pause(getId());
                }
                return;
            }

            if (!succeed) {
                //noinspection StatementWithEmptyBody
                if (!lostConnectedHandler.dispatchTaskStart(runningTask)) {
                    final MessageSnapshot snapshot = prepareErrorMessage(
                            new RuntimeException("Occur Unknown Error, when request to start" +
                                    " maybe some problem in binder, maybe the process was killed in " +
                                    "unexpected."));

                    if (FileDownloadList.getImpl().isNotContains(runningTask)) {
                        lostConnectedHandler.taskWorkFine(runningTask);
                        FileDownloadList.getImpl().add(runningTask);
                    }

                    FileDownloadList.getImpl().remove(runningTask, snapshot);

                } else {
                    // the FileDownload Service host process was killed when request stating and it
                    // will be restarted by LostServiceConnectedHandler.
                }
            } else {
                lostConnectedHandler.taskWorkFine(runningTask);
            }

        } catch (Throwable e) {
            e.printStackTrace();

            FileDownloadList.getImpl().remove(runningTask, prepareErrorMessage(e));
        }
    }

    @Override
    public boolean equalListener(FileDownloadListener listener) {
        return mTask.getRunningTask().getOrigin().getListener() == listener;
    }
}


text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2018)
//   René Fritze     (2018)

#ifndef DUNE_GDT_LOCAL_BILINEAR_FORMS_INTERFACES_HH
#define DUNE_GDT_LOCAL_BILINEAR_FORMS_INTERFACES_HH

#include <memory>
#include <vector>

#include <dune/common/dynmatrix.hh>

#include <dune/xt/common/parameter.hh>
#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/interfaces/element-functions.hh>

namespace Dune {
namespace GDT {

/**
 * Interface for local bilinear forms associated with grid elements.
 *
 * \note Regarding SMP: the bilinear form is copied for each thread, so
 *       - no shared mutable state between copies to be thread safe, but
 *       - local mutable state is ok.
 */
template <class Element,
          size_t test_range_dim = 1,
          size_t test_range_dim_cols = 1,
          class TestRangeField = double,
          class Field = double,
          size_t ansatz_range_dim = test_range_dim,
          size_t ansatz_range_dim_cols = test_range_dim_cols,
          class AnsatzRangeField = TestRangeField>
class LocalElementBilinearFormInterface
  : public XT::Common::ParametricInterface
  , public XT::Common::WithLogger<LocalElementBilinearFormInterface<Element,
                                                                    test_range_dim,
                                                                    test_range_dim_cols,
                                                                    TestRangeField,
                                                                    Field,
                                                                    ansatz_range_dim,
                                                                    ansatz_range_dim_cols,
                                                                    AnsatzRangeField>>
{
  static_assert(XT::Grid::is_entity<Element>::value, "");

  using ThisType = LocalElementBilinearFormInterface;
  using Logger = XT::Common::WithLogger<LocalElementBilinearFormInterface<Element,
                                                                          test_range_dim,
                                                                          test_range_dim_cols,
                                                                          TestRangeField,
                                                                          Field,
                                                                          ansatz_range_dim,
                                                                          ansatz_range_dim_cols,
                                                                          AnsatzRangeField>>;

public:
  using E = Element;
  using D = typename Element::Geometry::ctype;
  static constexpr size_t d = E::dimension;
  using F = Field;

  using TR = TestRangeField;
  static constexpr size_t t_r = test_range_dim;
  static constexpr size_t t_rC = test_range_dim_cols;

  using AR = AnsatzRangeField;
  static constexpr size_t a_r = ansatz_range_dim;
  static constexpr size_t a_rC = ansatz_range_dim_cols;

  using ElementType = Element;
  using LocalTestBasisType = XT::Functions::ElementFunctionSetInterface<E, t_r, t_rC, TR>;
  using LocalAnsatzBasisType = XT::Functions::ElementFunctionSetInterface<E, a_r, a_rC, AR>;

  LocalElementBilinearFormInterface(const XT::Common::ParameterType& param_type = {},
                                    const std::string& logging_prefix = "",
                                    const bool logging_disabled = true)
    : XT::Common::ParametricInterface(param_type)
    , Logger(logging_prefix.empty() ? "LocalElementBilinearForm" : logging_prefix, logging_disabled)
  {
    LOG_(debug) << "LocalElementBilinearFormInterface(this=" << this << ", param_type=" << param_type << ")"
                << std::endl;
  }

  LocalElementBilinearFormInterface(const ThisType&) = default;

  LocalElementBilinearFormInterface(ThisType&&) = default;

  virtual ~LocalElementBilinearFormInterface() = default;

  virtual std::unique_ptr<ThisType> copy() const = 0;

  /**
   * Computes the application of this bilinear form for all combinations of functions from the bases.
   */
  virtual void apply2(const LocalTestBasisType& test_basis,
                      const LocalAnsatzBasisType& ansatz_basis,
                      DynamicMatrix<F>& result,
                      const XT::Common::Parameter& param = {}) const = 0;

  /**
   * This method is provided for convenience and should not be used within library code.
   */
  virtual DynamicMatrix<F> apply2(const LocalTestBasisType& test_basis,
                                  const LocalAnsatzBasisType& ansatz_basis,
                                  const XT::Common::Parameter& param = {}) const
  {
    DynamicMatrix<F> result(test_basis.size(param), ansatz_basis.size(param), 0);
    this->apply2(test_basis, ansatz_basis, result, param);
    return result;
  }
}; // class LocalElementBilinearFormInterface

/**
 * Interface for local bilinear forms associated with inner grid intersections, applied to test and ansatz bases on
 * either side.
 *
 * \note Regarding SMP: the bilinear form is copied for each thread, so
 *       - no shared mutable state between copies to be thread safe, but
 *       - local mutable state is ok.
 */
template <class Intersection,
          size_t test_range_dim = 1,
          size_t test_range_dim_cols = 1,
          class TestRangeField = double,
          class Field = double,
          size_t ansatz_range_dim = test_range_dim,
          size_t ansatz_range_dim_cols = test_range_dim_cols,
          class AnsatzRangeField = TestRangeField>
class LocalCouplingIntersectionBilinearFormInterface
  : public XT::Common::ParametricInterface
  , public XT::Common::WithLogger<LocalCouplingIntersectionBilinearFormInterface<Intersection,
                                                                                test_range_dim,
                                                                                test_range_dim_cols,
                                                                                TestRangeField,
                                                                                Field,
                                                                                ansatz_range_dim,
                                                                                ansatz_range_dim_cols,
                                                                                AnsatzRangeField>>
{
  static_assert(XT::Grid::is_intersection<Intersection>::value, "");

  using ThisType = LocalCouplingIntersectionBilinearFormInterface;
  using Logger = XT::Common::WithLogger<LocalCouplingIntersectionBilinearFormInterface<Intersection,
                                                                                test_range_dim,
                                                                                test_range_dim_cols,
                                                                                TestRangeField,
                                                                                Field,
                                                                                ansatz_range_dim,
                                                                                ansatz_range_dim_cols,
                                                                                AnsatzRangeField>>;

public:
  using IntersectionType = Intersection;
  using ElementType = XT::Grid::extract_inside_element_t<Intersection>;

  using I = Intersection;
  using E = ElementType;
  using D = typename ElementType::Geometry::ctype;
  static constexpr size_t d = E::dimension;
  using F = Field;

  using TR = TestRangeField;
  static constexpr size_t t_r = test_range_dim;
  static constexpr size_t t_rC = test_range_dim_cols;

  using AR = AnsatzRangeField;
  static constexpr size_t a_r = ansatz_range_dim;
  static constexpr size_t a_rC = ansatz_range_dim_cols;

  using LocalTestBasisType = XT::Functions::ElementFunctionSetInterface<E, t_r, t_rC, TR>;
  using LocalAnsatzBasisType = XT::Functions::ElementFunctionSetInterface<E, a_r, a_rC, AR>;

  LocalCouplingIntersectionBilinearFormInterface(const XT::Common::ParameterType& param_type = {},
                                                 const std::string& logging_prefix = "",
                                                 const bool logging_disabled = true)
    : XT::Common::ParametricInterface(param_type)
    , Logger(logging_prefix.empty() ? "LocalCouplingIntersectionBilinearForm" : logging_prefix, logging_disabled)
  {}

  LocalCouplingIntersectionBilinearFormInterface(const ThisType&) = default;

  LocalCouplingIntersectionBilinearFormInterface(ThisType&&) = default;

  virtual ~LocalCouplingIntersectionBilinearFormInterface() = default;

  virtual std::unique_ptr<ThisType> copy() const = 0;

  /**
   * Computes the application of this bilinear form for all combinations of functions from all bases.
   */
  virtual void apply2(const IntersectionType& intersection,
                      const LocalTestBasisType& test_basis_inside,
                      const LocalAnsatzBasisType& ansatz_basis_inside,
                      const LocalTestBasisType& test_basis_outside,
                      const LocalAnsatzBasisType& ansatz_basis_outside,
                      DynamicMatrix<F>& result_in_in,
                      DynamicMatrix<F>& result_in_out,
                      DynamicMatrix<F>& result_out_in,
                      DynamicMatrix<F>& result_out_out,
                      const XT::Common::Parameter& param = {}) const = 0;

  /**
   * This method is provided for convenience and should not be used within library code.
   */
  virtual std::array<DynamicMatrix<F>, 4> apply2(const IntersectionType& intersection,
                                                 const LocalTestBasisType& test_basis_inside,
                                                 const LocalAnsatzBasisType& ansatz_basis_inside,
                                                 const LocalTestBasisType& test_basis_outside,
                                                 const LocalAnsatzBasisType& ansatz_basis_outside,
                                                 const XT::Common::Parameter& param = {}) const
  {
    DynamicMatrix<F> result_in_in(test_basis_inside.size(param), ansatz_basis_inside.size(param), 0);
    DynamicMatrix<F> result_in_out(test_basis_inside.size(param), ansatz_basis_outside.size(param), 0);
    DynamicMatrix<F> result_out_in(test_basis_outside.size(param), ansatz_basis_inside.size(param), 0);
    DynamicMatrix<F> result_out_out(test_basis_outside.size(param), ansatz_basis_outside.size(param), 0);
    this->apply2(intersection,
                 test_basis_inside,
                 ansatz_basis_inside,
                 test_basis_outside,
                 ansatz_basis_outside,
                 result_in_in,
                 result_in_out,
                 result_out_in,
                 result_out_out,
                 param);
    return {result_in_in, result_in_out, result_out_in, result_out_out};
  } // ... apply2(...)
}; // class LocalCouplingIntersectionBilinearFormInterface

/**
 * Interface for local bilinear forms associated with grid intersections, applied to test and ansatz bases on only one
 * side of the intersection.
 *
 * \note Regarding SMP: the bilinear form is copied for each thread, so
 *       - no shared mutable state between copies to be thread safe, but
 *       - local mutable state is ok.
 */
template <class Intersection,
          size_t test_range_dim = 1,
          size_t test_range_dim_cols = 1,
          class TestRangeField = double,
          class Field = double,
          size_t ansatz_range_dim = test_range_dim,
          size_t ansatz_range_dim_cols = test_range_dim_cols,
          class AnsatzRangeField = TestRangeField>
class LocalIntersectionBilinearFormInterface
  : public XT::Common::ParametricInterface
  , public XT::Common::WithLogger<LocalIntersectionBilinearFormInterface<Intersection,
                                                                         test_range_dim,
                                                                         test_range_dim_cols,
                                                                         TestRangeField,
                                                                         Field,
                                                                         ansatz_range_dim,
                                                                         ansatz_range_dim_cols,
                                                                         AnsatzRangeField>>
{
  static_assert(XT::Grid::is_intersection<Intersection>::value, "");

  using ThisType = LocalIntersectionBilinearFormInterface;
  using Logger = XT::Common::WithLogger<LocalIntersectionBilinearFormInterface<Intersection,
                                                                               test_range_dim,
                                                                               test_range_dim_cols,
                                                                               TestRangeField,
                                                                               Field,
                                                                               ansatz_range_dim,
                                                                               ansatz_range_dim_cols,
                                                                               AnsatzRangeField>>;

public:
  using IntersectionType = Intersection;
  using ElementType = XT::Grid::extract_inside_element_t<Intersection>;

  using I = Intersection;
  using E = ElementType;
  using D = typename ElementType::Geometry::ctype;
  static const constexpr size_t d = E::dimension;
  using F = Field;

  using TR = TestRangeField;
  static const constexpr size_t t_r = test_range_dim;
  static const constexpr size_t t_rC = test_range_dim_cols;

  using AR = AnsatzRangeField;
  static const constexpr size_t a_r = ansatz_range_dim;
  static const constexpr size_t a_rC = ansatz_range_dim_cols;

  using LocalTestBasisType = XT::Functions::ElementFunctionSetInterface<E, t_r, t_rC, TR>;
  using LocalAnsatzBasisType = XT::Functions::ElementFunctionSetInterface<E, a_r, a_rC, AR>;

  LocalIntersectionBilinearFormInterface(const XT::Common::ParameterType& param_type = {},
                                         const std::string& logging_prefix = "",
                                         const bool logging_disabled = true)
    : XT::Common::ParametricInterface(param_type)
    , Logger(logging_prefix.empty() ? "LocalIntersectionBilinearForm" : logging_prefix, logging_disabled)
  {}

  LocalIntersectionBilinearFormInterface(const ThisType&) = default;

  LocalIntersectionBilinearFormInterface(ThisType&&) = default;

  virtual ~LocalIntersectionBilinearFormInterface() = default;

  virtual std::unique_ptr<ThisType> copy() const = 0;

  /**
   * Flag to document which element the bases are expected to be bound to.
   */
  virtual bool inside() const
  {
    return true;
  }

  /**
   * Computes the application of this bilinear form for all combinations of functions from the bases.
   */
  virtual void apply2(const IntersectionType& intersection,
                      const LocalTestBasisType& test_basis,
                      const LocalAnsatzBasisType& ansatz_basis,
                      DynamicMatrix<F>& result,
                      const XT::Common::Parameter& param = {}) const = 0;

  /**
   * This method is provided for convenience and should not be used within library code.
   */
  DynamicMatrix<F> apply2(const IntersectionType& intersection,
                          const LocalTestBasisType& test_basis,
                          const LocalAnsatzBasisType& ansatz_basis,
                          const XT::Common::Parameter& param = {}) const
  {
    DynamicMatrix<F> result(test_basis.size(param), ansatz_basis.size(param), 0);
    this->apply2(intersection.test_basis, ansatz_basis, param);
    return result;
  }

protected:
  mutable DynamicMatrix<F> unused_result_;
}; // class LocalIntersectionBilinearFormInterface

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCAL_BILINEAR_FORMS_INTERFACES_HH

redpajama_set_name: RedPajamaGithub


text:
title: Installing Keyboards with Keyman for Linux
---

Keyboards are installed with Keyman Configuration. From the launcher, enter `Keyman Configuration`.
Alternatively from the command line run `km-config`.

![](../linux_images/km-config.png "Keyman Configuration")

## Download from Keyman cloud repository

From Keyman Configuration, click "Download". At the search page, enter the keyboard you want to download.

![](../linux_images/search-khmer-angkor.png "Search for khmer_angkor keyboard")

Clicking the keyboard brings the keyboard page which has a link for installation.

![](../linux_images/download-khmer-angkor.png "Install khmer_angkor")

## Install Local .kmp keyboard package

Keyman for Linux can also install keyboards from local .kmp keyboard packages. From Keyman Configuration,
click "Install". Then browse to the local .kmp keyboard package and install.

![](../linux_images/package-khmer-angkor-welcome.png "Package khmer_angkor")

The keyboard should appear in Keyman Configuration.

![](../linux_images/km-config-khmer-angkor.png "Keyman Configuration khmer_angkor")

Your input source is now accessible in IBus. Use the shortcut Windows-spacebar to switch input source.

![](../linux_images/region-language-khmer-angkor.png "Region & Language: khmer_angkor")


text:
'use strict';

function initCall() {
  console.log('Google maps api initialized.');
  angular.bootstrap(document.getElementById('map'), ['app']);
}

var controllers = angular.module('app.controllers');

controllers.controller('MapController', ['$scope', '$rootScope', '$timeout', '$stateParams', 'Shared', 'NavService',
function ($scope, $rootScope, $timeout, $stateParams, Shared, NavService) {
    console.log('Google maps controller.');

    var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(28.70, -127.50),
     new google.maps.LatLng(48.85, -55.90)
    );

    var mapStyles=[{
        featureType: 'all',
        elementType: 'labels',
        stylers:[
            {visibility: 'off'}
        ]
    },{
        featureType: 'water',
        elementType:'geometry',
        stylers:[
            {color: '#4E78A0'}
        ]
    },{
        featureType: 'landscape',
        elementType: 'geometry',
        stylers: [
        {color:'#272D34'}
        ]
    },{
        featureType: 'poi',
        elementType: 'geometry',
        stylers: [
        {color:'#272D34'}
        ]
    },{
        featureType: 'transit',
        elementType: 'geometry',
        stylers: [
        {color:'#4E78A0'}
        ]
    },{
        featureType: 'road',
        elementType: 'geometry',
        stylers: [
        {color:'#434C55'}
        ]
    }];

    var gm = google.maps;
    var markerShadow = new gm.MarkerImage(
        'https://www.google.com/intl/en_ALL/mapfiles/shadow50.png',
        new gm.Size(37, 34),  // size   - for sprite clipping
        new gm.Point(0, 0),   // origin - ditto
        new gm.Point(10, 34)  // anchor - where to meet map location
    );

    var getMarkerGeoLocation = $scope.getMarkerGeoLocation = Shared.getMarkerGeoLocation;

    var omsOptions = {
        keepSpiderfied: true,
        markersWontMove: true,
        markersWontHide: true
    };

    /* $scope.myMap auto-populated with google map object */
    $scope.isEditMode = false;
    $scope.isAdmin = false

    //TODO: use permissions to determine what content user can create if any
    $scope.contentTypes = ['event', 'amenity', 'alert'];
    $scope.newMarkers = [];

    $scope.mapOptions = {
        center: new google.maps.LatLng(40.6880492, -74.0188415),
        streetViewControl: false,
        panControl: false,
        mapTypeControl: false,
        zoomControl: true,
        disableDefaultUI: true,
        zoom: 17,
        maxZoom: 18,
        minZoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControlOptions:{
            position: google.maps.ControlPosition.RIGHT_TOP,
            style: google.maps.ZoomControlStyle.small
        },
        styles:mapStyles
    };

    $scope.mapEvents = {
        'map-rightclick': 'addNewMarker($event, $params)'
    };

    console.log('$rootScope.user', $rootScope.user);
    var user = $rootScope.user;
    if(user){
        //TODO: use actual permissions
        if(user.roles){
            user.roles.forEach(function(role){
                if(role.name === 'admin'){
                    $scope.isAdmin = true;
                    $scope.isEditMode = true;
                    omsOptions.markersWontMove = false;
                    omsOptions.markersWontHide  = false;
                }
            });
        }
    }

    $scope.$watch('myMap', function setupMap(map){
        if(!map){return;}
        $scope.mapInit();
        $scope.omsInit();

        var preSelectedFilters = $stateParams.filters;
        if(preSelectedFilters){
            preSelectedFilters = preSelectedFilters.split(',');
            Shared.filters = preSelectedFilters;

            $timeout(function() {
                angular.element('#filter-menu').trigger('click')
            }, 150);
        }
    });

    $scope.mapInit = function() {
        var options = $scope.mapOptions;
        var map = $scope.myMap;
        var mapBounds = new google.maps.LatLngBounds(
          new google.maps.LatLng(40.682146, -74.027796),
          new google.maps.LatLng(40.695640, -74.009978)
        );

        // var maptiler = new klokantech.MapTilerMapType(map, mapGetTile, mapBounds, options.minZoom, options.maxZoom);
        var googleMapsOverlay = new google.maps.ImageMapType({
            getTileUrl: function(coord, zoom) {
                var proj = map.getProjection();
                var z2 = Math.pow(2, zoom);
                var tileXSize = 256 / z2;
                var tileYSize = 256 / z2;
                var tileBounds = new google.maps.LatLngBounds(
                    proj.fromPointToLatLng(new google.maps.Point(coord.x * tileXSize, (coord.y + 1) * tileYSize)),
                    proj.fromPointToLatLng(new google.maps.Point((coord.x + 1) * tileXSize, coord.y * tileYSize))
                );
                var y = coord.y;
                if (mapBounds.intersects(tileBounds) && (options.minZoom <= zoom) && (zoom <= options.maxZoom)){
                    return "templates/maps/"+zoom + "/" + coord.x + "/" + y + ".png";
                }
                else{
                    return "templates/maps/blink.png";
                }
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: true,
            opacity: 1.0,
            name: "GovsIsle"
        });

        map.fitBounds(mapBounds);
        map.setTilt(0); //disable 45 degree view
        map.overlayMapTypes.insertAt(0, googleMapsOverlay);
    };

    $scope.omsInit = function(){
        var map = $scope.myMap;
        var oms = $scope.oms = new OverlappingMarkerSpiderfier(map, omsOptions);

        oms.addListener('click', function(marker) {
            $scope.openMarkerInfo(marker, marker.entity);
        });

        oms.addListener('spiderfy', function(markers) {
            for(var i = 0; i < markers.length; i ++) {
                markers[i].setShadow(null);
            }
            $scope.myInfoWindow.close();
        });

        oms.addListener('unspiderfy', function(markers) {
            for(var i = 0; i < markers.length; i ++) {
                markers[i].setShadow(markerShadow);
            }
        });
    };

    $scope.openMarkerInfo = function (marker, entity) {
        console.log('openMarkerInfo marker', marker, 'entity', entity );

        $scope.currentMarker = marker;

        //TODO: swtich on entyity.type or rename currentEvent
        $scope.currentEvent = entity;
        $scope.currentMarker = marker;
        $scope.myInfoWindow.open($scope.myMap, marker);
    };

    $scope.openNotificationCenter = function(alert){
        $timeout(function() {
            angular.element('#notification-center').trigger('click');
            angular.element('.list-notification #'+ alert.id).trigger('click');
        }, 1);
    };

    $scope.addNewMarker = function ($event, $params) {
        console.log('rightclick', $event, $params);

        if(!$scope.isEditMode){
            console.log('not isEditMode');
            return;
        }

        if(!$scope.isAdmin){
            console.log('not isAdmin');
            return;
        }

        // TODO: check user's permissions first
        var marker = new google.maps.Marker({
            map: $scope.myMap,
            position: $params[0].latLng,
            draggable: true
        });
        $scope.oms.addMarker(marker);
        $scope.newMarkers.push(marker);
    };

    $scope.editMarker = function(marker, entity){
        console.log('editting marker', marker, 'entity', entity);

        if(!$scope.isAdmin){
            console.log('not isAdmin');
            return;
        }

        $scope.$broadcast('MARKER_CAN_BE_EDITED_EVENT', {
            marker: marker,
            entity: entity
        });
    };

    $scope.cancelMarker = function(marker, markers){
        markers = markers.filter(function(_marker){
            return marker !== _marker
        });
        marker.setMap(null);
        $scope.oms.removeMarker(marker);
    };

    $scope.updateGeolocationAfterDrag = function(marker, entity){
        console.log('updating entity position. entity', entity, 'marker', marker);

        var geoLocation = getMarkerGeoLocation(marker);
        if(entity){
            entity.geoLocation = geoLocation;
        }

    };

    $scope.userLocation = function(){
        var map = $scope.myMap;

        var coordinates = function(position){
            var lat = position.coords.latitude,
                lon = position.coords.longitude,
                accu = position.coords.accuracy; //return the accuracy in meters
            //alert(accu);
            var coords = lat+ ', '+ lon;
            //document.getElementById('google_map').setAttribute('src',"https://maps.google.com?q="+coords+"&z=18&output=embed" )

            var newmarker = new google.maps.Marker({
                map: map,
                position: {lat:40.689462, lng:-74.016792},
                draggable: false,
                icon:'http://res.cloudinary.com/hqsaer6gs/image/upload/c_scale,h_51/v1410040466/locationMarker_lfmaem.png'
            });
            $scope.oms.addMarker(newmarker);
            return [lat, lon];

        };

        var err = function(error){
            //1 no premission, 2 no internet conncetion, 3 timeout
            if(error.code===1){
                console.log('please allow us to access your location');
            }
            if(error.code===3){
                console.log('The browser timeout');
            }
        };

        $scope.activateLink = function(numbtn) {
            NavService.updateBtn(numbtn);
        };

        document.getElementById('geolocation').onclick=function(){
            navigator.geolocation.getCurrentPosition(coordinates, err,
                {enableHighAccuracy: true,   //enableHighAccuracy: true -> increase by 10 meters
                    maximumAge: 30000,      //in millisecond to refresh the cache
                    //timeout: 300         //time in seconds for the browser to get the location
                });
            return false;
        }
    };
}]);

controllers.controller('MarkerListController', ['$scope', '$state','$stateParams','Events', 'Amenities', 'Alerts',
    'Tours', 'Shared', function($scope, $state, $stateParams, Events, Amenities, Alerts, Tours, Shared){
    console.log('in MarkerListController');

    $scope.events = [];
    $scope.existingEventMarkers = [];

    $scope.amenities = [];
    $scope.existingAmenityMarkers = [];

    $scope.tourPoints = [];
    $scope.tourMarkers = [];

    $scope.alerts = [];
    $scope.existingAlertMarkers = [];

    $scope.markerEvents = {
        //'map-click': 'openMarkerInfo(marker, entity)',
        'map-rightclick': 'editMarker(marker, entity)',
        'map-dragend': 'updateGeolocationAfterDrag(marker, entity)'
    };

    var determineMarkerIcon = function(entity){
        var icon;

        //using marker dot to distinguish between published and unpublished entity
        switch(entity.type){
            default:
            case 'event':
                icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/red.png';
                }
                break;
            case 'food':
            case 'drink':
                icon = 'http://maps.google.com/mapfiles/ms/icons/pink-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/pink.png';
                }
                break;
            case 'info':
                icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/green.png';
                }
                break;
            case 'activity':
                icon = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/orange.png';
                }
                break;
            case 'facility':
                icon = 'http://maps.google.com/mapfiles/ms/icons/ltblue-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/lightblue.png';
                }
                break;
            case 'tour':
                icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';

                break;
            case 'venue':
                icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';

                if(!entity.published){
                    icon = 'http://maps.google.com/mapfiles/ms/icons/purple.png';
                }
                break;
        }
        return icon;
    };

    var createMarker = function(entity, map){
        var position = new google.maps.LatLng(entity.geoLocation[0], entity.geoLocation[1]);

        var markerOptions = {
            map: map,
            position: position,
            draggable: false
        };

        var icon = determineMarkerIcon(entity);

        if(icon) {
            markerOptions.icon = icon;
        }

        var marker = new google.maps.Marker(markerOptions);
        marker.entity = entity;

        //console.log('existing entity', entity, 'marker', marker);
        return marker;
    };

    var createTourMarker = function(tourpoint, map){

		tourpoint.name = tourpoint.postName;
		tourpoint.description = tourpoint.postText;
		tourpoint.type = 'tour';
		//tourpoint.geoLocation[0] = tourpoint.latitude;
		//tourpoint.geoLocation[1] = tourpoint.longitude;

        var position = new google.maps.LatLng(tourpoint.latitude, tourpoint.longitude);

        var markerOptions = {
            map: map,
            position: position,
            draggable: false
        };

        var icon = determineMarkerIcon(tourpoint);

        if(icon) {
            markerOptions.icon = icon;
        }

        var marker = new google.maps.Marker(markerOptions);
		//console.log(tourpoint.description);
		marker.entity = tourpoint;

        //console.log('existing entity', tourpoint, 'marker', marker);
        return marker;
    };

    var clearMarkers = function(markers){
        markers.forEach(function(marker){
            marker.setMap(null);
        });
        markers = [];;
        $scope.oms.clearMarkers()
    };

    var updateMarkerIcon = function(entity, marker, markers){
        for(var i = markers.length - 1; i >= 0; i--){
            if(markers[i] == marker){
                var icon = determineMarkerIcon(entity);
                marker.setIcon(icon);
                break;
            }
        }
    };

    // TODO: filters are case sensitive
    var getContentByFilters = function(filters){
        console.log('getContentByFilters', filters);
        clearMarkers($scope.existingEventMarkers);
        clearMarkers($scope.existingAmenityMarkers);
        clearMarkers($scope.tourMarkers);

        if(filters.indexOf('tour') >= 0){
            var _tourpoints = [];
			Tours.getTourpoints(function(data){
			   for(var i in data['tour_points']) {
				    //console.log(data['tour_points'] [i]);
			       	//_tourpoints.push(data['tour_points'] [i]);
					//console.log(data['tour_points'] [i]);
	                var marker = createTourMarker(data['tour_points'] [i], $scope.myMap);
                    marker.source = 'tours';

	                $scope.oms.addMarker(marker);
					$scope.tourMarkers.push(marker);
	                $scope.tourPoints.push(data['tour_points'] [i]);
			   }

			});
        }

        if(filters && filters.length){
            Events.query({filter: filters}, function(events){
                console.log('events', events);
                events.forEach(function(event){
                    var marker = createMarker(event, $scope.myMap);
                    marker.source = 'events';

                    $scope.oms.addMarker(marker);
                    $scope.existingEventMarkers.push(marker);
                    $scope.events.push(event);
                });
            });

            //remove 'event' filter from the set of filters to prevent including
            //amenities query
            filters = filters.filter(function(f){
                return f != 'event'
            });

            Amenities.query({filter: filters}, function(amenities){
                console.log('amenities', amenities);
                amenities.forEach(function(amenity){
                    var marker = createMarker(amenity, $scope.myMap);
                    marker.source = 'amenities';

                    $scope.oms.addMarker(marker);
                    $scope.existingAmenityMarkers.push(marker);
                    $scope.amenities.push(amenity);
                });
            });
        }
    };

    $scope.Shared = Shared;
    $scope.$watch('Shared.filters', function(newVal, oldVal){
        //console.log('FILTERS_CHANGED', newVal, oldVal);
        if(newVal && !oldVal){
            //special case - ignores
            return;
        }
        if(!newVal){
            Shared.filters = Shared.allFilters;
            return getContentByFilters(Shared.filters);
        }
        getContentByFilters(newVal);
    }, true);

    $scope.$watch('Shared.alerts + Shared.filters', function handleAlertMarkers(){
        var alerts = Shared.alerts;
        var filters = Shared.filters;

        console.log('NEW ALERTS', alerts, 'NEW FILTERS', filters);

        if(!alerts || !filters){
            return;
        }

        clearMarkers($scope.existingAlertMarkers);
        if(filters.indexOf('alert') < 0){
            return;
        }

        alerts.forEach(function(alert){
            var marker = createMarker(alert, $scope.myMap);
            marker.source = 'alerts';

            $scope.oms.addMarker(marker);
            $scope.existingAlertMarkers.push(marker);
            $scope.alerts.push(alert);
        });
    }, true);

    $scope.$on('MARKER_UPDATED_EVENT', function(event, args){
        if(args.event){
            updateMarkerIcon(args.event, args.marker, $scope.existingEventMarkers);
        }
        else if(args.amenity){
            updateMarkerIcon(args.amenity, args.marker, $scope.existingAmenityMarkers);
        }
    });

    $scope.$watch(function(){return Shared.newEntityTurnedExisting}, function(args){
        if(!args){return}

        var marker = args.marker;
        var entity = args.event || args.amenity;

        $scope.oms.addMarker(marker);
        if(args.event){
            $scope.existingEventMarkers.push(marker);
            $scope.events.push(args.event);

            updateMarkerIcon(args.event, args.marker, $scope.existingEventMarkers);
        }
        else if(args.amenity){
            $scope.existingAmenityMarkers.push(marker);
            $scope.amenities.push(args.amenity);

            updateMarkerIcon(args.amenity, args.marker, $scope.existingAmenityMarkers);
        }

        marker.entity = entity;

    });
}]);

controllers.controller('NewMarkerListController', ['$scope', '$controller', 'Shared', function($scope, $controller, Shared){
    console.log('in NewMarkerListController');

    $scope.newMarkerEvents = {
        //'map-click': 'openMarkerInfo(marker, findRelatedEntity(marker))',
        'map-rightclick': 'editMarker(marker, findRelatedEntity(marker))',
        'map-dragend': 'updateGeolocationAfterDrag(marker, findRelatedEntity(marker))'
    };

    $scope.newEntities = [];

    $scope.$on('NEW_ENTITY_EVENT', function(event, args){
        console.log('responding to NEW_ENTITY_EVENT. args', args);
        $scope.newEntities.push(args.entity);
    });

    $scope.$on('ENTITY_PERSISTED_EVENT', function(event, args){
        var marker = args.marker;
        marker.isPersisted = true;

        if(args.alert){
            // handleAlertMarkers in MarkerListController takes care of alerts marker logic
            //instead of updating this marker, a new one will be created
            marker.setMap(null);
            $scope.oms.removeMarker(marker);
            return;
        }

        var params = {
            marker: marker,
        }

        if(args.event){
            params.event = args.event;
        }
        else if(args.amenity){
            params.amenity = args.amenity;
        }
        Shared.newEntityTurnedExisting = params;
    });

    $scope.findRelatedEntity = function(marker){
        var markers = $scope.newMarkers;
        var entities = $scope.newEntities;

        for(var i = markers.length - 1; i >= 0; i--){
            if(markers[i] == marker){
                return entities[i];
            }
        }
        return null;
    };
}]);


text:
create class range_test (id int,
			 test_int int,
			 test_char char(10))
partition by range(test_int) (
partition p0 values less than (10),
partition p1 values less than (20),
partition p2 values less than maxvalue);

insert into range_test values(0,-1,'-1');
insert into range_test values(1,1,'1');
insert into range_test values(2,2,'2');
insert into range_test values(3,11,'11');
insert into range_test values(4,12,'12');
insert into range_test values(5,21,'21');
insert into range_test values(6,22,'22');
insert into range_test values(7,2007,'2007');
insert into range_test values(8,4,'4');
insert into range_test values(9,5,'5');
insert into range_test values(10,16,'16');
select * from range_test where test_int = round(11.57) order by 1;
select * from range_test where test_int = ceil(11.01) order by 1;
select * from range_test where test_int = floor(11.99) order by 1;
select * from range_test where test_int = position('aa' in 'swedfrtgqcaasd') order by 1;
drop class range_Test;


text:
curl -f -s -I \
  "${BASE_URL}super" \
| tr -d '\r\n' \
| grep 'Link: <https://github.com/AtomGraph/Processor/blob/develop/http-tests/custom#DefaultSubjectSuperTemplate>; rel=https://www.w3.org/ns/ldt#template' > /dev/null


text:
QP Solver
=========

.. automodule:: active_subspaces.utils.qp_solver
    :members:


text:
{% extends 'base.html' %}
{% block pagetitle %}500 Oops{% endblock %}
{% block main_section %}

Oops!

An error occurred. Please try again later.

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sparsh.zhingur"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sparsh.zhingur.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<?php
/**
 * ECSHOP Short message module language file
 * ============================================================================
 * All right reserved (C) 2005-2011 Beijing Yi Shang Interactive Technology
 * Development Ltd.
 * Web site: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * This is a free/open source software;it means that you can modify, use and
 * republish the program code, on the premise of that your behavior is not for
 * commercial purposes.
 * ============================================================================
 * $Author: liubo $
 * $Id: sms.php 17217 2011-01-19 06:29:08Z liubo $
*/

/* Navigation */
$_LANG['register_sms'] = 'Register Or Enable Sms Account.';

/* Register or enable sms */
$_LANG['email'] = 'Email';
$_LANG['password'] = 'Password';
$_LANG['domain'] = 'Domain';
$_LANG['error_tips'] = 'Please login background from the YunQi account settings!';
$_LANG['register_new'] = 'Register';
$_LANG['enable_old'] = 'Enable account';

/* Sms special service message */
$_LANG['sms_user_name'] = 'Username:';
$_LANG['sms_password'] = 'Password:';
$_LANG['sms_domain'] = 'Domain:';
$_LANG['sms_num'] = 'Sms special service number:';
$_LANG['sms_count'] = 'Send smsquantity:';
$_LANG['sms_total_money'] = 'Total money:';
$_LANG['sms_balance'] = 'Balance:';
$_LANG['sms_last_request'] = 'Latest request time:';
$_LANG['disable'] = 'Disable sms service';

/* Send sms */
$_LANG['phone'] = 'Mobile phone';
$_LANG['user_rand'] = 'Send short message by the user level';
$_LANG['phone_notice'] = 'More than one phone number divided by DBC case comma.';
$_LANG['msg'] = 'Message';
$_LANG['msg_notice'] = '70 character at most';
$_LANG['msg_forbidden'] = 'Do not include words like "test" in the content, or may be intercepted';
$_LANG['send_date'] = 'Send at certain times';
$_LANG['send_date_notice'] = 'Format is YYYY-MM-DD HH:II. If it is blank then send immediately.';
$_LANG['back_send_history'] = 'Return to send history';
$_LANG['back_charge_history'] = 'Return to charge history';
$_LANG['sms_preview'] = 'SMS preview';
$_LANG['notice0'] = 'Has been entered';
$_LANG['notice1'] = 'character, about';
$_LANG['notice2'] = 'messages, The actual length of the text message is based on the final result';

/* Record query interface */
$_LANG['start_date'] = 'Start date';
$_LANG['date_notice'] = 'Format:YYYY-MM-DD. Allowed blank.';
$_LANG['end_date'] = 'Deadline';
$_LANG['page_size'] = 'Display every page';
$_LANG['page_size_notice'] = 'Can be blank, diaplay every 20 records.';
$_LANG['page'] = 'Page quantity';
$_LANG['page_notice'] = 'Can be blank,express display every 1 page.';
$_LANG['charge'] = 'Please enter the charge what you want to recharge.';

/* Confirm action information */
$_LANG['history_query_error'] = 'Sorry, error in the process of query.';
$_LANG['enable_ok'] = 'Congratulations, you have enabled sms service!';
$_LANG['enable_error'] = 'Sorry, you enable sms service has failed.';
$_LANG['disable_ok'] = 'You logout sms service successfully.';
$_LANG['disable_error'] = 'Logout sms service has failed.';
$_LANG['register_ok'] = 'Congratulations, you register sms service successfully!';
$_LANG['register_error'] = 'Sorry, you register sms service has failed.';
$_LANG['send_ok'] = 'Congratulations ,your message has be sent successfully!';
$_LANG['send_error'] = 'Sorry, error in the process of send.';
$_LANG['error_no'] = 'Error mark';
$_LANG['error_msg'] = 'Error description';
$_LANG['empty_info'] = 'Your sms special service is blank.';

/* cellphone replenishing record */
$_LANG['order_id'] = 'Order ID';
$_LANG['money'] = 'Recharge money';
$_LANG['log_date'] = 'Recharge date';

/* Send logs */
$_LANG['sent_phones'] = 'Sent cellphone number';
$_LANG['content'] = 'Content';
$_LANG['charge_num'] = 'Payments';
$_LANG['sent_date'] = 'Sent date';
$_LANG['send_status'] = 'Send status';
$_LANG['status'][0] = 'Fail';
$_LANG['status'][1] = 'Succeed';
$_LANG['user_list'] = 'All user';
$_LANG['please_select'] = 'Please choose the membership grade';

/* Prompting message */
$_LANG['test_now'] = '';
$_LANG['msg_price'] = '0.1 yuan(RMB) every message';

/* API return error information */
//--register
$_LANG['api_errors']['register'][1] = 'Domain name can\'t be blank.';
$_LANG['api_errors']['register'][2] = 'Mailbox is invalid.';
$_LANG['api_errors']['register'][3] = 'Username already exists.';
$_LANG['api_errors']['register'][4] = 'Unknown error.';
$_LANG['api_errors']['register'][5] = 'Port error.';
//--Gain balance
$_LANG['api_errors']['get_balance'][1] = 'Password is invalid.';
$_LANG['api_errors']['get_balance'][2] = 'User disable.';
//--Send sms
$_LANG['api_errors']['send'][1] = 'Password is invalid.';
$_LANG['api_errors']['send'][2] = 'Sms content length is invalid.';
$_LANG['api_errors']['send'][3] = 'Send time should later than current time.';
$_LANG['api_errors']['send'][4] = 'Error number.';
$_LANG['api_errors']['send'][5] = 'Balance not enough.';
$_LANG['api_errors']['send'][6] = 'Account is stoped.';
$_LANG['api_errors']['send'][7] = 'Port error.';
//--History record
$_LANG['api_errors']['get_history'][1] = 'Password is invalid.';
$_LANG['api_errors']['get_history'][2] = 'No record.';
//--User verify
$_LANG['api_errors']['auth'][1] = 'Password error.';
$_LANG['api_errors']['auth'][2] = 'No user.';

/* User server detected error information */
$_LANG['server_errors'][1] = 'error invalid register information.';//ERROR_INVALID_REGISTER_INFO
$_LANG['server_errors'][2] = 'error invalid enable information.';//ERROR_INVALID_ENABLE_INFO
$_LANG['server_errors'][3] = 'error invalid send information.';//ERROR_INVALID_SEND_INFO
$_LANG['server_errors'][4] = 'error invalid history query.';//ERROR_INVALID_HISTORY_QUERY
$_LANG['server_errors'][5] = 'error invalid passport.';//ERROR_INVALID_PASSPORT
$_LANG['server_errors'][6] = 'error invalid URL.';//ERROR_INVALID_URL
$_LANG['server_errors'][7] = 'error empty response.';//ERROR_EMPTY_RESPONSE
$_LANG['server_errors'][8] = 'error invalid xml file.';//ERROR_INVALID_XML_FILE
$_LANG['server_errors'][9] = 'error invalid node name.';//ERROR_INVALID_NODE_NAME
$_LANG['server_errors'][10] = 'error cant store.';//ERROR_CANT_STORE
$_LANG['server_errors'][11] = 'SMS feature is not yet activated.';//ERROR_INVALID_PASSPORT

/* Client JS language item */
//--Register or  invocation
$_LANG['js_languages']['password_empty_error'] = 'Please enter password.';
$_LANG['js_languages']['username_empty_error'] = 'Please enter username.';
$_LANG['js_languages']['username_format_error'] = 'Username format is invalid.';
$_LANG['js_languages']['domain_empty_error'] = 'Domain can\'t be blank.';
$_LANG['js_languages']['domain_format_error'] = 'Domain format is invalid.';
$_LANG['js_languages']['send_empty_error'] = 'Send phone number and send at least fill out a rating!';
$_LANG['js_languages']['sms_empty_error'] = 'SMS content length is not empty';

//--Send
$_LANG['js_languages']['phone_empty_error'] = 'Please enter phone number.';
$_LANG['js_languages']['phone_format_error'] = 'Phone member format is invalid.';
$_LANG['js_languages']['msg_empty_error'] = 'Please enter meaasge content.';
$_LANG['js_languages']['send_date_format_error'] = 'Timing format is invalid.';
//--History record
$_LANG['js_languages']['start_date_format_error'] = 'Start time format is invalid.';
$_LANG['js_languages']['end_date_format_error'] = 'Deadline format is invalid.';
//--Recharge
$_LANG['js_languages']['money_empty_error'] = 'Please enter charge what you want to recharge.';
$_LANG['js_languages']['money_format_error'] = 'Money format is invalid.';

$_LANG['insert_sign'] = 'Please enter the message signature';
$_LANG['insert_succ'] = 'Added successfully';
$_LANG['error_smg'] = 'Wrong information';
$_LANG['edit_succ'] = 'Successful modification';
$_LANG['default_succ'] = 'The successful signature';
$_LANG['no_default'] = 'No default value';
$_LANG['add_sign'] = 'New message signature';
$_LANG['new_default_sign'] = 'The current default signature';
$_LANG['default_sign'] = 'The original signature';
$_LANG['add'] = 'Add to';
$_LANG['edited'] = 'Amended as';
$_LANG['edit'] = 'edit';
$_LANG['set_default_sign'] = 'Set the default signature';

?>


text: Leverage system leds (eg keyboard backlights) to notify you when stuff happens


text:
<?php

session_start();
require_once("../resources/config.php");
require_once LIBRARY_PATH . "/user/user.php";

$request_legal = false;
$data = array();
$response = array();
$errors = array();

$user = new User();

$post_data = json_decode(file_get_contents('php://input'), true);

if (!empty($post_data["username"])) {
    if (strlen($post_data["username"]) < 3 || strlen($post_data["username"]) > 32) {
        $errors[] = "De gebruikersnaam moet tussend de 2 en 33 tekens lang zijn";
    } else {
        if ($user->user_exists($post_data["username"]) === false) {
            if($user->login($post_data["username"], $_SERVER['REMOTE_ADDR'])) {
                $request_legal = true;
                $data = array(
                    "username" => $user->username,
                    "user_id" => $user->user_id
                );
                $_SESSION["chat_user_id"] = $user->user_id;
            } else {
                $errors[] = "Er is een fout opgetreden bij het aanmaken van de gebruiker";
            }
        } else {
            $errors[] = "De gebruiker bestaat al";
        }
    }
} else {
    $errors[] = "Vul een gebruikersnaam in";
}

if ($request_legal === true) {
    $response = array(
        "request_legal" => $request_legal
    );
} else {
    $response = array(
        "request_legal" => $request_legal,
        "errors" => $errors
    );
}

echo json_encode($response);


text:
ic-sortable
============

Ember component mixin for creating sortable drag and drop ui.

Demo
----

https://instructure.github.io/ic-sortable

Installation
------------

`bower install ic-sortable`

`npm install ic-sortable`

... or download one of the distrobutions in `dist` and include however
you want.

Module Support
--------------

- AMD

  `define(['ic-sortable'], function(Sortable) {});`

- CJS

  `var Sortable = require('ic-sortable')`

- Globals

  `var Sortable = ic.Sortable.default`

Usage
-----

Don't use this, its not done.

Contributing
------------

```sh
bower install
npm install
npm test
```

License and Copyright
---------------------

MIT Style license

(c) 2014 Instructure, Inc.


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

<title>Uses of Package com.eyetechds.quicklink</title>
<meta name="date" content="2014-06-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
com.eyetechds.quicklink

Classes in com.eyetechds.quicklink used by com.eyetechds.quicklink

Class and Description

QLBoolean

The Class QLBoolean contains a boolean type with support functions for use with QuickLink.

QLCalibration

A QLCalibration object is a container for holding calibration data used by
 QLDevice objects.

QLCalibrationScore

The class QLCalibrationScore contains values that identify the quality of a calibration at a target.

QLCalibrationTarget

The class QLCalibrationTarget contains data that identifies a target and its location.

QLCalibrationTargetStatus

The Class QLCalibrationTargetStatus contains status information for a calibration target.

QLCalibrationType

The Class QLCalibrationType defines the available calibration types.

QLColor

The Class QLColor defines a Color object for use in QuickLink.

QLDevice

A QLDevice object contains all the methods needed for communicating with and getting gaze
 data from a device

QLDeviceEyesToUse

The Class QLDeviceEyesToUse defines which eyes will be tracked by the device.

QLDeviceGainMode

The Class QLDeviceGainMode defines the gain mode the device will use.

QLDeviceGazePointFilterMode

The Class QLDeviceGazePointFilterMode defines which gaze point filter mode the device will use.

QLDeviceInfo

The class QLDeviceInfo defines device specific information.

QLDeviceMessage

The Class QLDeviceMessage defines the messages values that are received by the message handler
 that is passed to the method QLDevice.enumerate(Context, Handler, boolean).

QLDeviceStatus

The Class QLDeviceStatus defines the possible status values of the device.

QLDouble

The Class QLDouble contains a double type with support functions for use with QuickLink.

QLError

The Class QLError defines the error codes used by QuickLink

QLEyeData

The class QLEyeData contains eye specific information;

QLEyeType

The Class QLEyeType defines values indicating which eye to use:

QLFloat

The Class QLFloat contains a float type with support functions for use with QuickLink.

QLFrameData

The QLFrameData class defines the complete data that is available for each frame.

QLImageData

The class QLImageData contains information/data about the image.

QLIndicatorMode

The Class QLIndicatorMode defines the different modes that the indicator lights can be.

QLIndicatorType

The Class QLIndicatorType defines the different indicator lights on the device.

QLInt

The Class QLInt contains an int type with support functions for use with QuickLink.

QLLong

The Class QLLong contains a long type with support functions for use with QuickLink.

QLRectInt

The class QLRect contains members that define a rectangle.

QLSettings

A QLSettings object is a container for holding settings used by QLDevice objects.

QLString

The Class QLString contains a String type with support functions for use with QuickLink.

QLWeightedGazePoint

The averaged gaze point.

QLXYPairDouble

An x-y pair of type double.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

namespace Kassko\DataMapper\ContainerAdapter;

use Kassko\ClassResolver\ContainerInterface;
use LogicException;

/**
 * @author kko
 */
class VariableAdapterContainer implements ContainerInterface
{
    private $container;
    private $getMethodName;
    private $hasMethodName;

    public function __construct($container, $getMethodName, $hasMethodName)
    {
        if (! is_object($container)) {
            throw new LogicException(sprintf('Container should be an object. Type "%s" given.', gettype($container)));
        }

        $this->container = $container;
        $this->getMethodName = $getMethodName;
        $this->hasMethodName = $hasMethodName;
    }

    /**
     * {@inheritdoc}
     */
    public function get($name)
    {
        return $this->container->{$this->getMethodName}($name);
    }

    /**
     * {@inheritdoc}
     */
    public function has($name)
    {
        return $this->container->{$this->hasMethodName}($name);
    }
}


text:
ofxBumblebeeGrabber
=====================================

Introduction
------------
C++ openFrameworks addon to capture stereo images from a PointGrey bumblebee using PTGrey SDKs.

Licence
-------
The code in this repository is available under the [MIT License](https://secure.wikimedia.org/wikipedia/en/wiki/Mit_license).
Copyright (c) 2008-2012 Memo Akten, [www.memo.tv](http://www.memo.tv)
The Mega Super Awesome Visuals Company

Installation
------------
Copy to your openFrameworks/addons folder.
install PTGrey SDKs (FlyCapture and Triclops)

Dependencies
------------

Compatibility
------------

Known issues
------------

Version history
------------


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

<TITLE>
PluginTypeCategoriesOrder
</TITLE>

<META NAME="date" CONTENT="2012-11-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT

org.pentaho.di.core.plugins

Annotation Type PluginTypeCategoriesOrder

@Retention(value=RUNTIME)
@Target(value=TYPE)
public @interface PluginTypeCategoriesOrder

This annotation when applied to a PluginTypeInterface instance describes an ordered list of
 categories. The categories are internationalized when applied using the Messages located in
 the package where i18nPackageClass is located.

Author:

nbaker

Required Element Summary

 Class<?>
i18nPackageClass

Optional Element Summary

 String[]
getNaturalCategoriesOrder

Element Detail

i18nPackageClass

public abstract Class<?> i18nPackageClass

getNaturalCategoriesOrder

public abstract String[] getNaturalCategoriesOrder

Default:
""

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT


text:
package de.binarytree.plugins.qualitygates.steps.manualcheck;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;

import org.junit.Before;
import org.junit.Test;

import de.binarytree.plugins.qualitygates.result.GateStepReport;
import de.binarytree.plugins.qualitygates.steps.manualcheck.ManualCheck.DescriptorImpl;

public class ManualCheckTest {
    class MockManualCheck extends ManualCheck {
        public MockManualCheck(String usernameIfUserUnknown) {
            super(usernameIfUserUnknown);
        }

        public MockManualCheck(String hash, String usernameIfUserUnkown) {
            this(usernameIfUserUnkown);
            this.setHash(hash);
        }

        @Override
        public DescriptorImpl getDescriptor() {
            return new ManualCheck.DescriptorImpl();
        }
    }

    private ManualCheck check;

    private AbstractBuild<?, ?> build;

    private BuildListener listener;

    private Launcher launcher;

    private String unknownUser = "Unknown User";

    @Before
    public void setUp() throws Exception {
        check = new MockManualCheck(unknownUser);
        build = mock(AbstractBuild.class);
        listener = mock(BuildListener.class);
        launcher = mock(Launcher.class);
    }

    @Test
    public void testCheckResult() {
        GateStepReport report = new GateStepReport(check);
        check.doStep(build, launcher, listener, report);
        assertEquals(Result.NOT_BUILT, report.getResult());
        assertTrue(report.getReason().contains("href"));
        assertApprovalReset();
    }

    @Test
    public void testCheckBeingManuallyApprovedLeadsToSuccess() {
        GateStepReport report = new GateStepReport(check);
        check.approve();
        assertTrue(check.isApproved());
        assertFalse(check.isDisapproved());
        check.doStep(build, launcher, listener, report);
        assertEquals(Result.SUCCESS, report.getResult());
        assertTrue(report.getReason().contains("approved"));
        assertTrue(report.getReason().contains(unknownUser));
        assertApprovalReset();
    }

    private void assertApprovalReset() {
        assertFalse(check.isApproved());
        assertFalse(check.isDisapproved());
    }

    @Test
    public void testCheckBeingManuallyDisapprovedLeadsToFailure() {
        GateStepReport report = new GateStepReport(check);
        check.disapprove();
        assertFalse(check.isApproved());
        assertTrue(check.isDisapproved());
        check.doStep(build, launcher, listener, report);
        assertEquals(Result.FAILURE, report.getResult());
        assertTrue(report.getReason().contains("disapproved"));
        assertTrue(report.getReason().contains(unknownUser));
        assertApprovalReset();
    }

    @Test
    public void testEqualsTrue() {
        ManualCheck check1 = new MockManualCheck("hash", "user1");
        ManualCheck check2 = new MockManualCheck("hash", "user2");
        assertEquals(check1, check2);
        assertEquals(check1.hashCode(), check2.hashCode());

    }

    @Test
    public void testEqualsFalse() {
        ManualCheck check1 = new MockManualCheck("hash1", "user1");
        ManualCheck check2 = new MockManualCheck("hash2", "user1");
        assertNotEquals(check1, check2);
        assertNotEquals(check1.hashCode(), check2.hashCode());

    }

    @Test
    public void testDescriptionsContainManual() {
        DescriptorImpl descriptor = new ManualCheck.DescriptorImpl();
        assertTrue(descriptor.getDisplayName().toLowerCase().contains("manual"));
        assertTrue(check.getDescription().toLowerCase().contains("manual"));
    }

}


text:
package io.joynr.androidhelloworldprovider;

import androidx.lifecycle.LiveData;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import io.joynr.exceptions.JoynrRuntimeException;
import io.joynr.proxy.Future;
import joynr.exceptions.ApplicationException;
import joynr.types.ProviderQos;
import joynr.types.ProviderScope;

public class HelloWorldProviderModel {

    private static final Logger logger = LoggerFactory.getLogger(HelloWorldProviderModel.class);
    private HelloWorldProvider provider;

    private HelloWorldProviderApplication app;

    public void setApp(final HelloWorldProviderApplication app) {
        this.app = app;
    }

    public void init() {
        provider = new HelloWorldProvider();
        final ProviderQos providerQos = new ProviderQos();
        providerQos.setScope(ProviderScope.LOCAL);
        final Future<Void> future = app.getRuntime().registerProvider("domain", provider,
                providerQos);
        try {
            future.get();
        } catch (final JoynrRuntimeException | ApplicationException | InterruptedException e) {
            logger.error("runtime.registerProvider failed: ", e);
        }
    }

    public LiveData<List<String>> getData() {
        LiveData<List<String>> strings = provider.getData();
        provider.clearData();
        return strings;
    }
}


text:
#ifndef __SDMMC_18XX_43XX_H_
#define __SDMMC_18XX_43XX_H_

#include "sdmmc.h"

#ifdef __cplusplus
extern "C" {
#endif

/** @defgroup SDMMC_18XX_43XX CHIP: LPC18xx/43xx SD/MMC driver
 * @ingroup CHIP_18XX_43XX_Drivers
 * @{
 */

#define CMD_MASK_RESP       (0x3UL << 28)
#define CMD_RESP(r)         (((r) & 0x3) << 28)
#define CMD_RESP_R0         (0 << 28)
#define CMD_RESP_R1         (1 << 28)
#define CMD_RESP_R2         (2 << 28)
#define CMD_RESP_R3         (3 << 28)
#define CMD_BIT_AUTO_STOP   (1 << 24)
#define CMD_BIT_APP         (1 << 23)
#define CMD_BIT_INIT        (1 << 22)
#define CMD_BIT_BUSY        (1 << 21)
#define CMD_BIT_LS          (1 << 20)	/* Low speed, used during acquire */
#define CMD_BIT_DATA        (1 << 19)
#define CMD_BIT_WRITE       (1 << 18)
#define CMD_BIT_STREAM      (1 << 17)
#define CMD_MASK_CMD        (0xff)
#define CMD_SHIFT_CMD       (0)

#define CMD(c, r)        ( ((c) &  CMD_MASK_CMD) | CMD_RESP((r)) )

#define CMD_IDLE            CMD(MMC_GO_IDLE_STATE, 0) | CMD_BIT_LS    | CMD_BIT_INIT
#define CMD_SD_OP_COND      CMD(SD_APP_OP_COND, 1)      | CMD_BIT_LS | CMD_BIT_APP
#define CMD_SD_SEND_IF_COND CMD(SD_CMD8, 1)      | CMD_BIT_LS
#define CMD_MMC_OP_COND     CMD(MMC_SEND_OP_COND, 3)    | CMD_BIT_LS | CMD_BIT_INIT
#define CMD_ALL_SEND_CID    CMD(MMC_ALL_SEND_CID, 2)    | CMD_BIT_LS
#define CMD_MMC_SET_RCA     CMD(MMC_SET_RELATIVE_ADDR, 1) | CMD_BIT_LS
#define CMD_SD_SEND_RCA     CMD(SD_SEND_RELATIVE_ADDR, 1) | CMD_BIT_LS
#define CMD_SEND_CSD        CMD(MMC_SEND_CSD, 2) | CMD_BIT_LS
#define CMD_SEND_EXT_CSD    CMD(MMC_SEND_EXT_CSD, 1) | CMD_BIT_LS | CMD_BIT_DATA
#define CMD_DESELECT_CARD   CMD(MMC_SELECT_CARD, 0)
#define CMD_SELECT_CARD     CMD(MMC_SELECT_CARD, 1)
#define CMD_SET_BLOCKLEN    CMD(MMC_SET_BLOCKLEN, 1)
#define CMD_SEND_STATUS     CMD(MMC_SEND_STATUS, 1)
#define CMD_READ_SINGLE     CMD(MMC_READ_SINGLE_BLOCK, 1) | CMD_BIT_DATA
#define CMD_READ_MULTIPLE   CMD(MMC_READ_MULTIPLE_BLOCK, 1) | CMD_BIT_DATA | CMD_BIT_AUTO_STOP
#define CMD_SD_SET_WIDTH    CMD(SD_APP_SET_BUS_WIDTH, 1) | CMD_BIT_APP
#define CMD_STOP            CMD(MMC_STOP_TRANSMISSION, 1) | CMD_BIT_BUSY
#define CMD_WRITE_SINGLE    CMD(MMC_WRITE_BLOCK, 1) | CMD_BIT_DATA | CMD_BIT_WRITE
#define CMD_WRITE_MULTIPLE  CMD(MMC_WRITE_MULTIPLE_BLOCK, 1) | CMD_BIT_DATA | CMD_BIT_WRITE | CMD_BIT_AUTO_STOP

/* Card specific setup data */
typedef struct _mci_card_struct {
	sdif_device sdif_dev;
	SDMMC_CARD_T card_info;
} mci_card_struct;

/**
 * @brief	Get card's current state (idle, transfer, program, etc.)
 * @param	pSDMMC	: SDMMC peripheral selected
 * @return	Current SD card transfer state
 */
int32_t Chip_SDMMC_GetState(LPC_SDMMC_T *pSDMMC);

/**
 * @brief	Function to enumerate the SD/MMC/SDHC/MMC+ cards
 * @param	pSDMMC		: SDMMC peripheral selected
 * @param	pcardinfo	: Pointer to pre-allocated card info structure
 * @return	1 if a card is acquired, otherwise 0
 */
uint32_t Chip_SDMMC_Acquire(LPC_SDMMC_T *pSDMMC, mci_card_struct *pcardinfo);

/**
 * @brief	Get the device size of SD/MMC card (after enumeration)
 * @param	pSDMMC	: SDMMC peripheral selected
 * @return	Card size in number of bytes (capacity)
 */
uint64_t Chip_SDMMC_GetDeviceSize(LPC_SDMMC_T *pSDMMC);

/**
 * @brief	Get the number of device blocks of SD/MMC card (after enumeration)
 * Since Chip_SDMMC_GetDeviceSize is limited to 32 bits cards with greater than
 * 2 GBytes of data will not be correct, in such cases users can use this function
 * to get the size of the card in blocks.
 * @param	pSDMMC	: SDMMC peripheral selected
 * @return	Number of 512 bytes blocks in the card
 */
int32_t Chip_SDMMC_GetDeviceBlocks(LPC_SDMMC_T *pSDMMC);

/**
 * @brief	Performs the read of data from the SD/MMC card
 * @param	pSDMMC		: SDMMC peripheral selected
 * @param	buffer		: Pointer to data buffer to copy to
 * @param	start_block	: Start block number
 * @param	num_blocks	: Number of block to read
 * @return	Bytes read, or 0 on error
 */
int32_t Chip_SDMMC_ReadBlocks(LPC_SDMMC_T *pSDMMC, void *buffer, int32_t start_block, int32_t num_blocks);

/**
 * @brief	Performs write of data to the SD/MMC card
 * @param	pSDMMC		: SDMMC peripheral selected
 * @param	buffer		: Pointer to data buffer to copy to
 * @param	start_block	: Start block number
 * @param	num_blocks	: Number of block to write
 * @return	Number of bytes actually written, or 0 on error
 */
int32_t Chip_SDMMC_WriteBlocks(LPC_SDMMC_T *pSDMMC, void *buffer, int32_t start_block, int32_t num_blocks);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* __SDMMC_18XX_43XX_H_ */


text:
package com.github.programmerr47.vkgroups.adapter.item.subitems;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.github.programmerr47.vkgroups.R;
import com.vk.sdk.api.model.VKApiAudio;

import static com.github.programmerr47.vkgroups.utils.DurationFormatter.formatDuration;

/**
 * @author Michael Spitsin
 * @since 05.02.2016
 */
public class AudioAttachmentItem extends AbstractAttachmentItem {

    private VKApiAudio apiAudio;

    public AudioAttachmentItem(VKApiAudio apiAudio) {
        this.apiAudio = apiAudio;
    }

    @Override
    protected int getIconId() {
        return R.drawable.ic_music_note_white_36dp;
    }

    @NonNull
    @Override
    protected String getTitle() {
        return apiAudio.artist;
    }

    @Nullable
    @Override
    protected String getSubtitle() {
        return apiAudio.title;
    }

    @Nullable
    @Override
    protected String getOptionalInfo() {
        return formatDuration(apiAudio.duration);
    }
}


text:
@interface PhotosViewController () <UICollectionViewDelegateFlowLayout, PhotosHorizontalScrollingViewControllerDelegate>

@property (nonatomic, strong) PhotoBoxCell *selectedCell;
@property (nonatomic, assign) CGRect selectedItemRect;
@property (nonatomic, strong) NSMutableDictionary *locationDictionary;
@property (nonatomic, strong) NSMutableDictionary *placemarkDictionary;
@end

@implementation PhotosViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.numberOfColumns = 3;
    [self setPhotosCount:0 max:0];

    [self.navigationController.interactivePopGestureRecognizer setDelegate:nil];
}

- (CollectionViewHeaderCellConfigureBlock)headerCellConfigureBlock {
    void (^configureCell)(PhotosSectionHeaderView*, id,NSIndexPath*) = ^(PhotosSectionHeaderView* cell, id item, NSIndexPath *indexPath) {
        [cell setTitleLabelText:[item localizedDate]];
        if ([self.placemarkDictionary objectForKey:@(indexPath.section)]) {
            [cell setLocation:[self.placemarkDictionary objectForKey:@(indexPath.section)]];
        } else {
            [cell setLocation:nil];
        }
    };
    return configureCell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)cellIdentifier {
    return @"photoCell";
}

- (NSString *)groupKey {
    return NSStringFromSelector(@selector(dateTakenString));
}

- (NSString *)sectionHeaderIdentifier {
    return @"photoSection";
}

- (ResourceType)resourceType {
    return PhotoResource;
}

- (Class)resourceClass {
    return [Photo class];
}

- (NSString *)resourceId {
    return self.item.itemId;
}

- (NSString *)relationshipKeyPathWithItem {
    return @"albums";
}

- (void)didFetchItems {
    int count = [self.dataSource numberOfItems];
    [self setPhotosCount:count max:self.totalItems];
    [self getLocationForEachSection];
}

#pragma mark - Setters

- (void)setPhotosCount:(int)count max:(int)max{
    NSString *title = NSLocalizedString(@"Photos", nil);
    Album *album = (Album *)self.item;
    if (album) {
        title = album.name;
    }
    if (count == 0) {
        self.title = title;
    } else {
        [self setTitle:title subtitle:[NSString stringWithFormat:NSLocalizedString(@"%1$d of %2$d", nil), count, max]];
    }
}

- (void)setSelectedItemRectAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
    self.selectedItemRect = attributes.frame;
}

#pragma mark - Header Things

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(CGRectGetWidth(self.collectionView.frame), 44);
}

#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"pushPhoto"]) {
        CLS_LOG(@"Showing full screen photo");
        PhotosHorizontalScrollingViewController *destination = (PhotosHorizontalScrollingViewController *)segue.destinationViewController;
        PhotoBoxCell *cell = (PhotoBoxCell *)sender;
        [destination setItem:self.item];
        [destination setFirstShownPhoto:cell.item];
        [destination setFirstShownPhotoIndex:[self.dataSource positionOfItem:cell.item]];
        [destination setDelegate:self];

        self.selectedCell = cell;
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        [self setSelectedItemRectAtIndexPath:indexPath];
    }
}

#pragma mark - CustomAnimationTransitionFromViewControllerDelegate

- (UIImage *)imageToAnimate {
    return self.selectedCell.cellImageView.image;
}

- (CGRect)startRectInContainerView:(UIView *)containerView {
    return [self.selectedCell convertFrameRectToView:containerView];
}

- (CGRect)endRectInContainerView:(UIView *)containerView {
    CGRect originalPosition = CGRectOffset(self.selectedItemRect, 0, self.collectionView.contentInset.top);
    CGFloat adjustment = self.collectionView.contentOffset.y + self.collectionView.contentInset.top;
    return CGRectOffset(originalPosition, 0, -adjustment);
}

- (UIView *)viewToAnimate {
    return nil;
}

#pragma mark - PhotosHorizontalScrollingViewControllerDelegate

- (void)photosHorizontalScrollingViewController:(PhotosHorizontalScrollingViewController *)viewController didChangePage:(NSInteger)page item:(Photo *)item {
    CLS_LOG(@"Change page %d of %d", page, [self.dataSource numberOfItems]);
    NSIndexPath *indexPath = [self.dataSource indexPathOfItem:item];
    if (indexPath) {
        CLS_LOG(@"Index path target section %d row %d", indexPath.section, indexPath.item);
        CLS_LOG(@"Current number of sections %d. Number of items in section = %d", [self.collectionView numberOfSections], [self.collectionView numberOfItemsInSection:indexPath.section]);
        if (indexPath.section < [self.collectionView numberOfSections]) {
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];

            [self setSelectedItemRectAtIndexPath:indexPath];
        }
    }

}

- (UIView *)snapshotView {
    return [self.view snapshotViewAfterScreenUpdates:YES];
}

- (CGRect)selectedItemRectInSnapshot {
    return [self endRectInContainerView:nil];
}

- (void)photosHorizontalWillClose {
    [self setNavigationBarHidden:NO animated:YES];
}

#pragma mark - Location

- (void)getLocationForEachSection {
    if (!self.locationDictionary) {
        self.locationDictionary = [NSMutableDictionary dictionary];
    }
    int i = 0;
    for (id<NSFetchedResultsSectionInfo> section in self.dataSource.fetchedResultsController.sections) {
        for (NSManagedObject *photo in section.objects) {
            NSNumber *latitude = [photo valueForKey:@"latitude"];
            NSNumber *longitude = [photo valueForKey:@"longitude"];
            if (latitude && ![latitude isKindOfClass:[NSNull class]] && longitude && ![longitude isKindOfClass:[NSNull class]]) {
                CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longitude doubleValue]];
                [self.locationDictionary setObject:location forKey:@(i)];
                break;
            }
        }
        i++;
    }

    for (NSNumber *section in self.locationDictionary.allKeys) {
        CLLocation *location = [self.locationDictionary objectForKey:section];
        [[LocationManager sharedManager] nameForLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            if (!error && placemarks.count > 0) {
                [self updateSectionHeader:[section integerValue] placemark:placemarks[0]];
            }
        }];
    }
}

- (void)updateSectionHeader:(NSInteger)section placemark:(CLPlacemark *)placemark {
    if (!self.placemarkDictionary) {
        self.placemarkDictionary = [NSMutableDictionary dictionary];
    }
    if (placemark) {
        [self.placemarkDictionary setObject:placemark forKey:@(section)];
        [[NSNotificationCenter defaultCenter] postNotificationName:PhotoBoxLocationPlacemarkDidFetchNotification object:@{@"placemark": placemark, @"section":@(section)}];
    }
}

@end