text:
#ifdef INTEL_MKL

#define EIGEN_USE_THREADS

#include "dnnl.hpp"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/type_traits.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/mkl_graph_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/mkl_util.h"
#ifdef DNNL_AARCH64_USE_ACL
#include "tensorflow/core/platform/mutex.h"
#endif

using dnnl::primitive_attr;
using dnnl::prop_kind;
using dnnl::reorder;
using dnnl::stream;

namespace {
enum {
  QUANTIZE_MODE_MIN_COMBINED,
  QUANTIZE_MODE_MIN_FIRST,
  QUANTIZE_MODE_SCALED,
};
enum {
  // Round half away from zero: if the fraction of y is exactly 0.5, then
  // round(y) = y + 0.5 if y > 0
  // round(y) = y - 0.5 if y < 0
  // E.g., -5.5 gets rounded to -6, -5.4 goes to -5,
  // 5.4 goes to 5, and 5.5 goes to 6.
  ROUND_HALF_AWAY_FROM_ZERO,
  // Round half to even: if the fraction of y is exactly 0.5, then round(y) is
  // the nearest even integer to y.
  // E.g., 23.5 gets rounded to 24, 24.5 gets rounded to 24, while -23.5 becomes
  // -24, and -24.5 gets rounded to 24.
  ROUND_HALF_TO_EVEN,
};
}  // namespace

namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;

struct MklReorderWithScaleFwdParams {
  memory::dims src_dims;
  memory::desc src_md;
  memory::desc dst_md;
  string dtypes = string("");
  struct PostOpParam {
    string name;
    std::vector<float> param;
  };
  PostOpParam post_op_params;

  MklReorderWithScaleFwdParams(memory::dims src_dims, memory::desc src_md,
                               memory::desc dst_md)
      : src_dims(src_dims), src_md(src_md), dst_md(dst_md) {}
};

class MklReorderWithScalePrimitive : public MklPrimitive {
 public:
  explicit MklReorderWithScalePrimitive(
      const MklReorderWithScaleFwdParams& fwdParams)
      : MklPrimitive(engine(engine::kind::cpu, 0)) {
    // Create reorder primitive
    Setup(fwdParams);
  }

  ~MklReorderWithScalePrimitive() {}

  std::shared_ptr<primitive> GetPrimitive() { return context_.reorder_prim; }

  void Execute(void* src_data, void* dst_data,
               std::shared_ptr<stream> reorder_stream) {
#ifdef DNNL_AARCH64_USE_ACL
    mutex_lock lock(primitive_execution_mu_);
#endif
#ifndef ENABLE_ONEDNN_OPENMP
    context_.src_mem->set_data_handle(src_data, *reorder_stream);
    context_.dst_mem->set_data_handle(dst_data, *reorder_stream);
#else
    context_.src_mem->set_data_handle(src_data);
    context_.dst_mem->set_data_handle(dst_data);
#endif  // !ENABLE_ONEDNN_OPENMP
    context_.reorder_prim->execute(*reorder_stream, context_.prim_args);
    // After execution, set data handle back.
    context_.src_mem->set_data_handle(DummyData);
    context_.dst_mem->set_data_handle(DummyData);
  }

 private:
  // Primitive reuse context for reorder
  struct ReorderContext {
    // MKL-DNN memory
    std::shared_ptr<dnnl::memory> src_mem;
    std::shared_ptr<dnnl::memory> dst_mem;

    // Reorder primitive descriptor and primitive
    std::shared_ptr<reorder::primitive_desc> reorder_pd;
    std::shared_ptr<primitive> reorder_prim;

    // Stream and primitive vector
    std::shared_ptr<dnnl::stream> reorder_stream;

    std::unordered_map<int, dnnl::memory> prim_args;

    ReorderContext()
        : src_mem(nullptr),
          dst_mem(nullptr),
          reorder_pd(nullptr),
          reorder_prim(nullptr) {}
  } context_;

  // Reorder primitive setup
  void Setup(const MklReorderWithScaleFwdParams& fwdParams) {
    // Create memory descriptors for reorder data with specified format
    context_.src_mem.reset(
        new memory(fwdParams.src_md, cpu_engine_, DummyData));
    context_.dst_mem.reset(
        new memory(fwdParams.dst_md, cpu_engine_, DummyData));

    // Check if there is any fusion as post-ops
    auto const& post_op_params = fwdParams.post_op_params;
    dnnl::primitive_attr post_ops_attr;

    DCHECK(post_op_params.name == "scale");
    DCHECK_EQ(post_op_params.param.size(), 1);
    std::vector<float> scales;
    scales.push_back(post_op_params.param[0]);
    post_ops_attr.set_output_scales(0, scales);

    context_.reorder_pd.reset(
        new ReorderPd(cpu_engine_, context_.src_mem->get_desc(), cpu_engine_,
                      context_.dst_mem->get_desc(), post_ops_attr));

    // Create reorder primitive
    context_.reorder_prim.reset(new reorder(*context_.reorder_pd));
    context_.prim_args.insert({DNNL_ARG_FROM, *context_.src_mem});
    context_.prim_args.insert({DNNL_ARG_TO, *context_.dst_mem});
  }

#ifdef DNNL_AARCH64_USE_ACL
  mutex primitive_execution_mu_;
#endif
};

template <typename T>
class MklReorderWithScalePrimitiveFactory : public MklPrimitiveFactory<T> {
 public:
  static MklReorderWithScalePrimitive* Get(
      const memory* from, const memory* to,
      const MklReorderWithScaleFwdParams& fwdParams) {
    // Try to find a suitable primitive from the cached pool
    auto reorderPrim = static_cast<MklReorderWithScalePrimitive*>(
        MklReorderWithScalePrimitiveFactory<T>::GetInstance().GetReorder(
            from, to, fwdParams));
    if (reorderPrim == nullptr) {
      reorderPrim = new MklReorderWithScalePrimitive(fwdParams);
      MklReorderWithScalePrimitiveFactory<T>::GetInstance().SetReorder(
          from, to, reorderPrim, fwdParams);
    }
    return reorderPrim;
  }

  static MklReorderWithScalePrimitiveFactory& GetInstance() {
    static MklReorderWithScalePrimitiveFactory instance_;
    return instance_;
  }

 private:
  MklReorderWithScalePrimitiveFactory() {}
  ~MklReorderWithScalePrimitiveFactory() {}

  static string CreateKey(const memory* from, const memory* to,
                          const MklReorderWithScaleFwdParams& fwdParams) {
    FactoryKeyCreator key_creator;
    key_creator.AddAsKey(MklReorderPrimitiveFactory<T>::CreateKey(from, to));
    // Generate key for post-op scale
    if (fwdParams.post_op_params.name == "scale") {
      DCHECK_EQ(fwdParams.post_op_params.param.size(), 1);
      key_creator.AddAsKey(fwdParams.post_op_params.name);
      key_creator.AddAsKey(fwdParams.post_op_params.param[0]);
    } else {
      return string("not_a_key");
    }

    return key_creator.GetKey();
  }

  MklPrimitive* GetReorder(const memory* from, const memory* to,
                           const MklReorderWithScaleFwdParams& fwdParams) {
    string key = CreateKey(from, to, fwdParams);
    return this->GetOp(key);
  }

  void SetReorder(const memory* from, const memory* to, MklPrimitive* op,
                  const MklReorderWithScaleFwdParams& fwdParams) {
    string key = CreateKey(from, to, fwdParams);
    this->SetOp(key, op);
  }
};

// Quantizes a tensor from float to T, with user-specified min_range and
// max_range.
template <typename Device, typename T, bool native_format = false>
class MklQuantizeV2Op : public OpKernel {
 public:
  explicit MklQuantizeV2Op(OpKernelConstruction* ctx) : OpKernel(ctx) {
    string mode_string;
    OP_REQUIRES_OK(ctx, ctx->GetAttr("mode", &mode_string));
    OP_REQUIRES(ctx,
                (mode_string == "MIN_COMBINED" || mode_string == "MIN_FIRST" ||
                 mode_string == "SCALED"),
                errors::InvalidArgument("Mode string must be 'MIN_COMBINED',"
                                        " 'MIN_FIRST', or 'SCALED', is '" +
                                        mode_string + "'"));
    if (mode_string == "MIN_COMBINED") {
      mode_ = QUANTIZE_MODE_MIN_COMBINED;
    } else if (mode_string == "MIN_FIRST") {
      mode_ = QUANTIZE_MODE_MIN_FIRST;
    } else if (mode_string == "SCALED") {
      mode_ = QUANTIZE_MODE_SCALED;
    }

    string round_mode_string;
    OP_REQUIRES_OK(ctx, ctx->GetAttr("round_mode", &round_mode_string));
    OP_REQUIRES(ctx,
                (round_mode_string == "HALF_AWAY_FROM_ZERO" ||
                 round_mode_string == "HALF_TO_EVEN"),
                errors::InvalidArgument("Round mode string must be "
                                        "'HALF_AWAY_FROM_ZERO' or "
                                        "'HALF_TO_EVEN', is '" +
                                        round_mode_string + "'"));
    if (round_mode_string == "HALF_AWAY_FROM_ZERO") {
      round_mode_ = ROUND_HALF_AWAY_FROM_ZERO;
    } else if (round_mode_string == "HALF_TO_EVEN") {
      OP_REQUIRES(ctx, mode_string == "SCALED",
                  errors::InvalidArgument("Round mode 'HALF_TO_EVEN' "
                                          "only supported for mode 'SCALED', "
                                          "but mode is '" +
                                          mode_string + "'."));
      round_mode_ = ROUND_HALF_TO_EVEN;
    }
    OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_));
    OP_REQUIRES_OK(
        ctx, ctx->GetAttr("ensure_minimum_range", &ensure_minimum_range_));
  }

  void ComputeScalar(OpKernelContext* ctx, float min_range, float max_range) {
    // TODO(intel-tf): Scalar support has to be added for SCALE mode
    OP_REQUIRES(ctx, (mode_ == QUANTIZE_MODE_MIN_FIRST),
                errors::InvalidArgument(
                    "Scalar calculation in MKL is supported only for"
                    "MIN_FIRST mode for now."));

    auto cpu_engine = engine(engine::kind::cpu, 0);
    const unsigned int src_idx = 0;
    const Tensor& src_tensor = MklGetInput(ctx, src_idx);

    MklDnnShape output_mkl_shape;
    output_mkl_shape.SetMklTensor(false);

    Tensor* output_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 0, &output_tensor, src_tensor.shape(),
                              output_mkl_shape, native_format);
    TensorShape min_tf_shape = {};
    MklDnnShape min_mkl_shape;
    min_mkl_shape.SetMklTensor(false);
    Tensor* output_min_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 1, &output_min_tensor, min_tf_shape,
                              min_mkl_shape, native_format);
    TensorShape max_tf_shape = {};
    MklDnnShape max_mkl_shape;
    max_mkl_shape.SetMklTensor(false);
    Tensor* output_max_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 2, &output_max_tensor, max_tf_shape,
                              max_mkl_shape, native_format);

    // Estimate scale for quantization
    float scale_factor = 0;
    const int number_of_bits = sizeof(T) * 8;
    const int64 number_of_steps = static_cast<int64_t>(1) << number_of_bits;
    scale_factor = (number_of_steps - 1.0) / (max_range - min_range);

    float* src_data = const_cast<float*>(src_tensor.flat<float>().data());
    T* out_data = output_tensor->flat<T>().data();

    out_data[0] = (src_data[0] - min_range) * scale_factor;
    output_min_tensor->flat<float>()(0) = min_range;
    output_max_tensor->flat<float>()(0) = max_range;

    return;
  }

  void Compute(OpKernelContext* ctx) override {
    const unsigned int src_idx = 0;
    const Tensor& input = ctx->input(src_idx);
    const float input_min_range = ctx->input(1).flat<float>()(0);
    const float input_max_range = ctx->input(2).flat<float>()(0);
    float min_range = std::min(0.0f, input_min_range);
    float max_range;
    OP_REQUIRES(ctx, (input_max_range >= input_min_range),
                errors::InvalidArgument(
                    "input_max_range must be larger than input_min_range."));

    // When the minimum and maximum ranges are too close together, nudge them
    // apart by a small value so that they are slightly different. This helps
    // us avoid creating ill-formed buffers where all quantized values map to
    // the same float number. These kinds of buffers cause problems for
    // downstream ops when they need to do calculations on them.
    // We pick the value by making sure that zero is not more than 100x the
    // overall range from the maximum, so that the value can be easily
    // represented when we promote the quantized value to a higher
    // intermediate bit depth, since that's a common requirement.
    const float epsilon = std::max(1.0f, std::max(fabsf(input_min_range),
                                                  fabsf(input_max_range))) *
                          ensure_minimum_range_;
    max_range = std::max(input_max_range, min_range + epsilon);
    // Clamping the max_range to zero since max_range can also be negative.
    max_range = std::max(0.0f, max_range);
    auto cpu_engine = engine(engine::kind::cpu, 0);
    const Tensor& src_tensor = MklGetInput(ctx, src_idx);
    MklDnnShape src_mkl_shape;
    GetMklShape(ctx, src_idx, &src_mkl_shape, native_format);
    auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape()
                                                    : src_tensor.shape();
    auto src_dims = src_mkl_shape.IsMklTensor()
                        ? src_mkl_shape.GetSizesAsMklDnnDims()
                        : TFShapeToMklDnnDims(src_tensor.shape());
    auto output_dims = src_dims;
    // Set the dst layout to be the best mkl layout based on dims and type.
    memory::format_tag dst_layout_type;
    switch (src_tf_shape.dims()) {
      case 0:
        ComputeScalar(ctx, min_range, max_range);
        return;
      case 1:
        dst_layout_type = memory::format_tag::x;
        break;
      case 2:
        dst_layout_type = memory::format_tag::nc;
        break;
      case 3:
        dst_layout_type = memory::format_tag::tnc;
        break;
      case 4:
        dst_layout_type = memory::format_tag::nhwc;
        break;
      case 5:
        dst_layout_type = memory::format_tag::ndhwc;
        break;
      default:
        OP_REQUIRES_OK(ctx,
                       errors::Aborted("Input dims must be <= 5 and >= 1"));
        return;
    }
    // Create reorder memory for src, dst: both are defined in mkl_util.h,
    // they are wrapper
    MklDnnData<float> src(&cpu_engine);
    MklDnnData<T> dst(&cpu_engine);
    auto src_md =
        src_mkl_shape.IsMklTensor()
            ? src_mkl_shape.GetMklLayout()
            : memory::desc(src_dims, MklDnnType<float>(), dst_layout_type);

    // If the mode is min_first, input data has to be subtracted from
    // min_range, before being scaled
    auto flat_input = input.flat<float>().data();
    Tensor min_shifted_input_tensor;
    OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_FLOAT, input.shape(),
                                           &min_shifted_input_tensor));
    if (mode_ == QUANTIZE_MODE_MIN_FIRST) {
      auto minfirst_input = min_shifted_input_tensor.flat<float>().data();
      const Eigen::TensorOpCost cost(
          sizeof(float), /*load bytes*/
          sizeof(float), /*saved bytes*/
          Eigen::TensorOpCost::AddCost<float>() /*sub cost*/);

      const CPUDevice& d = ctx->eigen_device<CPUDevice>();
      auto ParallelSub = [&](int64 start, int64 end) {
        for (int i = start; i < end; ++i) {
          minfirst_input[i] = flat_input[i] - min_range;
        }
      };
      d.parallelFor(input.NumElements(), cost, ParallelSub);

      src.SetUsrMem(src_md, &min_shifted_input_tensor);
    } else {
      src.SetUsrMem(src_md, &src_tensor);
    }

    memory::desc dst_md =
        memory::desc(src_dims, MklDnnType<T>(), dst_layout_type);

    // Standard shape assignments for layout pass
    MklDnnShape output_mkl_shape;
    TensorShape output_tf_shape;
    if (src_mkl_shape.IsMklTensor()) {
      output_mkl_shape.SetMklTensor(true);
      output_mkl_shape.SetMklLayout(&dst_md);
      output_mkl_shape.SetElemType(MklDnnType<T>());
      output_mkl_shape.SetTfLayout(src_mkl_shape.GetDimension(),
                                   src_mkl_shape.GetSizesAsMklDnnDims(),
                                   src_mkl_shape.GetTfDataFormat());
      output_tf_shape.AddDim(dst_md.get_size() / sizeof(T));
    } else {
      output_mkl_shape.SetMklTensor(false);
      output_tf_shape = MklDnnDimsToTFShape(output_dims);
    }

    Tensor* output_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 0, &output_tensor, output_tf_shape,
                              output_mkl_shape, native_format);
    dst.SetUsrMem(dst_md, output_tensor);

    TensorShape min_tf_shape = {};
    MklDnnShape min_mkl_shape;
    min_mkl_shape.SetMklTensor(false);
    Tensor* output_min_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 1, &output_min_tensor, min_tf_shape,
                              min_mkl_shape, native_format);
    TensorShape max_tf_shape = {};
    MklDnnShape max_mkl_shape;
    max_mkl_shape.SetMklTensor(false);
    Tensor* output_max_tensor = nullptr;
    AllocateOutputSetMklShape(ctx, 2, &output_max_tensor, max_tf_shape,
                              max_mkl_shape, native_format);

    float scale_factor = 0;
    if (mode_ == QUANTIZE_MODE_SCALED) {
      // Estimating scales for quantization.
      const int num_bits = sizeof(T) * 8;
      const float max_abs = std::max(std::abs(min_range), std::abs(max_range));
      const bool is_signed = std::is_signed<T>::value;
      float target_range;
      if (is_signed) {
        max_range = max_abs;
        min_range = -max_abs;
        // If it is signed, we try to keep 0.0 being 0 and drop one bucket. For
        // example, if it is 8 bits, we have the range [-127, 127]. So for input
        // range of [-x, x], the scale should be 254/(2*x).
        target_range = static_cast<float>((uint64_t{1} << (num_bits - 1)) - 1);
      } else {
        max_range = max_abs;
        min_range = 0.0;
        // If it is unsigned and num_bits == 8, the range with 8 bits is [0,
        // 255].  If the input range is [0, x], then the scale is 255/x instead
        // of 254 as in the case above.
        target_range = static_cast<float>((uint64_t{1} << num_bits) - 1);
      }
      scale_factor = target_range / max_abs;
    } else if (mode_ == QUANTIZE_MODE_MIN_FIRST) {
      // Estimate scale for qunatization
      const int number_of_bits = sizeof(T) * 8;
      const int64 number_of_steps = static_cast<int64_t>(1) << number_of_bits;
      scale_factor = (number_of_steps - 1.0) / (max_range - min_range);
    }

    MklReorderWithScaleFwdParams fwdParams(src_dims, src_md, dst_md);
    fwdParams.dtypes.append(typeid(T).name());
    fwdParams.post_op_params.name = "scale";
    fwdParams.post_op_params.param.push_back(scale_factor);

    MklReorderWithScalePrimitive* reorder_prim =
        MklReorderWithScalePrimitiveFactory<T>::Get(src.GetUsrMem(),
                                                    dst.GetUsrMem(), fwdParams);
    std::shared_ptr<stream> cpu_stream;
    MklDnnThreadPool eigen_tp(ctx);
    cpu_stream.reset(CreateStream(&eigen_tp, reorder_prim->GetEngine()));
    reorder_prim->Execute(src.GetUsrMemDataHandle(), dst.GetUsrMemDataHandle(),
                          cpu_stream);

    output_min_tensor->flat<float>()(0) = min_range;
    output_max_tensor->flat<float>()(0) = max_range;
  }

 private:
  float ensure_minimum_range_;
  int mode_;
  int round_mode_;
  int axis_;
  bool narrow_range_;
};

REGISTER_KERNEL_BUILDER(Name("_MklQuantizeV2")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<quint8>("T")
                            .Label(mkl_op_registry::kMklQuantizedOpLabel),
                        MklQuantizeV2Op<CPUDevice, quint8, true>);
REGISTER_KERNEL_BUILDER(Name("_MklQuantizeV2")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<qint8>("T")
                            .Label(mkl_op_registry::kMklQuantizedOpLabel),
                        MklQuantizeV2Op<CPUDevice, qint8, true>);
}  // namespace tensorflow

#endif  // INTEL_MKL


text:
package org.holoeverywhere.widget;

import org.holoeverywhere.ArrayAdapter;
import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListAdapter;

public class AutoCompleteTextView extends EditText implements
        Filter.FilterListener {
    private class DropDownItemClickListener implements
            AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            performCompletion(v, position, id);
        }
    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            doAfterTextChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            doBeforeTextChanged();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }
    }

    private class PassThroughClickListener implements OnClickListener {
        private View.OnClickListener mWrapped;

        @Override
        public void onClick(View v) {
            onClickImpl();

            if (mWrapped != null) {
                mWrapped.onClick(v);
            }
        }
    }

    private class PopupDataSetObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            if (mAdapter != null) {
                post(new Runnable() {
                    @Override
                    public void run() {
                        final ListAdapter adapter = mAdapter;
                        if (adapter != null) {
                            updateDropDownForFilter(adapter.getCount());
                        }
                    }
                });
            }
        }
    }

    public interface Validator {
        CharSequence fixText(CharSequence invalidText);

        boolean isValid(CharSequence text);
    }

    static final int EXPAND_MAX = 3;
    static final String TAG = "AutoCompleteTextView";
    private ListAdapter mAdapter;
    private boolean mBlockCompletion;
    private int mDropDownAnchorId;
    private boolean mDropDownDismissedOnCompletion = true;
    private Filter mFilter;
    private int mHintResource;
    private CharSequence mHintText;
    private TextView mHintView;
    private AdapterView.OnItemClickListener mItemClickListener;
    private AdapterView.OnItemSelectedListener mItemSelectedListener;
    private int mLastKeyCode = KeyEvent.KEYCODE_UNKNOWN;
    private PopupDataSetObserver mObserver;
    private boolean mOpenBefore;

    private PassThroughClickListener mPassThroughClickListener;

    private ListPopupWindow mPopup;

    private boolean mPopupCanBeUpdated = true;

    private int mThreshold;

    private Validator mValidator = null;

    public AutoCompleteTextView(Context context) {
        this(context, null);
    }

    public AutoCompleteTextView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.autoCompleteTextViewStyle);
    }

    public AutoCompleteTextView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        mPopup = new ListPopupWindow(context, attrs,
                R.attr.autoCompleteTextViewStyle);
        mPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPopup.setPromptPosition(ListPopupWindow.POSITION_PROMPT_BELOW);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.AutoCompleteTextView, defStyle, 0);
        mThreshold = a
                .getInt(R.styleable.AutoCompleteTextView_android_completionThreshold,
                        2);
        mPopup.setListSelector(a
                .getDrawable(R.styleable.AutoCompleteTextView_android_dropDownSelector));
        mPopup.setVerticalOffset((int) a.getDimension(
                R.styleable.AutoCompleteTextView_dropDownVerticalOffset, 0.0f));
        mPopup.setHorizontalOffset((int) a
                .getDimension(
                        R.styleable.AutoCompleteTextView_dropDownHorizontalOffset,
                        0.0f));
        mDropDownAnchorId = a.getResourceId(
                R.styleable.AutoCompleteTextView_android_dropDownAnchor,
                View.NO_ID);
        mPopup.setWidth(a.getLayoutDimension(
                R.styleable.AutoCompleteTextView_android_dropDownWidth,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        mPopup.setHeight(a.getLayoutDimension(
                R.styleable.AutoCompleteTextView_android_dropDownHeight,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        mHintResource = a.getResourceId(
                R.styleable.AutoCompleteTextView_android_completionHintView,
                R.layout.simple_dropdown_hint);
        mPopup.setOnItemClickListener(new DropDownItemClickListener());
        setCompletionHint(a
                .getText(R.styleable.AutoCompleteTextView_android_completionHint));
        int inputType = getInputType();
        if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
            inputType |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
            setRawInputType(inputType);
        }
        CharSequence[] entries = null;
        if (a.hasValue(R.styleable.AutoCompleteTextView_android_entries)) {
            entries = a
                    .getTextArray(R.styleable.AutoCompleteTextView_android_entries);
        }
        a.recycle();
        setFocusable(true);
        addTextChangedListener(new MyWatcher());
        mPassThroughClickListener = new PassThroughClickListener();
        super.setOnClickListener(mPassThroughClickListener);
        if (entries != null) {
            onLoadEntries(entries);
        }
    }

    private void buildImeCompletions() {
        final ListAdapter adapter = mAdapter;
        if (adapter != null) {
            InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                final int count = Math.min(adapter.getCount(), 20);
                CompletionInfo[] completions = new CompletionInfo[count];
                int realCount = 0;
                for (int i = 0; i < count; i++) {
                    if (adapter.isEnabled(i)) {
                        Object item = adapter.getItem(i);
                        long id = adapter.getItemId(i);
                        completions[realCount] = new CompletionInfo(id,
                                realCount, convertSelectionToString(item));
                        realCount++;
                    }
                }
                if (realCount != count) {
                    CompletionInfo[] tmp = new CompletionInfo[realCount];
                    System.arraycopy(completions, 0, tmp, 0, realCount);
                    completions = tmp;
                }

                imm.displayCompletions(this, completions);
            }
        }
    }

    public void clearListSelection() {
        mPopup.clearListSelection();
    }

    protected CharSequence convertSelectionToString(Object selectedItem) {
        return mFilter.convertResultToString(selectedItem);
    }

    public void dismissDropDown() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.displayCompletions(this, null);
        }
        mPopup.dismiss();
        mPopupCanBeUpdated = false;
    }

    void doAfterTextChanged() {
        if (mBlockCompletion) {
            return;
        }
        if (mOpenBefore && !isPopupShowing()) {
            return;
        }
        if (enoughToFilter()) {
            if (mFilter != null) {
                mPopupCanBeUpdated = true;
                performFiltering(getText(), mLastKeyCode);
            }
        } else {
            if (!mPopup.isDropDownAlwaysVisible()) {
                dismissDropDown();
            }
            if (mFilter != null) {
                mFilter.filter(null);
            }
        }
    }

    void doBeforeTextChanged() {
        if (mBlockCompletion) {
            return;
        }
        mOpenBefore = isPopupShowing();
    }

    public boolean enoughToFilter() {
        return getText().length() >= mThreshold;
    }

    public void ensureImeVisible(boolean visible) {
        mPopup.setInputMethodMode(visible ? ListPopupWindow.INPUT_METHOD_NEEDED
                : ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
        if (mPopup.isDropDownAlwaysVisible() || mFilter != null
                && enoughToFilter()) {
            showDropDown();
        }
    }

    public ListAdapter getAdapter() {
        return mAdapter;
    }

    public CharSequence getCompletionHint() {
        return mHintText;
    }

    public int getDropDownAnchor() {
        return mDropDownAnchorId;
    }

    public int getDropDownAnimationStyle() {
        return mPopup.getAnimationStyle();
    }

    public Drawable getDropDownBackground() {
        return mPopup.getBackground();
    }

    public int getDropDownHeight() {
        return mPopup.getHeight();
    }

    public int getDropDownHorizontalOffset() {
        return mPopup.getHorizontalOffset();
    }

    public int getDropDownVerticalOffset() {
        return mPopup.getVerticalOffset();
    }

    public int getDropDownWidth() {
        return mPopup.getWidth();
    }

    protected Filter getFilter() {
        return mFilter;
    }

    public int getListSelection() {
        return mPopup.getSelectedItemPosition();
    }

    public AdapterView.OnItemClickListener getOnItemClickListener() {
        return mItemClickListener;
    }

    public AdapterView.OnItemSelectedListener getOnItemSelectedListener() {
        return mItemSelectedListener;
    }

    public int getThreshold() {
        return mThreshold;
    }

    public Validator getValidator() {
        return mValidator;
    }

    public boolean isDropDownAlwaysVisible() {
        return mPopup.isDropDownAlwaysVisible();
    }

    public boolean isDropDownDismissedOnCompletion() {
        return mDropDownDismissedOnCompletion;
    }

    public boolean isInputMethodNotNeeded() {
        return mPopup.getInputMethodMode() == ListPopupWindow.INPUT_METHOD_NOT_NEEDED;
    }

    public boolean isPerformingCompletion() {
        return mBlockCompletion;
    }

    public boolean isPopupShowing() {
        return mPopup.isShowing();
    }

    private void onClickImpl() {
        if (isPopupShowing()) {
            ensureImeVisible(true);
        }
    }

    @Override
    public void onCommitCompletion(CompletionInfo completion) {
        if (isPopupShowing()) {
            mPopup.performItemClick(completion.getPosition());
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        dismissDropDown();
        super.onDetachedFromWindow();
    }

    @Override
    protected void onDisplayHint(int hint) {
        super.onDisplayHint(hint);
        switch (hint) {
            case INVISIBLE:
                if (!mPopup.isDropDownAlwaysVisible()) {
                    dismissDropDown();
                }
                break;
        }
    }

    @Override
    public void onFilterComplete(int count) {
        updateDropDownForFilter(count);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (!focused) {
            performValidation();
        }
        if (!focused && !mPopup.isDropDownAlwaysVisible()) {
            dismissDropDown();
        }
    }

    @Override
    @SuppressLint("NewApi")
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mPopup.onKeyDown(keyCode, event)) {
            return true;
        }
        if (!isPopupShowing()) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (VERSION.SDK_INT < 11 || event.hasNoModifiers()) {
                        performValidation();
                    }
            }
        }
        if (isPopupShowing() && keyCode == KeyEvent.KEYCODE_TAB
                && (VERSION.SDK_INT < 11 || event.hasNoModifiers())) {
            return true;
        }
        mLastKeyCode = keyCode;
        boolean handled = super.onKeyDown(keyCode, event);
        mLastKeyCode = KeyEvent.KEYCODE_UNKNOWN;
        if (handled && isPopupShowing()) {
            clearListSelection();
        }
        return handled;
    }

    @Override
    @SuppressLint("NewApi")
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (VERSION.SDK_INT < 5) {
            return false;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()
                && !mPopup.isDropDownAlwaysVisible()) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                KeyEvent.DispatcherState state = getKeyDispatcherState();
                if (state != null) {
                    state.startTracking(event, this);
                }
                return true;
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                KeyEvent.DispatcherState state = getKeyDispatcherState();
                if (state != null) {
                    state.handleUpEvent(event);
                }
                if (event.isTracking() && !event.isCanceled()) {
                    dismissDropDown();
                    return true;
                }
            }
        }
        return super.onKeyPreIme(keyCode, event);
    }

    @Override
    @SuppressLint("NewApi")
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean consumed = mPopup.onKeyUp(keyCode, event);
        if (consumed) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_TAB:
                    if (VERSION.SDK_INT < 11 || event.hasNoModifiers()) {
                        performCompletion();
                    }
                    return true;
            }
        }
        if (isPopupShowing() && keyCode == KeyEvent.KEYCODE_TAB
                && (VERSION.SDK_INT < 11 || event.hasNoModifiers())) {
            performCompletion();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    protected void onLoadEntries(CharSequence[] entries) {
        setAdapter(new ArrayAdapter<CharSequence>(getContext(),
                R.layout.simple_dropdown_item_1line, entries));
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (!hasWindowFocus && !mPopup.isDropDownAlwaysVisible()) {
            dismissDropDown();
        }
    }

    public void performCompletion() {
        performCompletion(null, -1, -1);
    }

    private void performCompletion(View selectedView, int position, long id) {
        if (isPopupShowing()) {
            Object selectedItem;
            if (position < 0) {
                selectedItem = mPopup.getSelectedItem();
            } else {
                selectedItem = mAdapter.getItem(position);
            }
            if (selectedItem == null) {
                Log.w(AutoCompleteTextView.TAG,
                        "performCompletion: no selected item");
                return;
            }
            mBlockCompletion = true;
            replaceText(convertSelectionToString(selectedItem));
            mBlockCompletion = false;
            if (mItemClickListener != null) {
                final ListPopupWindow list = mPopup;
                if (selectedView == null || position < 0) {
                    selectedView = list.getSelectedView();
                    position = list.getSelectedItemPosition();
                    id = list.getSelectedItemId();
                }
                mItemClickListener.onItemClick(list.getListView(),
                        selectedView, position, id);
            }
        }
        if (mDropDownDismissedOnCompletion && !mPopup.isDropDownAlwaysVisible()) {
            dismissDropDown();
        }
    }

    protected void performFiltering(CharSequence text, int keyCode) {
        mFilter.filter(text, this);
    }

    public void performValidation() {
        if (mValidator == null) {
            return;
        }
        CharSequence text = getText();
        if (!TextUtils.isEmpty(text) && !mValidator.isValid(text)) {
            setText(mValidator.fixText(text));
        }
    }

    protected void replaceText(CharSequence text) {
        clearComposingText();
        setText(text);
        Editable spannable = getText();
        Selection.setSelection(spannable, spannable.length());
    }

    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
        if (mObserver == null) {
            mObserver = new PopupDataSetObserver();
        } else if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mObserver);
        }
        mAdapter = adapter;
        if (mAdapter != null) {
            mFilter = ((Filterable) mAdapter).getFilter();
            adapter.registerDataSetObserver(mObserver);
        } else {
            mFilter = null;
        }
        mPopup.setAdapter(mAdapter);
    }

    public void setCompletionHint(CharSequence hint) {
        mHintText = hint;
        if (hint != null) {
            if (mHintView == null) {
                final TextView hintView = (TextView) LayoutInflater.inflate(
                        getContext(), mHintResource).findViewById(
                        android.R.id.text1);
                hintView.setText(mHintText);
                mHintView = hintView;
                mPopup.setPromptView(hintView);
            } else {
                mHintView.setText(hint);
            }
        } else {
            mPopup.setPromptView(null);
            mHintView = null;
        }
    }

    public void setDropDownAlwaysVisible(boolean dropDownAlwaysVisible) {
        mPopup.setDropDownAlwaysVisible(dropDownAlwaysVisible);
    }

    public void setDropDownAnchor(int id) {
        mDropDownAnchorId = id;
        mPopup.setAnchorView(null);
    }

    public void setDropDownAnimationStyle(int animationStyle) {
        mPopup.setAnimationStyle(animationStyle);
    }

    public void setDropDownBackgroundDrawable(Drawable d) {
        mPopup.setBackgroundDrawable(d);
    }

    public void setDropDownBackgroundResource(int id) {
        mPopup.setBackgroundDrawable(getResources().getDrawable(id));
    }

    public void setDropDownDismissedOnCompletion(
            boolean dropDownDismissedOnCompletion) {
        mDropDownDismissedOnCompletion = dropDownDismissedOnCompletion;
    }

    public void setDropDownHeight(int height) {
        mPopup.setHeight(height);
    }

    public void setDropDownHorizontalOffset(int offset) {
        mPopup.setHorizontalOffset(offset);
    }

    public void setDropDownVerticalOffset(int offset) {
        mPopup.setVerticalOffset(offset);
    }

    public void setDropDownWidth(int width) {
        mPopup.setWidth(width);
    }

    public void setForceIgnoreOutsideTouch(boolean forceIgnoreOutsideTouch) {
        mPopup.setForceIgnoreOutsideTouch(forceIgnoreOutsideTouch);
    }

    @Override
    protected boolean setFrame(final int l, int t, final int r, int b) {
        boolean result = super.setFrame(l, t, r, b);
        if (isPopupShowing()) {
            showDropDown();
        }
        return result;
    }

    public void setListSelection(int position) {
        mPopup.setSelection(position);
    }

    @Override
    public void setOnClickListener(OnClickListener listener) {
        mPassThroughClickListener.mWrapped = listener;
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
        mItemClickListener = l;
    }

    public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener l) {
        mItemSelectedListener = l;
    }

    public void setText(CharSequence text, boolean filter) {
        if (filter) {
            setText(text);
        } else {
            mBlockCompletion = true;
            setText(text);
            mBlockCompletion = false;
        }
    }

    public void setThreshold(int threshold) {
        if (threshold <= 0) {
            threshold = 1;
        }

        mThreshold = threshold;
    }

    public void setValidator(Validator validator) {
        mValidator = validator;
    }

    @SuppressLint("NewApi")
    public void showDropDown() {
        buildImeCompletions();
        if (mPopup.getAnchorView() == null) {
            if (mDropDownAnchorId != View.NO_ID) {
                mPopup.setAnchorView(getRootView().findViewById(
                        mDropDownAnchorId));
            } else {
                mPopup.setAnchorView(this);
            }
        }
        if (!isPopupShowing()) {
            mPopup.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NEEDED);
            mPopup.setListItemExpandMax(AutoCompleteTextView.EXPAND_MAX);
        }
        mPopup.show();
        if (VERSION.SDK_INT >= 9) {
            mPopup.getListView().setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        }
    }

    public void showDropDownAfterLayout() {
        mPopup.postShow();
    }

    private void updateDropDownForFilter(int count) {
        if (getWindowVisibility() == View.GONE) {
            return;
        }
        final boolean dropDownAlwaysVisible = mPopup.isDropDownAlwaysVisible();
        final boolean enoughToFilter = enoughToFilter();
        if ((count > 0 || dropDownAlwaysVisible) && enoughToFilter) {
            if (hasFocus() && hasWindowFocus() && mPopupCanBeUpdated) {
                showDropDown();
            }
        } else if (!dropDownAlwaysVisible && isPopupShowing()) {
            dismissDropDown();
            mPopupCanBeUpdated = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

Add Academic Information

<form action="adda.php" method="post">

        Level Education
        <select name="level_edu">
            <option value="Diploma" selected="selected">Diploma</option>
            <option value="Bachelor/Honors">Bachelor/Honors</option>
            <option value="Masters">Masters</option>
        </select>

        Exam Title *

        <input type="text" name="e_title" />

        Group/Subject *

        <input type="text" name="group_sub" />

        Institution *
        <select name="ins_ion">
            <option value="select institute" selected="selected">--select institute--</option>
            <option value="UAP">UAP</option>
            <option value="DU">DU</option>
            <option value="North">North</option>
            <option value="South">South</option>
        </select>

        Result Type *
        <select name="r_type">
            <option value="Grade" selected="selected">Grade</option>
            <option value="Other">Other</option>

        </select>

    Result *

    <input type="text" name="result" />

    Scale *
    <input type="text" name="scale" />

        Passing Year *

        <input type="text" name="pass_yr" />

        Duration (in year)

        <input type="text" name="dur_yr" />

        Achievement

        <textarea name="achieve" rows="5" cols="40"></textarea>

    <button type="submit" name="submit" style="width: 210px;">Submit</button>


text:
<?php namespace davestewart\sketchpad\objects\reflection;

use davestewart\sketchpad\utils\Options;
use JsonSerializable;
use ReflectionParameter;

/**
 * Sketchpad Parameter
 *
 * Represents a method parameter
 */

class Parameter extends Tag implements JsonSerializable
{

	// ---------------------------------------------------------------------------------------------------------------
	// PROPERTIES

		/**
		 * The parameter type
		 *
		 * @var mixed|string
		 */
		public $type;

		/**
		 * Whether the parameter is optional or not
		 *
		 * @var bool
		 */
		public $optional;

		/**
		 * The parameter value, if optional
		 *
		 * @var mixed
		 */
		public $value;

		/**
		 * Optional docblock text (must be set externally)
		 *
		 * @var string
		 */
		public $text;

		/**
		 * Any field attribute values
		 *
		 * @var Field
		 */
		public $field;

		/**
		 * Any field attribute values
		 *
		 * @var array
		 */
		public $attrs;

	// ---------------------------------------------------------------------------------------------------------------
	// METHODS

		/**
		 * Parses a ReflectionParameter into a more usable object
		 *
		 * @param   ReflectionParameter $param      PHP reflection parameter object
		 * @param   Tag                 $tag        An optional PHP DocComment @param declaration of user-defined type and text
		 */
		public function __construct($param, $tag = null)
		{
			// name & optional
			$this->name         = $param->getName();
			$this->optional     = $param->isOptional();
			$this->text         = $tag ? $tag->text : '';

			// value
			$value              = $param->isOptional() && ! $param->isVariadic()
                                    ? $param->getDefaultValue()
                                    : $param->getName();

            //$value              = $value === null ? 'null' : $value;
			//$value              = $value === false ? 'false' : $value;
			$this->value	    = $value;

			// type
			$this->type         = $this->getType($param, $value, $tag ? $tag->type : null);
		}

		/**
		 * Set the field value
		 *
		 * @param   Field   $field
		 * @return          $this
		 */
		public function setField ($field)
		{
			$this->field = $field;
			return $this;
		}

		/**
		 * Gets the parameter type
		 *
		 * @param   ReflectionParameter $param
		 * @param   mixed               $value
		 * @param   string              $type
		 * @return  string
		 */
		protected function getType($param, $value, $type = null)
		{
			// attempt to get the type
			$type = method_exists($param, 'getType')
				? $param->getType()
				: $type
					? $type
					: gettype($value);

			// coerce type to something javascript will understand
			if($type == 'double' || $type == 'float' || $type == 'integer' || $type == 'int')
			{
				$type = 'number';
			}
			else if($type == 'bool')
			{
				$type = 'boolean';
			}
			else if($type == 'NULL')
			{
				$type = 'null';
			}

			// return
			return $type;
		}

		/**
		 * Specify data which should be serialized to JSON
		 */
		public function jsonSerialize()
		{
			// base values
			$values = (object)
			[
				'name'      => $this->name,
				'type'      => $this->type,
				'value'     => $this->value,
				'text'      => $this->text,
				'field'     => null,
				'attrs'     => (object) [],
			];

			// override if field set
			if (isset($this->field))
			{
				$values->field = $this->field->type;
				$values->attrs = (object) $this->field->attrs;

			}
			return $values;
		}

}


text:
package com.yjl.javabase.thinkinjava.containers;//: containers/FillingLists.java
// The Collections.fill() & Collections.nCopies() methods.
import java.util.*;

class StringAddress {
  private String s;
  public StringAddress(String s) { this.s = s; }
  public String toString() {
    return super.toString() + " " + s;
  }
}

public class FillingLists {
  public static void main(String[] args) {
    List<StringAddress> list= new ArrayList<StringAddress>(
      Collections.nCopies(4, new StringAddress("Hello")));
    System.out.println(list);
    Collections.fill(list, new StringAddress("World!"));
    System.out.println(list);
  }
} /* Output: (Sample)
[StringAddress@82ba41 Hello, StringAddress@82ba41 Hello, StringAddress@82ba41 Hello, StringAddress@82ba41 Hello]
[StringAddress@923e30 World!, StringAddress@923e30 World!, StringAddress@923e30 World!, StringAddress@923e30 World!]
*///:~


text:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "ofMain.h"
#pragma once

@interface ofxiPhoneCoreLocationDelegate : NSObject <CLLocationManagerDelegate>
{
	CLLocationManager *locationManager;

	//location
	double lat;
	double lng;
	double hAccuracy;
	double alt;
	double vAccuracy;
	double distMoved;
	//NSString * lastUpdatedLocationTimestamp

	//heading
	double x;
	double y;
	double z;
	double magneticHeading;
	double trueHeading;
	double headingAccuracy;
	//NSString * lastUpdatedCompasTimestamp
}

@property (nonatomic, readonly) double lat;
@property (nonatomic, readonly) double lng;
@property (nonatomic, readonly) double hAccuracy;
@property (nonatomic, readonly) double alt;
@property (nonatomic, readonly) double vAccuracy;
@property (nonatomic, readonly) double distMoved;
@property (nonatomic, readonly) double x;
@property (nonatomic, readonly) double y;
@property (nonatomic, readonly) double z;
@property (nonatomic, readonly) double magneticHeading;
@property (nonatomic, readonly) double trueHeading;
@property (nonatomic, readonly) double headingAccuracy;

- (id) init;
- (void) dealloc;

- (bool) startHeading;
- (void) stopHeading;

- (bool) startLocation;
- (void) stopLocation;

- (bool) startMonitoringSignificantLocationChanges;
- (void) stopMonitoringSignificantLocationChanges;

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation;

- (void)locationManager:(CLLocationManager *)manager
	   didFailWithError:(NSError *)error;

@end

class ofxiPhoneCoreLocation
{

	public:

		ofxiPhoneCoreLocation();
		~ofxiPhoneCoreLocation();

		bool startHeading();
		void stopHeading();

		bool startLocation();
		void stopLocation();

        bool startMonitoringSignificantLocationChanges();
        void stopMonitoringSignificantLocationChanges();

		double getLatitude();
		double getLongitude();
		double getLocationAccuracy();
		double getAltitude();
		double getAltitudeAccuracy();
		double getDistMoved();
		double getCompassX();
		double getCompassY();
		double getCompassZ();
		double getMagneticHeading();
		double getTrueHeading();
		double getHeadingAccuracy();

	protected:

		ofxiPhoneCoreLocationDelegate *	coreLoc;
};


text:
var effects = require('./imageprocessing');

// Use SPI mock for development on windows machines
try{
	var SPI = require('spi');
} catch (error) {
	var SPI = require('./spi-mock');
}

var LedPanel = function(dev){ // device eg: '/dev/spidev1.1'
	this.device = new SPI.Spi(dev, {
		"mode": SPI.MODE['MODE_0'],// always set mode as the first option
    	'chipSelect': SPI.CS['none'], // 'none', 'high' - defaults to low
		'maxSpeed': 16000000
	}, function(s){s.open();});

	this.line = function(panel, line, data){
		var buffer = new Buffer((3 + (32*3)));

		buffer[0] = 0x01; 	// line command
		buffer[1] = panel;	// panel number
		buffer[2] = line;	// line number

		data.copy(buffer, 3);

		this.device.write(buffer);
	};

};

LedPanel.prototype.image = function(image, callback)
{
	if(image.length != 96*64*3 && image.length != 96*64*4)
		throw "Incorrect buffer size";

	if(image.length == 96*64*4){
		image = effects.RgbaToRgb(image);
	}

	for(slice = 0;slice < 6*32; slice++){
		var start = slice*32*3;
		var panel = (slice < 3*32) ? (slice % 3) : 3 + (slice % 3);
		var line =  Math.floor((slice < 3*32) ? (slice / 3) : (slice / 3) - 32);

		var buffer = image.slice(start, start + (32*3));

		buffer = effects.adjustGamma(buffer, 0.3);

		this.line(panel, line, buffer);
	}
	this.flush();

	if(typeof(callback) === "function")
		callback();
}

LedPanel.prototype.flush = function(callback)
{
	var buffer = new Buffer([0x08]);
	this.device.write(buffer);

	if(typeof(callback) === "function")
		callback();
}

module.exports = LedPanel;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Awesome chat</title>

        <input type="text" id="name">

        <input type="text" id="inputMsg">

        <button id="send">Send</button>


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace ValueUtils
{
    public static class FieldwiseHasher
    {
        /// <summary>
        /// Computes a hashcode for an object based on its fields.  Type resolution is done
        /// statically, which allows fast code (similar to hand-rolled performance).
        /// However, warning: if the instance is of compile-time type BaseType, but at runtime turns out
        /// to be SubClass, then only the fields of BaseType will be checked.
        /// This is simply a type-inference friendly wrapper around FieldwiseHasher<>.Instance
        /// </summary>
        /// <typeparam name="T">The type of the object to hash.</typeparam>
        public static int Hash<T>(T val) => FieldwiseHasher<T>.Instance(val);
    }

    public static class FieldwiseHasher<T>
    {
        /// <summary>
        /// Computes a hashcode for an object based on its fields.  Type resolution is specified
        /// statically, which allows fast code (similar to hand-rolled performance).
        /// However, warning: if the instance is of compile-time type BaseType, but at runtime turns out
        /// to be SubClass, then only the fields of BaseType will be checked.
        /// </summary>
        public static readonly Func<T, int> Instance = CreateLambda().Compile();

        internal static Expression<Func<T, int>> CreateLambda()
        {
            //Get all fields including inherited fields
            var type = typeof(T);
            var nonNullableTypeOrNull = ReflectionHelper.WhenNullableValueTypeGetNonNullableType(type.GetTypeInfo());
            var fields = ReflectionHelper.GetAllFields(type);

            var paramExpr = Expression.Parameter(type, "valueToHash");
            //Strategy: accumulate a scaled hash code for each member

            //Start with some arbitrary constant; pick something type-dependant for the rare mixed-type usecase.
            Expression hashExpr = Expression.Constant((ulong)type.GetHashCode() * 1234567);
            var fieldIndex = 0ul;
            var getHashCodeMethod = ((Func<int>)new object().GetHashCode).GetMethodInfo();

            foreach (var fieldInfo in fields) {
                var fieldExpr = Expression.Field(paramExpr, fieldInfo);

                //use the field's hash code (pre-resolving overridden GetHashCode does not appear to be faster)
                var rawFieldHashExpr = Expression.Call(fieldExpr, getHashCodeMethod);

                //we want to scale/bit-rotate the 32bit hashcode, and the fastest way to do that on common
                //x64 systems is via ulong - but we don't want sign-extension, so first we cast to unsigned.
                var uintFieldHashExpr = Expression.Convert(rawFieldHashExpr, typeof(uint));
                var ulongFieldHashExpr = Expression.Convert(uintFieldHashExpr, typeof(ulong));

                /*
thoughts here are: I'd like common cases (i.e. the first 50 or so fields) not to wrap in 64-bit arithmetic.
This allows me to use plain old normal math to ensure that the coefficients are relatively prime
 - of course I guess I could just use primes themselves...
Furthermore, I want coefficients to be relatively large, so that I'm using as much of my 64-bit entropy
as possible to encourage good mixing.  In practice this means I want my multiplicative factor to be not\
too far from 2^64/2^32/100 say, i.e. not too much smaller than 50 million.

The below constants were chosen so that field coefficients are less than 2^32 but not that far
from it, and (almost entirely) relatively prime for the first 50 coefficients.

                 */
                fieldIndex++;
                var scale = 1794966779ul /*prime*/
                    + fieldIndex * 35225190ul /*2*3*3*5*7*11*13*17*23 */;
                var scaledFieldHashExpr = Expression.Multiply(ulongFieldHashExpr, Expression.Constant(scale));

                //if this field is null, use some arbitrary hash code.
                var nullSafeFieldHashExpr = fieldInfo.FieldType.GetTypeInfo().IsValueType
                    ? (Expression)scaledFieldHashExpr
                    : Expression.Condition(
                        Expression.Equal(Expression.Default(typeof(object)),
                            Expression.Convert(fieldExpr, typeof(object))
                        ),
                        Expression.Constant(scale * 3456789ul),
                        scaledFieldHashExpr
                    );

                //add this field to running total.  Note we don't need an explicit accumulation variable!
                hashExpr = Expression.Add(hashExpr, nullSafeFieldHashExpr);
            }

            //we have a 64-bit expression, need to downmix to 32bit.
            var ulongHashVariable = Expression.Variable(typeof(ulong), "hashcode");
            var writeHashStatement = Expression.Assign(ulongHashVariable,
                    !type.GetTypeInfo().IsValueType
                        ? Expression.Condition(
                            Expression.NotEqual(Expression.Convert(paramExpr, typeof(object)), Expression.Default(typeof(object))),
                            hashExpr,
                            Expression.Constant((ulong)type.GetHashCode() * 1234567)
                        )
                        : nonNullableTypeOrNull != null
                            ? Expression.Condition(
                                Expression.Property(paramExpr, "HasValue"),
                                hashExpr,
                                Expression.Constant((ulong)type.GetHashCode() * 1234567)
                            )
                            : hashExpr
                );

            var intHashExpr =
                Expression.Convert(
                    Expression.ExclusiveOr(
                        ulongHashVariable,
                        Expression.RightShift(ulongHashVariable, Expression.Constant(32))
                    )
                    , typeof(int)
                );

            var bodyExpr = Expression.Block(new[] { ulongHashVariable, }, writeHashStatement, intHashExpr);
            return Expression.Lambda<Func<T, int>>(bodyExpr, paramExpr);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using MultichainCliLib;
using TrustLessAPI.Models;
using TrustLessModelLib;
using System.Web.Configuration;
using MultichainCliLib.Responses;

namespace TrustLessAPI.Storage
{
    /// <summary>
    /// BlockChain is a dedicated MultiChain layer between the server node and the server API. Any contact with the server node must
    /// be executed within this class.
    /// </summary>
    public static class BlockChain
	{
        /// <summary>
        /// A lock object that ensures that race condition won't create a problem with issuing funds in GenerateFunds method.
        /// The needed new assets of S_X or F_X are found by getting the list of assets in the server node. Therefore the conclusion
        /// to issue more assets mustn't be made twice.
        /// </summary>
		public static Object issueLock = new object();

        /// <summary>
        /// Imports a public key to the wallet of the server node.
        /// This allows for checking the balance of the public key.
        /// </summary>
        /// <param name="person"></param>
		public static void ImportPublicKeyToWallet(Person person)
		{
			string chainName = WebConfigurationManager.AppSettings["ChainName"];
			string nodeIp = WebConfigurationManager.AppSettings["NodeIp"];
			MultiChainClient client = new MultiChainClient(chainName,nodeIp);
			client.ImportAddress(person.PublicKey);
		}

        /// <summary>
        /// Reserves/locks away one S and F asset and sets the recommendation to reference these assets.
        /// </summary>
        /// <param name="db">DataContext</param>
        /// <param name="recommendation">Recommendation</param>
        public static void MakeRecommendation(DataContext db, TrustLessModelLib.Recommendation recommendation)
        {
			string chainName = WebConfigurationManager.AppSettings["ChainName"];
			string nodeIp = WebConfigurationManager.AppSettings["NodeIp"];
			MultiChainClient client = new MultiChainClient(chainName,nodeIp);
			Dictionary<string,int> dictionary = new Dictionary<string, int>();
			AddressBalance[] addressBalances = client.GetTotalBalances ().Balances;
			var lastFasset = addressBalances.OrderBy (x => x.name).LastOrDefault (x => x.name.StartsWith ("F_"));
			var lastSasset = addressBalances.OrderBy (x => x.name).LastOrDefault (x => x.name.StartsWith ("S_"));
			if (lastFasset == null || lastSasset == null) {
				GenerateFunds (client);
				MakeRecommendation (db, recommendation);
				return;
			}
			string lastF = lastFasset.name;
			string lastS = lastSasset.name;

			dictionary.Add(lastF,1);
			dictionary.Add(lastS,1);
			try
			{
				var resp = client.PrepareLockUnspent(dictionary);

				recommendation.Transaction = new ReservedTransaction()
				{
					Tx = resp.txid,
					Vout = resp.vout
				};
			}
			catch {
				//Insurficient funds
				GenerateFunds(client);
				MakeRecommendation (db, recommendation);
				return;
			}

			db.SaveChanges ();
        }

        /// <summary>
        /// If the balance of S_X or F_X is equals zero, a new unique asset S_X or F_X will be issued.
        /// </summary>
        /// <param name="client">MultichainClient</param>
		private static void GenerateFunds(MultiChainClient client)
		{
			lock (issueLock) {
				AddressBalance[] addressBalances = client.GetTotalBalances ().Balances;
				ListAssetsResponseAsset[] assets = client.ListAssets ().Assets;
					string rootKey = WebConfigurationManager.AppSettings["MultichainPublicKey"];
					ListAssetsResponseAsset lastSasset = assets.OrderBy (x => x.name).LastOrDefault (x => x.name.StartsWith ("S_"));
					string lastS = lastSasset != null ? lastSasset.name : "S_0";
					ListAssetsResponseAsset lastFasset = assets.OrderBy (x => x.name).LastOrDefault (x => x.name.StartsWith ("F_"));
					string lastF = lastSasset != null ? lastSasset.name : "F_0";
					string newS = "S_" + (Convert.ToInt32 (lastS.Substring (2)) + 1);
					string newF = "F_" + (Convert.ToInt32 (lastS.Substring (2)) + 1);
				var balanceS = addressBalances.FirstOrDefault (x => x.name == lastS);
				var balanceF = addressBalances.FirstOrDefault (x => x.name == lastF);

				if (balanceS == null || balanceS.qty == 0)
					client.Issue (rootKey, newS, 100000, 1.0);
				if (balanceF == null || balanceF.qty == 0)
					client.Issue (rootKey, newF, 100000, 1.0);
			}
		}

        /// <summary>
        /// Issues an S or F to a user for a recommendation.
        /// </summary>
        /// <param name="recommendation">Recommendation</param>
        /// <param name="rewardUser">true for S asset and false for F</param>
		public static void Issue(TrustLessModelLib.Recommendation recommendation, bool rewardUser)
        {
				string chainName = WebConfigurationManager.AppSettings["ChainName"];
				string nodeIp = WebConfigurationManager.AppSettings["NodeIp"];
				MultiChainClient client = new MultiChainClient(chainName,nodeIp);

				GetTxOutResponse getTxOutResponse = client.GetTxOut(recommendation.Transaction.Tx,recommendation.Transaction.Vout);
			if (getTxOutResponse == null)
				return;

			Dictionary<string,int> amount = new Dictionary<string, int>();
				amount.Add(getTxOutResponse.assets.First(x => x.name.StartsWith(rewardUser ? "S_" : "F_")).name,1);

				string multichainPublicKey = WebConfigurationManager.AppSettings["MultichainPublicKey"];
			var resp = client.CreateRawTransaction (recommendation.Person.PublicKey, recommendation.Transaction.Tx,recommendation.Transaction.Vout, amount);
				var respAppendRawChange = client.AppendRawChange (resp.Hex, multichainPublicKey);
			var respSignTransaction = client.SignRawTransaction (respAppendRawChange.Hex);
			if (respSignTransaction.complete) {
				var respSendRawTransaction = client.SendRawTransaction (respSignTransaction.hex);
				if (String.IsNullOrEmpty (respSendRawTransaction.TransactionId))
					client.LockUnspent (true,  recommendation.Transaction.Tx,recommendation.Transaction.Vout);
			}

        }

        /// <summary>
        /// Converts a hex string to a byte array
        /// </summary>
        /// <param name="hex">string hex</param>
        /// <returns>byte array</returns>
        public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

        /// <summary>
        /// Gets a given person's (user) assets.
        /// </summary>
        /// <param name="person">person (user)</param>
        /// <returns>AddressBalance array</returns>
		public static AddressBalance[] GetPersonBalance(Person person)
		{
			string chainName = WebConfigurationManager.AppSettings["ChainName"];
			string nodeIp = WebConfigurationManager.AppSettings["NodeIp"];
			MultiChainClient client = new MultiChainClient(chainName,nodeIp);
			var resp = client.GetAddressbalances (person.PublicKey);
			return resp.Balances;
		}

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:orientation="horizontal"
            android:layout_margin="12dp">
        <EditText
                android:layout_width="0dp"
                android:layout_weight="1"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:layout_height="match_parent"
                android:background="@drawable/white_rounded_rect"/>

        <TextView
                android:id="@+id/cancel_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:text="Cancel"
                style="@style/Base.Widget.AppCompat.Button.Borderless"/>

    </LinearLayout>

    <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:background="@color/white"
            android:layout_height="0dp"/>

</LinearLayout>


text:
void Model::addChild(std::shared_ptr<Model> model)
{
    children.push_back(model);
    model->parent = this;
}

std::vector<Mesh::SubMesh> Model::getAllSubMeshes() const
{
    std::vector<Mesh::SubMesh> allMeshes;
    allMeshes.insert(allMeshes.end(), subMeshes.begin(), subMeshes.end());

    for (auto m : children)
    {
        auto childMeshes = m->getAllSubMeshes();
        allMeshes.insert(allMeshes.end(), childMeshes.begin(), childMeshes.end());
    }

    return allMeshes;
}

std::vector<MaterialDescription> Model::getAllMaterials() const
{
    std::vector<MaterialDescription> allMaterials;
    allMaterials.insert(allMaterials.end(), materials.begin(), materials.end());

    for (auto m : children)
    {
        auto childMaterials = m->getAllMaterials();
        allMaterials.insert(allMaterials.end(), childMaterials.begin(), childMaterials.end());
    }

    return allMaterials;
}

size_t Model::getTriangleCount() const
{
    size_t triangleCount = 0;

    for (auto& sm : subMeshes)
        triangleCount += sm.indices.size() / 3;

    for (auto& c : children)
        triangleCount += c->getTriangleCount();

    return triangleCount;
}


text:
var
	gulp = require('gulp'),
	$ = require('gulp-load-plugins')(),

	path = require('path'),
	browserSync = require('browser-sync'),
	// bSync = browserSync.create(),
	config = require('../config'),
	consoleError = require('../utils/console_error');

function bSync(cb) {

	browserSync({
		minify: false,
		injectChanges: true,
		files: [
			config.paths.built.styles.all,
			config.paths.built.scripts.all,
			config.paths.built.templates.all,
			config.paths.built.images.all
		],
		notify: false,
		open: false,
		server: {
			baseDir: path.join(__dirname, '/../../dist')
		},
		port: 3000
	}, cb);

}

module.exports = bSync;


text:
#include "galib_phototaxis_loop_functions.h"

/****************************************/
/****************************************/

CGALibPhototaxisLoopFunctions::CGALibPhototaxisLoopFunctions() :
   m_unCurrentTrial(0),
   m_vecInitSetup(5),
   m_pcFootBot(NULL),
   m_pcController(NULL),
   m_pfControllerParams(new Real[GENOME_SIZE]),
   m_pcRNG(NULL) {}

/****************************************/
/****************************************/

CGALibPhototaxisLoopFunctions::~CGALibPhototaxisLoopFunctions() {
   delete[] m_pfControllerParams;
}

/****************************************/
/****************************************/

void CGALibPhototaxisLoopFunctions::Init(TConfigurationNode& t_node) {
   /*
    * Create the random number generator
    */
   m_pcRNG = CRandom::CreateRNG("argos");

   /*
    * Create the foot-bot and get a reference to its controller
    */
   m_pcFootBot = new CFootBotEntity(
      "fb",    // entity id
      "fnn"    // controller id as set in the XML
      );
   AddEntity(*m_pcFootBot);
   m_pcController = &dynamic_cast<CFootBotNNController&>(m_pcFootBot->GetControllableEntity().GetController());

   /*
    * Create the initial setup for each trial
    * The robot is placed 4.5 meters away from the light
    * (which is in the origin) at angles
    * { PI/12, 2*PI/12, 3*PI/12, 4*PI/12, 5*PI/12 }
    * wrt to the world reference.
    * Also, the rotation of the robot is chosen at random
    * from a uniform distribution.
    */
   CRadians cOrient;
   for(size_t i = 0; i < 5; ++i) {
      /* Set position */
      m_vecInitSetup[i].Position.FromSphericalCoords(
         4.5f,                                          // distance from origin
         CRadians::PI_OVER_TWO,                         // angle with Z axis
         static_cast<Real>(i+1) * CRadians::PI / 12.0f // rotation around Z
         );
      /* Set orientation */
      cOrient = m_pcRNG->Uniform(CRadians::UNSIGNED_RANGE);
      m_vecInitSetup[i].Orientation.FromEulerAngles(
         cOrient,        // rotation around Z
         CRadians::ZERO, // rotation around Y
         CRadians::ZERO  // rotation around X
         );
   }

   /*
    * Process trial information, if any
    */
   try {
      GetNodeAttribute(t_node, "trial", m_unCurrentTrial);
      Reset();
   }
   catch(CARGoSException& ex) {}
}

/****************************************/
/****************************************/

void CGALibPhototaxisLoopFunctions::Reset() {
   /*
    * Move robot to the initial position corresponding to the current trial
    */
   if(!MoveEntity(
         m_pcFootBot->GetEmbodiedEntity(),             // move the body of the robot
         m_vecInitSetup[m_unCurrentTrial].Position,    // to this position
         m_vecInitSetup[m_unCurrentTrial].Orientation, // with this orientation
         false                                         // this is not a check, leave the robot there
         )) {
      LOGERR << "Can't move robot in <"
             << m_vecInitSetup[m_unCurrentTrial].Position
             << ">, <"
             << m_vecInitSetup[m_unCurrentTrial].Orientation
             << ">"
             << std::endl;
   }
}

/****************************************/
/****************************************/

void CGALibPhototaxisLoopFunctions::ConfigureFromGenome(const GARealGenome& c_genome) {
   /* Copy the genes into the NN parameter buffer */
   for(size_t i = 0; i < GENOME_SIZE; ++i) {
      m_pfControllerParams[i] = c_genome[i];
   }
   /* Set the NN parameters */
   m_pcController->GetPerceptron().SetOnlineParameters(GENOME_SIZE, m_pfControllerParams);
}

/****************************************/
/****************************************/

Real CGALibPhototaxisLoopFunctions::Performance() {
   /* The performance is simply the distance of the robot to the origin */
   return m_pcFootBot->GetEmbodiedEntity().GetOriginAnchor().Position.Length();
}

/****************************************/
/****************************************/

REGISTER_LOOP_FUNCTIONS(CGALibPhototaxisLoopFunctions, "galib_phototaxis_loop_functions")


text:
#region License

#endregion

using System;
using System.Collections.Generic;

namespace VulkaNet
{
    public interface IVkImageView : IVkNonDispatchableHandledObject, IVkDeviceChild, IDisposable
    {
        VkImageView.HandleType Handle { get; }
        IVkAllocationCallbacks Allocator { get; }
    }

    public unsafe class VkImageView : IVkImageView
    {
        public IVkDevice Device { get; }
        public HandleType Handle { get; }
        public IVkAllocationCallbacks Allocator { get; }

        private VkDevice.DirectFunctions Direct => Device.Direct;

        public ulong RawHandle => Handle.InternalHandle;

        public VkImageView(IVkDevice device, HandleType handle, IVkAllocationCallbacks allocator)
        {
            Device = device;
            Handle = handle;
            Allocator = allocator;
        }

        public struct HandleType
        {
            public readonly ulong InternalHandle;
            public HandleType(ulong internalHandle) { InternalHandle = internalHandle; }
            public override string ToString() => InternalHandle.ToString();
            public static int SizeInBytes { get; } = sizeof(ulong);
            public static HandleType Null => new HandleType(default(ulong));
        }

        public void Dispose()
        {
            var unmanagedSize =
                Allocator.SizeOfMarshalIndirect();
            var unmanagedArray = new byte[unmanagedSize];
            fixed (byte* unmanagedStart = unmanagedArray)
            {
                var unmanaged = unmanagedStart;
                var _device = Device.Handle;
                var _imageView = Handle;
                var _pAllocator = Allocator.MarshalIndirect(ref unmanaged);
                Direct.DestroyImageView(_device, _imageView, _pAllocator);
            }
        }

    }

    public static unsafe class VkImageViewExtensions
    {
        public static int SizeOfMarshalDirect(this IReadOnlyList<IVkImageView> list) =>
            list.SizeOfMarshalDirectNonDispatchable();

        public static VkImageView.HandleType* MarshalDirect(this IReadOnlyList<IVkImageView> list, ref byte* unmanaged) =>
            (VkImageView.HandleType*)list.MarshalDirectNonDispatchable(ref unmanaged);
    }
}


text:
if ! [ "$(which astyle)" ]; then
    echo "Install astyle first!"
    exit
fi

astyle \
--mode=c \
--style=google \
--indent=force-tab \
--attach-namespaces \
--attach-classes \
--attach-inlines \
--indent-col1-comments \
--pad-header \
--unpad-paren \
--align-pointer=type \
--fill-empty-lines \
--recursive \
--suffix=none *.c *.cpp *.h *.hpp


text:
require "no_patch/version"

# The no patch module provides a way to avoid a class from being monkey patched.
# An example of that would be shared code between two objects. You would not want
# any of the objects to define methods that are already defined in what is meant
# to be shared.
#
# This is evaluated at compile time so you can figure it out before your code
# makes it to production
#
# Example Usage:
#
#   class Foo
#     include NoPatch
#
#     def foo
#     end
#   end
#
# Now, further down the line:
#
#   class Foo
#     def foo
#     end
#   end # => raise NoPatch::RedifinitionError
#
#
# Warning: this does not prevent it from being redefined dynamically, aka
#
# Example:
#   a = Foo.new
#   def a.foo
#     puts "ok"
#   end
#
#   a.foo # => "ok"
#
module NoPatch
  # A specific error class
  #
  class RedifinitionError < StandardError; end

  # Used by including it in a class.
  # This is the hook that will be run each time a class includes it.
  #
  # Example
  #
  #   class Foo
  #     include NoPatch
  #   end
  #
  def self.included(klass)
    klass.extend(ClassMethods)
  end

  module ClassMethods
    def method_added(sym)
      @immutable_instance_methods ||= []
      raise RedifinitionError, "Method #{self}##{sym} cannot be redefined" if @immutable_instance_methods.include? sym
      @immutable_instance_methods << sym
      super
    end

    def method_removed(sym)
      super
      raise RedifinitionError, "Method #{self}##{sym} cannot be removed"
    end

    def method_undefined(sym)
      super
      raise RedifinitionError, "Method #{self}##{sym} cannot be undefined"
    end

    # Heads up, this calls itself after being defined
    def singleton_method_added(sym)
      @immutable_class_methods ||= []
      raise RedifinitionError, "Method #{self}::#{sym} cannot be redefined" if @immutable_class_methods.include? sym
      @immutable_class_methods << sym
      super
    end

    def singleton_method_removed(sym)
      super
      raise RedifinitionError, "Method #{self}::#{sym} cannot be removed"
    end

    def singleton_method_undefined(sym)
      super
      raise RedifinitionError, "Method #{self}::#{sym} cannot be undefined"
    end
  end
end


text:
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Husky.Lbs.QQLbs.Tests
{
	[TestClass()]
	public class QQLbsServiceTests
	{
		//attention: fill the required values to run this test

		private readonly string _key = "";

		[TestMethod()]
		public async Task MarshalTest() {
			if ( string.IsNullOrEmpty(_key) ) {
				return;
			}

			var qqLbs = new QQLbsService(_key);

			static void assert(Address actual) {
				Assert.IsNotNull(actual);
				Assert.IsTrue(actual.Province.Contains("江苏"));
				Assert.IsTrue(actual.City.Contains("苏州"));
				Assert.AreEqual(31, Math.Floor(actual.Location.Lat));
				Assert.AreEqual(120, Math.Floor(actual.Location.Lon));
				Assert.AreEqual(LatLonType.Gcj02, actual.Location.LatLonType);
			};

			var ip = "49.73.123.252";
			var address = await qqLbs.GetAddressAsync(IPAddress.Parse(ip));
			assert((Address)address);

			var lonlat = address.Location;
			address = await qqLbs.GetAddressAsync(lonlat);
			assert((Address)address);
		}

		[TestMethod()]
		public async Task GetLatLonTest() {
			if ( string.IsNullOrEmpty(_key) ) {
				return;
			}

			var qqLbs = new QQLbsService(_key);
			var givenAddress = "江苏省苏州工业园区苏州中心";
			var latlon = await qqLbs.GetLatLonAsync(givenAddress);

			Assert.AreEqual(31, Math.Floor(latlon.Lat));
			Assert.AreEqual(120, Math.Floor(latlon.Lon));
		}

		[TestMethod()]
		public async Task GetDistanceTest() {
			if ( string.IsNullOrEmpty(_key) ) {
				return;
			}

			var qqLbs = new QQLbsService(_key);
			var latlon1 = new Location { Lat = 31.317064m, Lon = 120.680137m, LatLonType = LatLonType.Gcj02 };
			var latlon2 = new Location { Lat = 31.315506m, Lon = 120.670792m, LatLonType = LatLonType.Gcj02 };

			foreach ( DistanceMode i in Enum.GetValues(typeof(DistanceMode)) ) {
				var distance = await qqLbs.GetDistanceAsync(latlon1, latlon2, i);

				if ( i == DistanceMode.Driving ) {
					Assert.IsTrue(Math.Abs(distance.TravelTimeEstimate.TotalMinutes - 5) < 2);
				}
				Assert.IsTrue(Math.Abs(distance.Meters - 1400) < 500);
			}
		}

		[TestMethod()]
		public async Task GetDistancesTest() {
			if ( string.IsNullOrEmpty(_key) ) {
				return;
			}

			var qqLbs = new QQLbsService(_key);
			var latlon1 = new Location { Lat = 31.317064m, Lon = 120.680137m, LatLonType = LatLonType.Gcj02 };
			var latlon2 = new Location { Lat = 31.315506m, Lon = 120.670792m, LatLonType = LatLonType.Gcj02 };

			var distances = await qqLbs.GetDistancesAsync(latlon1, new Location[] { latlon2 }, DistanceMode.Driving);
			foreach ( var distance in distances ) {
				Assert.IsTrue(Math.Abs(distance.TravelTimeEstimate.TotalMinutes - 5) < 2);
				Assert.IsTrue(Math.Abs(distance.Meters - 1400) < 500);
			}
		}
	}
}


text:
<?php
namespace Glucose\Exceptions\MySQL\Server;
class MySQLBadNullException extends MySQLServerErrorException {

}


text:
namespace Incoding.MvcContrib
{
    using System;

    #region << Using >>

    #endregion

    public interface IIncodingMetaLanguageCallbackBodyDsl : IIncodingMetaLanguageWithDsl
    {
        IExecutableSetting Break { get; }

        IncodingMetaCallbackDocumentDsl Document { get; }

        IncodingMetaCallbackWindowDsl Window { get; }
    }
}


text:
package black.door.json;

import black.door.util.Misc;
import org.junit.Before;
import org.junit.Test;

import java.util.*;

import static org.junit.Assert.*;

/**
 * Created by nfischer on 6/28/2015.
 */
public class JsonHasherTest {

	Map<String, Object> map;
	Map<String, Object> simpleMap;
	List<Object> simpleList;

	@Before
	public void setup(){
		map = new HashMap<>();

		simpleMap = new HashMap<>();
		simpleMap.put("string", "sample");
		simpleMap.put("int", 5l);
		simpleMap.put("fraction", 5.50d);
		simpleMap.put("sciNote", Double.valueOf("3.7e-4"));
		simpleMap.put("bool", true);
		simpleMap.put("null", JsonNull.NULL);
		simpleMap.put("nullprim", null);

		simpleMap.put("emptyList", new ArrayList<>());

		simpleList = new ArrayList<>();
		simpleList.add("sample");
		simpleList.add(5l);
		simpleList.add(5.5d);
		simpleList.add(Double.valueOf("9.3e-200"));
		simpleList.add(true);
		simpleList.add(null);

		map.put("map", simpleMap);
		map.put("array", simpleList);
		map.put("emptyMap", new HashMap<>());
	}

	@Test
	public void testCannon(){
		String cannon = JsonHasher.canonicalize(map).toString();

		JsonObject json = new JsonObject(cannon);

		List<String> mapKeyset = new ArrayList<>(map.keySet());
		Collections.sort(mapKeyset);
		assertEquals(new ArrayList<>(json.keySet()), mapKeyset);

		System.out.println(cannon);
		System.out.println(Derulo.toJSON(2,Derulo.fromJSON(cannon)));
		System.out.println(Misc.bytesToHex(JsonHasher.hash(map)));
	}

	@Test
	public void testHash() throws Exception {
		byte[] hash1 = JsonHasher.hash(map);

		List<String> simpleKeys = new ArrayList<>(simpleMap.keySet());
		Collections.shuffle(simpleKeys);

		JsonObject json = new JsonObject();

		for(String key : simpleKeys){
			json.put(key, simpleMap.get(key));
		}
		map.put("map", json);

		assertArrayEquals(hash1, JsonHasher.hash(map));
	}

	@Test
	public void testInstance(){
		Map<String, Object> original = new HashMap<>(simpleMap);
		JsonHasher hasher = new JsonHasher(simpleMap);
		hasher.setIgnoredFields(Arrays.asList(new String[]{"int", "null"}));

		Map<String, Object> copy = new HashMap<>(simpleMap);
		copy.remove("int");
		copy.remove("null");

		assertArrayEquals(JsonHasher.hash(copy), hasher.hash());
		assertEquals(original, simpleMap);
	}
}


text:
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->

# Traffic Portal Installation / Configuration

### 1. Build Traffic Portal RPM w/ Docker or fetch Traffic Portal RPM from [Jenkins](https://builds.apache.org/view/S-Z/view/TrafficControl/job/incubator-trafficcontrol-master-build)

* Build instructions: https://github.com/apache/incubator-trafficcontrol/blob/master/BUILD.md

### 2. Install

* Install the Node.js JavaScript runtime

    ```
    $ curl --silent --location https://rpm.nodesource.com/setup_6.x | sudo bash -
    $ sudo yum install -y nodejs
    ```

* Install the Traffic Portal RPM

    ```
    $ sudo yum install -y traffic_portal-[version]-[commits].[sha].x86_64.rpm
    ```

### 3. Configure

* Configure Traffic Portal

    ```
    $ sudo vim /etc/traffic_portal/conf/config.js (read the inline comments)
    ```

### 4. Run

* Start Traffic Portal

    ```
    $ sudo service traffic_portal start
    ```

* Navigate to Traffic Portal

    ```
    $ http(s)://ip-address:port
    ```

#### Notes

    - Traffic Portal consumes the Traffic Ops API, therefore, an instance of Traffic Ops must be running.
    - Traffic Portal and Traffic Ops must be running on the same protocol (http or https).
    - This is known to work with CentOS 6.7 and Centos 7 as the host environment.


text:
<?php
namespace StudioNet\GraphQL\Support\Pipe;

use Illuminate\Pipeline\Pipeline as PipelineBase;

/**
 * Pipeline
 *
 * @see PipelineBase
 */
class Pipeline extends PipelineBase {
	/** @var array $parameters */
	protected $parameters = [];

	/**
	 * Get a Closure that represents a slice of the application onion.
	 *
	 * @override
	 * @return \Closure
	 */
	protected function carry() {
		return function ($stack, $pipe) {
			return function ($passable) use ($stack, $pipe) {
				if (is_callable($pipe)) {
					// If the pipe is an instance of a Closure, we will just call it directly but
					// otherwise we'll resolve the pipes out of the container and call it with
					// the appropriate method and arguments, returning the results back out.
					return $pipe($passable, $stack, ...$this->parameters);
				} elseif (!is_object($pipe)) {
					list($name, $parameters) = $this->parsePipeString($pipe);

					// If the pipe is a string we will parse the string and resolve the class out
					// of the dependency injection container. We can then build a callable and
					// execute the pipe function giving in the parameters that are required.
					$pipe = $this->getContainer()->make($name);
					$parameters = array_merge([$passable, $stack], array_merge($this->parameters, $parameters));
				} else {
					// If the pipe is already an object we'll just make a callable and pass it to
					// the pipe as-is. There is no need to do any extra parsing and formatting
					// since the object we're given was already a fully instantiated object.
					$parameters = array_merge([$passable, $stack], $this->parameters);
				}

				return method_exists($pipe, $this->method) ? $pipe->{$this->method}(...$parameters) : $pipe(...$parameters);
			};
		};
	}

	/**
	 * with
	 *
	 * @param  mixed $params,...
	 * @return self
	 */
	public function with(...$params): self {
		$this->parameters = $params;
		return $this;
	}
}


text:
'use strict';

/*
 * @noflow - get/set properties not yet supported by flow. also `...require(x)` is broken #6560135
 */

/* eslint global-require: 0 */

module.exports = {
  // Core
  get createNavigationContainer() {
    return require('./createNavigationContainer').default;
  },
  get StateUtils() {
    return require('./StateUtils').default;
  },
  get addNavigationHelpers() {
    return require('./addNavigationHelpers').default;
  },
  get NavigationActions() {
    return require('./NavigationActions').default;
  },

  // Navigators
  get createNavigator() {
    return require('./navigators/createNavigator').default;
  },
  get StackNavigator() {
    return require('./navigators/StackNavigator').default;
  },
  get TabNavigator() {
    return require('./navigators/TabNavigator').default;
  },
  get DrawerNavigator() {
    return require('./navigators/DrawerNavigator').default;
  },

  // Routers
  get StackRouter() {
    return require('./routers/StackRouter').default;
  },
  get TabRouter() {
    return require('./routers/TabRouter').default;
  },

  // Views
  get Transitioner() {
    return require('./views/Transitioner').default;
  },
  get CardStack() {
    return require('./views/CardStack').default;
  },
  get Card() {
    return require('./views/Card').default;
  },

  // Header
  get Header() {
    return require('./views/Header').default;
  },
  get HeaderTitle() {
    return require('./views/HeaderTitle').default;
  },
  get HeaderBackButton() {
    return require('./views/HeaderBackButton').default;
  },

  // DrawerView
  get DrawerView() {
    return require('./views/Drawer/DrawerView').default;
  },
  get DrawerItems() {
    return require('./views/Drawer/DrawerNavigatorItems').default;
  },

  // TabView
  get TabView() {
    return require('./views/TabView/TabView').default;
  },
  get TabBarTop() {
    return require('./views/TabView/TabBarTop').default;
  },
  get TabBarBottom() {
    return require('./views/TabView/TabBarBottom').default;
  },

  // HOCs
  get withNavigation() {
    return require('./views/withNavigation').default;
  }
};


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import qs from 'qs';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';
import { Row, Col } from 'react-bootstrap';
import _ from 'lodash/fp';
import moment from 'moment';

import PTPanel from '../../ui-elements/PTPanel/PTPanel';
import PatientsChart from '../../containers/PatientsChart/PatientsChart';

import { fetchPatientOnSearch } from '../../../utils/HOCs/fetch-patient-on-search.utils';
import { fetchClinicalQuerySearchRequest } from '../../../ducks/fetch-clinical-query-search.duck';
import { fetchBasicPatientSearchRequest } from '../../../ducks/fetch-basic-patient-search.duck';
import { patientsSelector, clinicalQuerySearchSelector } from './selectors';
import { patientAgeRangesForClinicalSearch } from '../../../config/patients.constants';
import { clientUrls } from '../../../config/client-urls.constants';

const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ fetchClinicalQuerySearchRequest, fetchBasicPatientSearchRequest }, dispatch) });

@connect(patientsSelector, mapDispatchToProps)
@connect(clinicalQuerySearchSelector)
@lifecycle(fetchPatientOnSearch)
class SearchReport extends PureComponent {
  static contextTypes = {
    router: PropTypes.shape({
      history: PropTypes.object,
    }),
  };

  state = {
    searchResult: '',
  };

  componentDidMount() {
    this.getSearchParams(this.props.clinicalQuerySearch);
  }

  componentWillReceiveProps(nextProps) {
    this.getSearchParams(nextProps.clinicalQuerySearch);
  }

  getSearchParams = (clinicalQuerySearch) => {
    const { router } = this.context;
    const searchString = router.history.location.search.replace('?', '');

    let params = {};
    let paramsText = '';
    const paramsArr = [];

    if (!_.isEmpty(searchString) && !_.isEmpty(clinicalQuerySearch)) {
      params = JSON.parse(qs.parse(searchString).searchString);
    } else {
      this.setState({ searchResult: '' });
    }

    if (params.type) {
      paramsArr.push({
        key: 'Search Type',
        value: params.type,
      });
    }

    if (params.queryContains && params.queryText) {
      paramsArr.push({
        key: 'Search Query',
        value: `contains "${params.queryText}"`,
      });
    }

    if ((params.minValue || params.minValue === 0) && params.maxValue) {
      paramsArr.push({
        key: 'Age Range',
        value: `${params.minValue}-${params.maxValue}`,
      });
    } else if (params.dateOfBirth) {
      paramsArr.push({
        key: 'Date of Birth',
        value: moment(params.dateOfBirth).format('DD-MMM-YYYY'),
      });
    }

    if (params.sexFemale || params.sexMale) {
      let genderText = '';

      if (params.sexFemale && params.sexMale) {
        genderText = 'All';
      } else if (params.sexFemale) {
        genderText = 'Female';
      } else {
        genderText = 'Male';
      }

      paramsArr.push({
        key: 'Gender',
        value: genderText,
      });
    }

    for (let i = 0; i < paramsArr.length; i++) {
      if (i !== 0) {
        paramsText += ', ';
      }

      paramsText += `${paramsArr[i].key}: ${paramsArr[i].value}`;
    }

    if (paramsText.length) {
      this.setState({ searchResult: `(${paramsText})` });
    } else {
      this.setState({ searchResult: '' });
    }
  };

  handleBarClick = (data) => {
    const { searchResult } = this.state;
    this.context.router.history.push({
      pathname: `${clientUrls.PATIENTS}`,
      state: { data, searchResult },
    });
  };

  render() {
    const { patientsByAge, clinicalQuerySearch } = this.props;
    const { searchResult } = this.state;
    // TODO It is necessary to send data from the backend about the patient with his age
    const isChartsDataReceived = patientsByAge.map(_.size).reduce((a, b) => a + b) > 0;
    return (

      <Row>
        <Col xs={12}>
          <PTPanel className="col-xs-12" classNameForPanel={`${(!_.isEmpty(searchResult) && !_.isEmpty(clinicalQuerySearch))} ? 'mainPagePanel': ''`} header={
{` Patients Sorted By Age ${searchResult}`}
}>
            { (!_.isEmpty(searchResult) && !_.isEmpty(clinicalQuerySearch)) ? <PatientsChart
              title="Found Patients By Clinical Query"
              subTitle={`Clinical Query: ${searchResult}`}
              patients={patientsByAge}
              labels={patientAgeRangesForClinicalSearch}
              borderColor="rgba(126, 41, 205,1)"
              backgroundColor="rgba(126, 41, 205,0.3)"
              isChartsDataReceived={isChartsDataReceived}
              onBarClick={this.handleBarClick}
              isClinicalQueryChart
            /> :
There are no results that match your search criteria
 }
          </PTPanel>
        </Col>
      </Row>

)
  }
}

export default SearchReport;


text:
RSpec.shared_examples "an object that cannot be streamable" do
  it { is_expected.to_not be_streamable }
  its(:can_be_streamable?) { is_expected.to be false }
end

RSpec.shared_examples "an object that can be streamable" do
  it { is_expected.to_not be_streamable }
  its(:can_be_streamable?) { is_expected.to be true }

  describe "when streamable media is present" do
    before {
      subject.add_file(fixture_file_upload('bird.jpg', 'image/jpeg'), 'streamableMedia')
      subject.save!
    }
    specify {
      expect(subject).to be_streamable
      expect(subject.streamable_media_type).to eq 'image/jpeg'
      expect(subject.streamable_media_path).to be_present
      expect(subject.streamable_media_path).to eq subject.streamableMedia.file_path
      expect(subject.streamable_media_extension).to eq 'jpeg'
    }
  end
end


text:
select count(*)
from user_accounts


text:
export var errorCodes = {
    success: 0,
    unknownError: 1,
    couldNotListen: 2,
}

export function exit(code = errorCodes.success) {
    if (code == errorCodes.couldNotListen) {
        console.log('here')
        console.error("Could not listen on specified port");
    }
    process.exit(code);
}


text:
import pytest
from pytest import approx
import time
from fakeredis import FakeStrictRedis

from celery_once.backends.redis import parse_url, Redis
from celery_once.tasks import AlreadyQueued
from redis.lock import Lock as RedisLock

def test_parse_redis_details_tcp_default_args():
    details = parse_url('redis://localhost:6379/')
    assert details == {'host': 'localhost', 'port': 6379}

def test_parse_url_tcp_with_db():
    details = parse_url('redis://localhost:6379/3')
    assert details == {'host': 'localhost', 'port': 6379, 'db': 3}

def test_parse_url_tcp_no_port():
    details = parse_url('redis://localhost')
    assert details == {'host': 'localhost'}

def test_parse_url_tcp_with_password():
    details = parse_url('redis://:ohai@localhost:6379')
    assert details == {'host': 'localhost', 'port': 6379, 'password': 'ohai'}

def test_parse_url_unix_sock_no_options():
    details = parse_url('redis+socket:///var/run/redis/redis.sock')
    assert details == {'unix_socket_path': '/var/run/redis/redis.sock'}

def test_parse_url_unix_sock_with_options():
    details = parse_url('redis+socket:///var/run/redis/redis.sock?db=2&socket_timeout=2')
    assert details == {
        'unix_socket_path': '/var/run/redis/redis.sock',
        'db': 2,
        'socket_timeout': 2.0
    }

def test_parse_url_with_ssl():
    details = parse_url('rediss://localhost:6379/3')
    assert details == {'host': 'localhost', 'port': 6379, 'db': 3, 'ssl': True}

def test_parse_unsupported_url():
    with pytest.raises(ValueError):
        parse_url('amqp://guest:guest@localhost:5672/potato')

@pytest.fixture()
def redis(monkeypatch):
    fake_redis = FakeStrictRedis()
    fake_redis.flushall()
    monkeypatch.setattr("celery_once.backends.redis.Redis.redis", fake_redis)
    return fake_redis

@pytest.fixture()
def backend():
    backend = Redis({'url': "redis://localhost:1337"})
    return backend

def test_redis_raise_or_lock(redis, backend):
    assert redis.get("test") is None
    backend.raise_or_lock(key="test", timeout=60)
    assert redis.get("test") is not None

def test_redis_raise_or_lock_locked(redis, backend):
    # Set to expire in 30 seconds!
    lock = RedisLock(redis, "test", timeout=30)
    lock.acquire()

    with pytest.raises(AlreadyQueued) as e:
        backend.raise_or_lock(key="test", timeout=60)

    assert e.value.countdown == approx(30.0, rel=0.1)
    assert "Expires in" in e.value.message

def test_redis_raise_or_lock_locked_and_expired(redis, backend):
    lock = RedisLock(redis, "test", timeout=1)
    lock.acquire()
    time.sleep(1)  # wait for lock to expire

    backend.raise_or_lock(key="test", timeout=60)
    assert redis.get("test") is not None

def test_redis_clear_lock(redis, backend):
    redis.set("test", 1326499200 + 30)
    backend.clear_lock("test")
    assert redis.get("test") is None

def test_redis_cached_property(mocker, monkeypatch):
    # Remove any side effect previous tests could have had
    monkeypatch.setattr('celery_once.backends.redis.redis', None)
    mock_parse = mocker.patch('celery_once.backends.redis.parse_url')
    mock_parse.return_value = {
        'host': "localhost"
    }
    # Despite the class being inited twice, should only setup once.
    Redis({
        'url': "redis://localhost:1337"
    })
    Redis({})
    assert mock_parse.call_count == 1