text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: anuraag@google.com (Anuraag Agrawal)
// Author: tibell@google.com (Johan Tibell)

#include <google/protobuf/pyext/repeated_scalar_container.h>

#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif

#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/message.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>

#if PY_MAJOR_VERSION >= 3
  #define PyInt_FromLong PyLong_FromLong
  #if PY_VERSION_HEX < 0x03030000
    #error "Python 3.0 - 3.2 are not supported."
  #else
  #define PyString_AsString(ob) \
    (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
  #endif
#endif

namespace google {
namespace protobuf {
namespace python {

namespace repeated_scalar_container {

static int InternalAssignRepeatedField(
    RepeatedScalarContainer* self, PyObject* list) {
  self->message->GetReflection()->ClearField(self->message,
                                             self->parent_field_descriptor);
  for (Py_ssize_t i = 0; i < PyList_GET_SIZE(list); ++i) {
    PyObject* value = PyList_GET_ITEM(list, i);
    if (ScopedPyObjectPtr(Append(self, value)) == NULL) {
      return -1;
    }
  }
  return 0;
}

static Py_ssize_t Len(RepeatedScalarContainer* self) {
  Message* message = self->message;
  return message->GetReflection()->FieldSize(*message,
                                             self->parent_field_descriptor);
}

static int AssignItem(RepeatedScalarContainer* self,
                      Py_ssize_t index,
                      PyObject* arg) {
  cmessage::AssureWritable(self->parent);
  Message* message = self->message;
  const FieldDescriptor* field_descriptor = self->parent_field_descriptor;

  const Reflection* reflection = message->GetReflection();
  int field_size = reflection->FieldSize(*message, field_descriptor);
  if (index < 0) {
    index = field_size + index;
  }
  if (index < 0 || index >= field_size) {
    PyErr_Format(PyExc_IndexError,
                 "list assignment index (%d) out of range",
                 static_cast<int>(index));
    return -1;
  }

  if (arg == NULL) {
    ScopedPyObjectPtr py_index(PyLong_FromLong(index));
    return cmessage::InternalDeleteRepeatedField(self->parent, field_descriptor,
                                                 py_index.get(), NULL);
  }

  if (PySequence_Check(arg) && !(PyBytes_Check(arg) || PyUnicode_Check(arg))) {
    PyErr_SetString(PyExc_TypeError, "Value must be scalar");
    return -1;
  }

  switch (field_descriptor->cpp_type()) {
    case FieldDescriptor::CPPTYPE_INT32: {
      GOOGLE_CHECK_GET_INT32(arg, value, -1);
      reflection->SetRepeatedInt32(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_INT64: {
      GOOGLE_CHECK_GET_INT64(arg, value, -1);
      reflection->SetRepeatedInt64(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT32: {
      GOOGLE_CHECK_GET_UINT32(arg, value, -1);
      reflection->SetRepeatedUInt32(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT64: {
      GOOGLE_CHECK_GET_UINT64(arg, value, -1);
      reflection->SetRepeatedUInt64(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_FLOAT: {
      GOOGLE_CHECK_GET_FLOAT(arg, value, -1);
      reflection->SetRepeatedFloat(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_DOUBLE: {
      GOOGLE_CHECK_GET_DOUBLE(arg, value, -1);
      reflection->SetRepeatedDouble(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_BOOL: {
      GOOGLE_CHECK_GET_BOOL(arg, value, -1);
      reflection->SetRepeatedBool(message, field_descriptor, index, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_STRING: {
      if (!CheckAndSetString(
          arg, message, field_descriptor, reflection, false, index)) {
        return -1;
      }
      break;
    }
    case FieldDescriptor::CPPTYPE_ENUM: {
      GOOGLE_CHECK_GET_INT32(arg, value, -1);
      if (reflection->SupportsUnknownEnumValues()) {
        reflection->SetRepeatedEnumValue(message, field_descriptor, index,
                                         value);
      } else {
        const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
        const EnumValueDescriptor* enum_value =
            enum_descriptor->FindValueByNumber(value);
        if (enum_value != NULL) {
          reflection->SetRepeatedEnum(message, field_descriptor, index,
                                      enum_value);
        } else {
          ScopedPyObjectPtr s(PyObject_Str(arg));
          if (s != NULL) {
            PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
                         PyString_AsString(s.get()));
          }
          return -1;
        }
      }
      break;
    }
    default:
      PyErr_Format(
          PyExc_SystemError, "Adding value to a field of unknown type %d",
          field_descriptor->cpp_type());
      return -1;
  }
  return 0;
}

static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
  Message* message = self->message;
  const FieldDescriptor* field_descriptor = self->parent_field_descriptor;
  const Reflection* reflection = message->GetReflection();

  int field_size = reflection->FieldSize(*message, field_descriptor);
  if (index < 0) {
    index = field_size + index;
  }
  if (index < 0 || index >= field_size) {
    PyErr_Format(PyExc_IndexError,
                 "list index (%zd) out of range",
                 index);
    return NULL;
  }

  PyObject* result = NULL;
  switch (field_descriptor->cpp_type()) {
    case FieldDescriptor::CPPTYPE_INT32: {
      int32 value = reflection->GetRepeatedInt32(
          *message, field_descriptor, index);
      result = PyInt_FromLong(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_INT64: {
      int64 value = reflection->GetRepeatedInt64(
          *message, field_descriptor, index);
      result = PyLong_FromLongLong(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT32: {
      uint32 value = reflection->GetRepeatedUInt32(
          *message, field_descriptor, index);
      result = PyLong_FromLongLong(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT64: {
      uint64 value = reflection->GetRepeatedUInt64(
          *message, field_descriptor, index);
      result = PyLong_FromUnsignedLongLong(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_FLOAT: {
      float value = reflection->GetRepeatedFloat(
          *message, field_descriptor, index);
      result = PyFloat_FromDouble(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_DOUBLE: {
      double value = reflection->GetRepeatedDouble(
          *message, field_descriptor, index);
      result = PyFloat_FromDouble(value);
      break;
    }
    case FieldDescriptor::CPPTYPE_BOOL: {
      bool value = reflection->GetRepeatedBool(
          *message, field_descriptor, index);
      result = PyBool_FromLong(value ? 1 : 0);
      break;
    }
    case FieldDescriptor::CPPTYPE_ENUM: {
      const EnumValueDescriptor* enum_value =
          message->GetReflection()->GetRepeatedEnum(
              *message, field_descriptor, index);
      result = PyInt_FromLong(enum_value->number());
      break;
    }
    case FieldDescriptor::CPPTYPE_STRING: {
      string value = reflection->GetRepeatedString(
          *message, field_descriptor, index);
      result = ToStringObject(field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_MESSAGE: {
      PyObject* py_cmsg = PyObject_CallObject(reinterpret_cast<PyObject*>(
          &CMessage_Type), NULL);
      if (py_cmsg == NULL) {
        return NULL;
      }
      CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
      const Message& msg = reflection->GetRepeatedMessage(
          *message, field_descriptor, index);
      cmsg->owner = self->owner;
      cmsg->parent = self->parent;
      cmsg->message = const_cast<Message*>(&msg);
      cmsg->read_only = false;
      result = reinterpret_cast<PyObject*>(py_cmsg);
      break;
    }
    default:
      PyErr_Format(
          PyExc_SystemError,
          "Getting value from a repeated field of unknown type %d",
          field_descriptor->cpp_type());
  }

  return result;
}

static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
  Py_ssize_t from;
  Py_ssize_t to;
  Py_ssize_t step;
  Py_ssize_t length;
  Py_ssize_t slicelength;
  bool return_list = false;
#if PY_MAJOR_VERSION < 3
  if (PyInt_Check(slice)) {
    from = to = PyInt_AsLong(slice);
  } else  // NOLINT
#endif
  if (PyLong_Check(slice)) {
    from = to = PyLong_AsLong(slice);
  } else if (PySlice_Check(slice)) {
    length = Len(self);
#if PY_MAJOR_VERSION >= 3
    if (PySlice_GetIndicesEx(slice,
#else
    if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
#endif
                             length, &from, &to, &step, &slicelength) == -1) {
      return NULL;
    }
    return_list = true;
  } else {
    PyErr_SetString(PyExc_TypeError, "list indices must be integers");
    return NULL;
  }

  if (!return_list) {
    return Item(self, from);
  }

  PyObject* list = PyList_New(0);
  if (list == NULL) {
    return NULL;
  }
  if (from <= to) {
    if (step < 0) {
      return list;
    }
    for (Py_ssize_t index = from; index < to; index += step) {
      if (index < 0 || index >= length) {
        break;
      }
      ScopedPyObjectPtr s(Item(self, index));
      PyList_Append(list, s.get());
    }
  } else {
    if (step > 0) {
      return list;
    }
    for (Py_ssize_t index = from; index > to; index += step) {
      if (index < 0 || index >= length) {
        break;
      }
      ScopedPyObjectPtr s(Item(self, index));
      PyList_Append(list, s.get());
    }
  }
  return list;
}

PyObject* Append(RepeatedScalarContainer* self, PyObject* item) {
  cmessage::AssureWritable(self->parent);
  Message* message = self->message;
  const FieldDescriptor* field_descriptor = self->parent_field_descriptor;

  const Reflection* reflection = message->GetReflection();
  switch (field_descriptor->cpp_type()) {
    case FieldDescriptor::CPPTYPE_INT32: {
      GOOGLE_CHECK_GET_INT32(item, value, NULL);
      reflection->AddInt32(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_INT64: {
      GOOGLE_CHECK_GET_INT64(item, value, NULL);
      reflection->AddInt64(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT32: {
      GOOGLE_CHECK_GET_UINT32(item, value, NULL);
      reflection->AddUInt32(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_UINT64: {
      GOOGLE_CHECK_GET_UINT64(item, value, NULL);
      reflection->AddUInt64(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_FLOAT: {
      GOOGLE_CHECK_GET_FLOAT(item, value, NULL);
      reflection->AddFloat(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_DOUBLE: {
      GOOGLE_CHECK_GET_DOUBLE(item, value, NULL);
      reflection->AddDouble(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_BOOL: {
      GOOGLE_CHECK_GET_BOOL(item, value, NULL);
      reflection->AddBool(message, field_descriptor, value);
      break;
    }
    case FieldDescriptor::CPPTYPE_STRING: {
      if (!CheckAndSetString(
          item, message, field_descriptor, reflection, true, -1)) {
        return NULL;
      }
      break;
    }
    case FieldDescriptor::CPPTYPE_ENUM: {
      GOOGLE_CHECK_GET_INT32(item, value, NULL);
      if (reflection->SupportsUnknownEnumValues()) {
        reflection->AddEnumValue(message, field_descriptor, value);
      } else {
        const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
        const EnumValueDescriptor* enum_value =
            enum_descriptor->FindValueByNumber(value);
        if (enum_value != NULL) {
          reflection->AddEnum(message, field_descriptor, enum_value);
        } else {
          ScopedPyObjectPtr s(PyObject_Str(item));
          if (s != NULL) {
            PyErr_Format(PyExc_ValueError, "Unknown enum value: %s",
                         PyString_AsString(s.get()));
          }
          return NULL;
        }
      }
      break;
    }
    default:
      PyErr_Format(
          PyExc_SystemError, "Adding value to a field of unknown type %d",
          field_descriptor->cpp_type());
      return NULL;
  }

  Py_RETURN_NONE;
}

static int AssSubscript(RepeatedScalarContainer* self,
                        PyObject* slice,
                        PyObject* value) {
  Py_ssize_t from;
  Py_ssize_t to;
  Py_ssize_t step;
  Py_ssize_t length;
  Py_ssize_t slicelength;
  bool create_list = false;

  cmessage::AssureWritable(self->parent);
  Message* message = self->message;
  const FieldDescriptor* field_descriptor =
      self->parent_field_descriptor;

#if PY_MAJOR_VERSION < 3
  if (PyInt_Check(slice)) {
    from = to = PyInt_AsLong(slice);
  } else
#endif
  if (PyLong_Check(slice)) {
    from = to = PyLong_AsLong(slice);
  } else if (PySlice_Check(slice)) {
    const Reflection* reflection = message->GetReflection();
    length = reflection->FieldSize(*message, field_descriptor);
#if PY_MAJOR_VERSION >= 3
    if (PySlice_GetIndicesEx(slice,
#else
    if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
#endif
                             length, &from, &to, &step, &slicelength) == -1) {
      return -1;
    }
    create_list = true;
  } else {
    PyErr_SetString(PyExc_TypeError, "list indices must be integers");
    return -1;
  }

  if (value == NULL) {
    return cmessage::InternalDeleteRepeatedField(
        self->parent, field_descriptor, slice, NULL);
  }

  if (!create_list) {
    return AssignItem(self, from, value);
  }

  ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  if (full_slice == NULL) {
    return -1;
  }
  ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
  if (new_list == NULL) {
    return -1;
  }
  if (PySequence_SetSlice(new_list.get(), from, to, value) < 0) {
    return -1;
  }

  return InternalAssignRepeatedField(self, new_list.get());
}

PyObject* Extend(RepeatedScalarContainer* self, PyObject* value) {
  cmessage::AssureWritable(self->parent);

  // TODO(ptucker): Deprecate this behavior. b/18413862
  if (value == Py_None) {
    Py_RETURN_NONE;
  }
  if ((Py_TYPE(value)->tp_as_sequence == NULL) && PyObject_Not(value)) {
    Py_RETURN_NONE;
  }

  ScopedPyObjectPtr iter(PyObject_GetIter(value));
  if (iter == NULL) {
    PyErr_SetString(PyExc_TypeError, "Value must be iterable");
    return NULL;
  }
  ScopedPyObjectPtr next;
  while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
    if (ScopedPyObjectPtr(Append(self, next.get())) == NULL) {
      return NULL;
    }
  }
  if (PyErr_Occurred()) {
    return NULL;
  }
  Py_RETURN_NONE;
}

static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) {
  Py_ssize_t index;
  PyObject* value;
  if (!PyArg_ParseTuple(args, "lO", &index, &value)) {
    return NULL;
  }
  ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  ScopedPyObjectPtr new_list(Subscript(self, full_slice.get()));
  if (PyList_Insert(new_list.get(), index, value) < 0) {
    return NULL;
  }
  int ret = InternalAssignRepeatedField(self, new_list.get());
  if (ret < 0) {
    return NULL;
  }
  Py_RETURN_NONE;
}

static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) {
  Py_ssize_t match_index = -1;
  for (Py_ssize_t i = 0; i < Len(self); ++i) {
    ScopedPyObjectPtr elem(Item(self, i));
    if (PyObject_RichCompareBool(elem.get(), value, Py_EQ)) {
      match_index = i;
      break;
    }
  }
  if (match_index == -1) {
    PyErr_SetString(PyExc_ValueError, "remove(x): x not in container");
    return NULL;
  }
  if (AssignItem(self, match_index, NULL) < 0) {
    return NULL;
  }
  Py_RETURN_NONE;
}

static PyObject* RichCompare(RepeatedScalarContainer* self,
                             PyObject* other,
                             int opid) {
  if (opid != Py_EQ && opid != Py_NE) {
    Py_INCREF(Py_NotImplemented);
    return Py_NotImplemented;
  }

  // Copy the contents of this repeated scalar container, and other if it is
  // also a repeated scalar container, into Python lists so we can delegate
  // to the list's compare method.

  ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  if (full_slice == NULL) {
    return NULL;
  }

  ScopedPyObjectPtr other_list_deleter;
  if (PyObject_TypeCheck(other, &RepeatedScalarContainer_Type)) {
    other_list_deleter.reset(Subscript(
        reinterpret_cast<RepeatedScalarContainer*>(other), full_slice.get()));
    other = other_list_deleter.get();
  }

  ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
  if (list == NULL) {
    return NULL;
  }
  return PyObject_RichCompare(list.get(), other, opid);
}

PyObject* Reduce(RepeatedScalarContainer* unused_self) {
  PyErr_Format(
      PickleError_class,
      "can't pickle repeated message fields, convert to list first");
  return NULL;
}

static PyObject* Sort(RepeatedScalarContainer* self,
                      PyObject* args,
                      PyObject* kwds) {
  // Support the old sort_function argument for backwards
  // compatibility.
  if (kwds != NULL) {
    PyObject* sort_func = PyDict_GetItemString(kwds, "sort_function");
    if (sort_func != NULL) {
      // Must set before deleting as sort_func is a borrowed reference
      // and kwds might be the only thing keeping it alive.
      if (PyDict_SetItemString(kwds, "cmp", sort_func) == -1)
        return NULL;
      if (PyDict_DelItemString(kwds, "sort_function") == -1)
        return NULL;
    }
  }

  ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  if (full_slice == NULL) {
    return NULL;
  }
  ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
  if (list == NULL) {
    return NULL;
  }
  ScopedPyObjectPtr m(PyObject_GetAttrString(list.get(), "sort"));
  if (m == NULL) {
    return NULL;
  }
  ScopedPyObjectPtr res(PyObject_Call(m.get(), args, kwds));
  if (res == NULL) {
    return NULL;
  }
  int ret = InternalAssignRepeatedField(self, list.get());
  if (ret < 0) {
    return NULL;
  }
  Py_RETURN_NONE;
}

static PyObject* Pop(RepeatedScalarContainer* self,
                     PyObject* args) {
  Py_ssize_t index = -1;
  if (!PyArg_ParseTuple(args, "|n", &index)) {
    return NULL;
  }
  PyObject* item = Item(self, index);
  if (item == NULL) {
    PyErr_Format(PyExc_IndexError,
                 "list index (%zd) out of range",
                 index);
    return NULL;
  }
  if (AssignItem(self, index, NULL) < 0) {
    return NULL;
  }
  return item;
}

// The private constructor of RepeatedScalarContainer objects.
PyObject *NewContainer(
    CMessage* parent, const FieldDescriptor* parent_field_descriptor) {
  if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
    return NULL;
  }

  RepeatedScalarContainer* self = reinterpret_cast<RepeatedScalarContainer*>(
      PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0));
  if (self == NULL) {
    return NULL;
  }

  self->message = parent->message;
  self->parent = parent;
  self->parent_field_descriptor = parent_field_descriptor;
  self->owner = parent->owner;

  return reinterpret_cast<PyObject*>(self);
}

// Initializes the underlying Message object of "to" so it becomes a new parent
// repeated scalar, and copies all the values from "from" to it. A child scalar
// container can be released by passing it as both from and to (e.g. making it
// the recipient of the new parent message and copying the values from itself).
static int InitializeAndCopyToParentContainer(
    RepeatedScalarContainer* from,
    RepeatedScalarContainer* to) {
  ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
  if (full_slice == NULL) {
    return -1;
  }
  ScopedPyObjectPtr values(Subscript(from, full_slice.get()));
  if (values == NULL) {
    return -1;
  }
  Message* new_message = from->message->New();
  to->parent = NULL;
  to->parent_field_descriptor = from->parent_field_descriptor;
  to->message = new_message;
  to->owner.reset(new_message);
  if (InternalAssignRepeatedField(to, values.get()) < 0) {
    return -1;
  }
  return 0;
}

int Release(RepeatedScalarContainer* self) {
  return InitializeAndCopyToParentContainer(self, self);
}

PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) {
  RepeatedScalarContainer* clone = reinterpret_cast<RepeatedScalarContainer*>(
      PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0));
  if (clone == NULL) {
    return NULL;
  }

  if (InitializeAndCopyToParentContainer(self, clone) < 0) {
    Py_DECREF(clone);
    return NULL;
  }
  return reinterpret_cast<PyObject*>(clone);
}

static void Dealloc(RepeatedScalarContainer* self) {
  self->owner.reset();
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

void SetOwner(RepeatedScalarContainer* self,
              const shared_ptr<Message>& new_owner) {
  self->owner = new_owner;
}

static PySequenceMethods SqMethods = {
  (lenfunc)Len,           /* sq_length */
  0, /* sq_concat */
  0, /* sq_repeat */
  (ssizeargfunc)Item, /* sq_item */
  0, /* sq_slice */
  (ssizeobjargproc)AssignItem /* sq_ass_item */
};

static PyMappingMethods MpMethods = {
  (lenfunc)Len,               /* mp_length */
  (binaryfunc)Subscript,      /* mp_subscript */
  (objobjargproc)AssSubscript, /* mp_ass_subscript */
};

static PyMethodDef Methods[] = {
  { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
    "Makes a deep copy of the class." },
  { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
    "Outputs picklable representation of the repeated field." },
  { "append", (PyCFunction)Append, METH_O,
    "Appends an object to the repeated container." },
  { "extend", (PyCFunction)Extend, METH_O,
    "Appends objects to the repeated container." },
  { "insert", (PyCFunction)Insert, METH_VARARGS,
    "Appends objects to the repeated container." },
  { "pop", (PyCFunction)Pop, METH_VARARGS,
    "Removes an object from the repeated container and returns it." },
  { "remove", (PyCFunction)Remove, METH_O,
    "Removes an object from the repeated container." },
  { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
    "Sorts the repeated container."},
  { NULL, NULL }
};

}  // namespace repeated_scalar_container

PyTypeObject RepeatedScalarContainer_Type = {
  PyVarObject_HEAD_INIT(&PyType_Type, 0)
  FULL_MODULE_NAME ".RepeatedScalarContainer",  // tp_name
  sizeof(RepeatedScalarContainer),     // tp_basicsize
  0,                                   //  tp_itemsize
  (destructor)repeated_scalar_container::Dealloc,  //  tp_dealloc
  0,                                   //  tp_print
  0,                                   //  tp_getattr
  0,                                   //  tp_setattr
  0,                                   //  tp_compare
  0,                                   //  tp_repr
  0,                                   //  tp_as_number
  &repeated_scalar_container::SqMethods,   //  tp_as_sequence
  &repeated_scalar_container::MpMethods,   //  tp_as_mapping
  PyObject_HashNotImplemented,         //  tp_hash
  0,                                   //  tp_call
  0,                                   //  tp_str
  0,                                   //  tp_getattro
  0,                                   //  tp_setattro
  0,                                   //  tp_as_buffer
  Py_TPFLAGS_DEFAULT,                  //  tp_flags
  "A Repeated scalar container",       //  tp_doc
  0,                                   //  tp_traverse
  0,                                   //  tp_clear
  (richcmpfunc)repeated_scalar_container::RichCompare,  //  tp_richcompare
  0,                                   //  tp_weaklistoffset
  0,                                   //  tp_iter
  0,                                   //  tp_iternext
  repeated_scalar_container::Methods,      //  tp_methods
  0,                                   //  tp_members
  0,                                   //  tp_getset
  0,                                   //  tp_base
  0,                                   //  tp_dict
  0,                                   //  tp_descr_get
  0,                                   //  tp_descr_set
  0,                                   //  tp_dictoffset
  0,                                   //  tp_init
};

}  // namespace python
}  // namespace protobuf
}  // namespace google


text:
package com.alibaba.jstorm.message.netty;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.Config;
import backtype.storm.messaging.IConnection;
import backtype.storm.messaging.TaskMessage;
import backtype.storm.utils.DisruptorQueue;
import backtype.storm.utils.Utils;

import com.alibaba.jstorm.utils.JStormUtils;
import com.alibaba.jstorm.client.ConfigExtension;

class NettyServer implements IConnection {
    private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class);
    @SuppressWarnings("rawtypes")
    Map storm_conf;
    int port;

    // private LinkedBlockingQueue message_queue;
    volatile ChannelGroup allChannels = new DefaultChannelGroup("jstorm-server");
    final ChannelFactory factory;
    final ServerBootstrap bootstrap;

    // ayncBatch is only one solution, so directly set it as true
    private final boolean isSyncMode;

    private ConcurrentHashMap<Integer, DisruptorQueue> deserializeQueues;

    @SuppressWarnings("rawtypes")
    NettyServer(Map storm_conf, int port, boolean isSyncMode, ConcurrentHashMap<Integer, DisruptorQueue> deserializeQueues) {
        this.storm_conf = storm_conf;
        this.port = port;
        this.isSyncMode = isSyncMode;
        this.deserializeQueues = deserializeQueues;

        // Configure the server.
        int buffer_size = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE));
        int maxWorkers = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_SERVER_WORKER_THREADS));

        // asyncBatch = ConfigExtension.isNettyTransferAsyncBatch(storm_conf);

        ThreadFactory bossFactory = new NettyRenameThreadFactory("server" + "-boss");
        ThreadFactory workerFactory = new NettyRenameThreadFactory("server" + "-worker");
        if (maxWorkers > 0) {
            factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), maxWorkers);
        } else {
            factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory));
        }

        bootstrap = new ServerBootstrap(factory);
        bootstrap.setOption("reuserAddress", true);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.receiveBufferSize", buffer_size);
        bootstrap.setOption("child.keepAlive", true);

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new StormServerPipelineFactory(this, storm_conf));

        // Bind and start to accept incoming connections.
        Channel channel = bootstrap.bind(new InetSocketAddress(port));
        allChannels.add(channel);

        LOG.info("Successfull bind {}, buffer_size:{}, maxWorkers:{}", port, buffer_size, maxWorkers);
    }

    @Override
    public void registerQueue(Integer taskId, DisruptorQueue recvQueu) {
        deserializeQueues.put(taskId, recvQueu);
    }

    /**
     * enqueue a received message
     *
     * @param message
     * @throws InterruptedException
     */
    public void enqueue(TaskMessage message) {

        int task = message.task();

        DisruptorQueue queue = deserializeQueues.get(task);
        if (queue == null) {
            LOG.debug("Received invalid message directed at port " + task + ". Dropping...");
            return;
        }

        queue.publish(message.message());
    }

    /**
     * fetch a message from message queue synchronously (flags != 1) or asynchronously (flags==1)
     */
    public Object recv(Integer taskId, int flags) {
        try {
            DisruptorQueue recvQueue = deserializeQueues.get(taskId);
            if ((flags & 0x01) == 0x01) {
                return recvQueue.poll();
                // non-blocking

            } else {
                return recvQueue.take();

            }

        } catch (Exception e) {
            LOG.warn("Occur unexception ", e);
            return null;
        }

    }

    /**
     * register a newly created channel
     *
     * @param channel
     */
    protected void addChannel(Channel channel) {
        allChannels.add(channel);
    }

    /**
     * close a channel
     *
     * @param channel
     */
    protected void closeChannel(Channel channel) {
        MessageDecoder.removeTransmitHistogram(channel);
        channel.close().awaitUninterruptibly();
        allChannels.remove(channel);
    }

    /**
     * close all channels, and release resources
     */
    public synchronized void close() {
        LOG.info("Begin to shutdown NettyServer");
        if (allChannels != null) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        // await(5, TimeUnit.SECONDS)
                        // sometimes allChannels.close() will block the exit
                        // thread
                        allChannels.close().await(1, TimeUnit.SECONDS);
                        LOG.info("Successfully close all channel");
                        factory.releaseExternalResources();
                    } catch (Exception e) {

                    }
                    allChannels = null;
                }
            }).start();

            JStormUtils.sleepMs(1 * 1000);
        }
        LOG.info("Successfully shutdown NettyServer");
    }

    @Override
    public void send(List<TaskMessage> messages) {
        throw new UnsupportedOperationException("Server connection should not send any messages");
    }

    @Override
    public void send(TaskMessage message) {
        throw new UnsupportedOperationException("Server connection should not send any messages");
    }

    @Override
    public boolean isClosed() {
        // TODO Auto-generated method stub
        return false;
    }

    public boolean isSyncMode() {
        return isSyncMode;
    }

    @Override
    public boolean available() {
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.nulabinc.zxcvbn.matchers;

import com.nulabinc.zxcvbn.io.Resource;

public class AlignedKeyboardLoader extends KeyboardLoader {

    public AlignedKeyboardLoader(final String name, final Resource inputStreamSource) {
        super(name, inputStreamSource);
    }

    @Override
    protected Keyboard.AdjacentGraphBuilder buildAdjacentGraphBuilder(final String layout) {
        return new AlignedAdjacentGraphBuilder(layout);
    }

}


text:
import * as React from "react";
import * as ReactDOM from "react-dom";
import {Provider} from "react-redux";
import Todoist from "./containers/Todoist";

import configureStore from "./store";

ReactDOM.render(
  <Provider store={configureStore()}>
    <Todoist />
  </Provider>
  , document.getElementById("todoist-configuration"),
);


text:
package ru.nivanov.xmlOptimizer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Nikolay Ivanov on 12.09.2017.
 */
class XmlCreator {
    private final String path;

    /**
     * Constructor.
     * @param path for creating xml.
     */
    XmlCreator(String path) {
        this.path = path;
    }

    /**
     * Generating xml file.
     * @param conn ..
     * @return ..
     */
    String generateXML(Connection conn) {

        Document doc = null;
        Statement st;
        ResultSet rs = null;

        try {
            st = conn.createStatement();
            rs = st.executeQuery("SELECT * FROM TEST WHERE FIELD NOT NULL");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        try {
            doc = factory.newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element rootElement = doc != null ? doc.createElement("entries") : null;
        assert doc != null;
        doc.appendChild(rootElement);

        try {
            while (rs != null && rs.next()) {
                Element entry = doc.createElement("entry");
                assert rootElement != null;
                rootElement.appendChild(entry);

                Element field = doc.createElement("field");
                field.appendChild(doc.createTextNode(rs.getString(1)));
                entry.appendChild(field);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = transformerFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(this.path));

        try {
            assert transformer != null;
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return this.path;
    }
}


text:
package Alignment::Shrimp2;

use strict;
use warnings;
use File::Basename;
use CQS::PBS;
use CQS::ConfigUtils;
use CQS::SystemUtils;
use CQS::FileUtils;
use CQS::Task;
use CQS::NGSCommon;
use CQS::StringUtils;

our @ISA = qw(CQS::Task);

sub new {
  my ($class) = @_;
  my $self = $class->SUPER::new();
  $self->{_name}   = __PACKAGE__;
  $self->{_suffix} = "_srp2";
  bless $self, $class;
  return $self;
}

sub perform {
  my ( $self, $config, $section ) = @_;

  my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct, $cluster ) = $self->init_parameter( $config, $section );

  my $shrimp2_index = $config->{$section}{shrimp2_index} or die "define ${section}::shrimp2_index first";
  die "shrimp2_index ${shrimp2_index}.genome not exist" if ( !-e "${shrimp2_index}.genome" );

  my $is_mirna = $config->{$section}{is_mirna} or die "define ${section}::is_mirna first";
  my $mirna = "-M mirna" if $is_mirna or "";

  my $output_bam = $config->{$section}{output_bam} or die "define ${section}::output_bam first";

  my %raw_files = %{ get_raw_files( $config, $section, "source", ".fastq\$" ) };

  my $shfile = $self->get_task_filename( $pbs_dir, $task_name );
  open( my $sh, ">$shfile" ) or die "Cannot create $shfile";
  print $sh get_run_command($sh_direct);

  for my $sample_name ( sort keys %raw_files ) {
    my @sample_files = @{ $raw_files{$sample_name} };
    my $sampleFile   = $sample_files[0];

    my $shrimpFile = $sample_name . ".shrimp";
    my $sam_file   = $sample_name . ".sam";
    my $bam_file   = $sample_name . ".bam";

    my $pbs_file = $self->get_pbs_filename( $pbs_dir, $sample_name );
    my $pbs_name = basename($pbs_file);
    my $log      = $self->get_log_filename( $log_dir, $sample_name );

    print $sh "\$MYCMD ./$pbs_name \n";

    my $cur_dir = create_directory_or_die( $result_dir . "/$sample_name" );

    my $log_desc = $cluster->get_log_description($log);

    my $final_file = $output_bam ? $bam_file : $shrimpFile;
    my $pbs = $self->open_pbs( $pbs_file, $pbs_desc, $log_desc, $path_file, $cur_dir, $final_file );

    if ($output_bam) {
      print $pbs "gmapper -L $shrimp2_index $sampleFile $mirna $option --extra-sam-fields > $sam_file

if [ -s $sam_file ]; then
  samtools view -S -b $sam_file | samtools sort - $sample_name
  samtools index $bam_file
  samtools flagstat $bam_file > ${bam_file}.stat
fi

echo finished=`date`
";
    }
    else {
      print $pbs "gmapper -L $shrimp2_index $sampleFile $mirna $option --pretty >$shrimpFile

echo finished=`date`
";
    }

    $self->close_pbs( $pbs, $pbs_file );
  }
  close $sh;

  if ( is_linux() ) {
    chmod 0755, $shfile;
  }

  print "!!!shell file $shfile created, you can run this shell file to submit all tasks.\n";
}

sub result {
  my ( $self, $config, $section, $pattern ) = @_;

  my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct ) = $self->init_parameter( $config, $section, 0 );

  my $output_bam = $config->{$section}{output_bam} or die "define ${section}::output_bam first";

  my %raw_files = %{ get_raw_files( $config, $section, "source", ".fastq\$" ) };

  my $result = {};
  for my $sample_name ( sort keys %raw_files ) {
    my $cur_dir      = $result_dir . "/$sample_name/";
    my @result_files = ();
    if ($output_bam) {
      push( @result_files, $cur_dir . $sample_name . ".bam" );
    }
    else {
      push( @result_files, $cur_dir . $sample_name . ".shrimp" );
    }

    $result->{$sample_name} = filter_array( \@result_files, $pattern );
  }
  return $result;
}

1;


text:
{% load i18n %}
{% load lfc_tags %}

    {% trans "Files" %}

{% ifportalhasperm manage_portal %}
    {% if obj.files.all %}
        <form id="object-files-update-form"
              action="{% url lfc_update_portal_files %}"
              method="post">

                        <input type="checkbox"
                               class="select-all"
                               value="file" />

                        {% trans 'Title' %}

                        {% trans 'Description' %}

                        {% trans 'Position' %}

                        {% trans 'Manage' %}

                {% for file in obj.files.all %}

                            <input type="checkbox"
                                   class="select-file"
                                   name="delete-files"
                                   value="{{ file.id }}"
                                   style="float:left" />

                            <input type="text" name="title-{{ file.id }}" value="{{ file.title }}" />

                            {{ file.description|truncatewords_html:5|safe }}

                            <input class="position" type="text" name="position-{{ file.id }}" value="{{ file.position }}" />

                            {% if not forloop.first %}

                            {% endif %}

                            {% if not forloop.last %}

                            {% endif %}

                                <image src="{{ MEDIA_URL }}lfc/icons/disk.png"
                                       alt='{% trans "Download" %}'
                                       title='{% trans "Download" %}' />

                                <image src="{{ MEDIA_URL }}lfc/icons/edit.png"
                                       alt='{% trans "Edit" %}'
                                       title='{% trans "Edit" %}' />

                {% endfor %}

            <input class="ajax-submit"
                   type="submit" name="update" value="{% trans 'Update' %}" />
            <input class="ajax-submit"
                   type="submit" name="delete" value="{% trans 'Delete' %}" />

        </form>
    {% else %}
        {% trans 'There are no files' %}
    {% endif %}

{% trans 'Add files' %}

    <form id="files-form"
          data="{% url lfc_load_portal_files %}"
          method="post"
          enctype="multipart/form-data">

        {# {% trans 'Upload Queue' %} #}

            <input id="btnUpload"
                   type="button"
                   value='{% trans "Select Files" %}'
                   style="width: 100px; height: 22px; font-size: 8pt;" />

            <input id="btnCancel"
                   type="button"
                   value="Cancel All Uploads"
                   onclick="swfu.cancelQueue();"
                   disabled="disabled"
                   style="margin-left: 2px; font-size: 8pt; height: 29px;" />

    </form>

{% else %}
    {% if obj.files.all %}

                    {% trans 'Title' %}

                    {% trans 'Creation date' %}

            {% for file in obj.files.all %}

                        {{ file.title }}

                        {{ file.creation_date|date:"Y-m-d H:i:s" }}

            {% endfor %}

    {% else %}
        {% trans 'There are no files' %}
    {% endif %}
{% endifportalhasperm %}


text:
package org.urllib.internal;

import java.nio.charset.Charset;

public final class StandardCharsets {

  private StandardCharsets() {}

  public static final Charset US_ASCII = Charset.forName("US-ASCII");
  public static final Charset UTF_8 = Charset.forName("UTF-8");
}


text:
#pragma once
#include <aws/config/ConfigService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ConfigService
{
namespace Model
{
  enum class ConfigRuleState
  {
    NOT_SET,
    ACTIVE,
    DELETING,
    DELETING_RESULTS,
    EVALUATING
  };

namespace ConfigRuleStateMapper
{
AWS_CONFIGSERVICE_API ConfigRuleState GetConfigRuleStateForName(const Aws::String& name);

AWS_CONFIGSERVICE_API Aws::String GetNameForConfigRuleState(ConfigRuleState value);
} // namespace ConfigRuleStateMapper
} // namespace Model
} // namespace ConfigService
} // namespace Aws


text:
import RSVP from '../../lib/ext/rsvp';
import { getAdapter, setAdapter } from '../../lib/test/adapter';
import TestPromise, { getLastPromise } from '../../lib/test/promise';
import { getCurrentRunLoop } from '@ember/runloop';
import { isTesting, setTesting } from '@ember/debug';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';

const originalTestAdapter = getAdapter();
const originalTestingFlag = isTesting();

let asyncStarted = 0;
let asyncEnded = 0;

moduleFor(
  'ember-testing RSVP',
  class extends AbstractTestCase {
    constructor() {
      super();
      setTesting(true);
      setAdapter({
        asyncStart() {
          asyncStarted++;
        },
        asyncEnd() {
          asyncEnded++;
        },
      });
    }

    teardown() {
      asyncStarted = 0;
      asyncEnded = 0;
      setAdapter(originalTestAdapter);
      setTesting(originalTestingFlag);
    }

    ['@test given `Ember.testing = true`, correctly informs the test suite about async steps'](
      assert
    ) {
      let done = assert.async();
      assert.expect(19);

      assert.ok(!getCurrentRunLoop(), 'expect no run-loop');

      setTesting(true);

      assert.equal(asyncStarted, 0);
      assert.equal(asyncEnded, 0);

      let user = RSVP.Promise.resolve({ name: 'tomster' });

      assert.equal(asyncStarted, 0);
      assert.equal(asyncEnded, 0);

      user
        .then(function (user) {
          assert.equal(asyncStarted, 1);
          assert.equal(asyncEnded, 1);

          assert.equal(user.name, 'tomster');

          return RSVP.Promise.resolve(1).then(function () {
            assert.equal(asyncStarted, 1);
            assert.equal(asyncEnded, 1);
          });
        })
        .then(function () {
          assert.equal(asyncStarted, 1);
          assert.equal(asyncEnded, 1);

          return new RSVP.Promise(function (resolve) {
            setTimeout(function () {
              assert.equal(asyncStarted, 1);
              assert.equal(asyncEnded, 1);

              resolve({ name: 'async tomster' });

              assert.equal(asyncStarted, 2);
              assert.equal(asyncEnded, 1);
            }, 0);
          });
        })
        .then(function (user) {
          assert.equal(user.name, 'async tomster');
          assert.equal(asyncStarted, 2);
          assert.equal(asyncEnded, 2);
          done();
        });
    }
  }
);

moduleFor(
  'TestPromise',
  class extends AbstractTestCase {
    ['does not throw error when falsy value passed to then'](assert) {
      assert.expect(1);
      return new TestPromise(function (resolve) {
        resolve();
      })
        .then(null)
        .then(function () {
          assert.ok(true);
        });
    }

    ['able to get last Promise'](assert) {
      assert.expect(2);

      let p1 = new TestPromise(function (resolve) {
        resolve();
      }).then(function () {
        assert.ok(true);
      });

      let p2 = new TestPromise(function (resolve) {
        resolve();
      });

      assert.deepEqual(getLastPromise(), p2);
      return p1;
    }
  }
);


text:
package org.conqat.engine.html_presentation.javascript.config;

import java.util.Date;
import java.util.Map.Entry;

import org.conqat.engine.core.driver.info.BlockInfo;
import org.conqat.engine.core.driver.instance.EInstanceState;
import org.conqat.engine.core.logging.ConQATLoggingEvent;
import org.conqat.lib.commons.collections.UnmodifiableList;

/**
 * Holds overall statistics data.
 *
 * @author $Author: hummelb $
 * @version $Rev: 39832 $
 * @ConQAT.Rating GREEN Hash: C1B7B5125B383F9C2CD90A4E3FF0E3AA
 */
public class StatisticsDataJson {

	/** The number of errors generated by the root block and its children. */
	private int errors = 0;

	/** The number of warnings generated by the root block and its children. */
	private int warnings = 0;

	/** The overall execution time of the root block. */
	private final long executionTime;

	/** The last time the dashboard was executed. */
	private final long lastExecution;

	/** The number of processors in the root block and its children. */
	private int numberOfProcessors = 0;

	/** The number of failed processors in the root block and its children. */
	private int numberOfFailedProcessors = 0;

	/** Constructor. */
	public StatisticsDataJson(BlockInfo rootBlock, UnmodifiableList<ConQATLoggingEvent> loggingEvents) {
		for (ConQATLoggingEvent event : loggingEvents) {
			switch (event.getLevel()) {
			case FATAL:
			case ERROR:
				errors++;
				break;
			case WARN:
				warnings++;
				break;
			}
		}

		for (Entry<EInstanceState, Integer> entry : rootBlock
				.getProcessorStateDistribution().entrySet()) {
			numberOfProcessors += entry.getValue();

			EInstanceState state = entry.getKey();
			switch (state) {
			case FAILED_BADLY:
			case FAILED_DUE_TO_CLONING_PROBLEM:
			case FAILED_DUE_TO_MISSING_INPUT:
			case FAILED_GRACEFULLY:
				numberOfFailedProcessors += entry.getValue();
			}
		}

		this.executionTime = rootBlock.getExecutionTime();
		this.lastExecution = new Date().getTime();
	}

	/** Returns errors. */
	public int getErrors() {
		return errors;
	}

	/** Returns warnings. */
	public int getWarnings() {
		return warnings;
	}

	/** Returns executionTime. */
	public long getExecutionTime() {
		return executionTime;
	}

	/** Returns lastExecution. */
	public long getLastExecution() {
		return lastExecution;
	}

	/** Returns numberOfProcessors. */
	public int getNumberOfProcessors() {
		return numberOfProcessors;
	}

	/** Returns numberOfFailedProcessors. */
	public int getNumberOfFailedProcessors() {
		return numberOfFailedProcessors;
	}

}


text:
{{ Form::bsText('description','Description','Description') }}
{{ Form::bsSelect('column','Column',array('1','2','3')) }}
{{ Form::bsSelect('width','Width (12  = 100%)',array('1','2','3','4','5','6','7','8','9','10','11','12')) }}
{{ Form::bsText('order','Order','Order') }}
{{ Form::bsText('active','Active','Active') }}
{{ Form::bsSelect('filename','Filename',$files) }}


text:
package org.apache.beam.fn.harness;

import com.google.auto.service.AutoService;
import java.io.IOException;
import java.util.Map;
import org.apache.beam.model.pipeline.v1.RunnerApi.FunctionSpec;
import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform;
import org.apache.beam.runners.core.construction.PCollectionViewTranslation;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.sdk.function.ThrowingFunction;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.WindowMappingFn;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;

/**
 * Represents mapping of main input window onto side input window.
 *
 *
Side input window mapping function:
 *
 *

 *
Input: {@code KV<nonce, MainInputWindow>}
 *
Output: {@code KV<nonce, SideInputWindow>}
 *

 *
 *
For each main input window, the side input window is returned. The nonce is used by a runner
 * to associate each input with its output. The nonce is represented as an opaque set of bytes.
 */
public class WindowMappingFnRunner {
  static final String URN = PTransformTranslation.MAP_WINDOWS_TRANSFORM_URN;

  /**
   * A registrar which provides a factory to handle mapping main input windows onto side input
   * windows.
   */
  @AutoService(PTransformRunnerFactory.Registrar.class)
  public static class Registrar implements PTransformRunnerFactory.Registrar {

    @Override
    public Map<String, PTransformRunnerFactory> getPTransformRunnerFactories() {
      return ImmutableMap.of(
          URN,
          MapFnRunners.forValueMapFnFactory(WindowMappingFnRunner::createMapFunctionForPTransform));
    }
  }

  static <T, W1 extends BoundedWindow, W2 extends BoundedWindow>
      ThrowingFunction<KV<T, W1>, KV<T, W2>> createMapFunctionForPTransform(
          String ptransformId, PTransform pTransform) throws IOException {
    FunctionSpec windowMappingFnPayload = FunctionSpec.parseFrom(pTransform.getSpec().getPayload());
    WindowMappingFn<W2> windowMappingFn =
        (WindowMappingFn<W2>)
            PCollectionViewTranslation.windowMappingFnFromProto(windowMappingFnPayload);
    return (KV<T, W1> input) ->
        KV.of(input.getKey(), windowMappingFn.getSideInputWindow(input.getValue()));
  }
}


text:
YoutuBar
========

A small and Spotlight-like app for quick Youtube search

###Download
You can download the app [here](https://github.com/rockingeric/YoutuBar/releases/tag/1.0)

That's how the app looks like:
![The App](https://i.imgur.com/JDJm78c.png)


text:
package org.apache.pulsar.testclient;

public interface IMessageFormatter {
    byte[] formatMessage(String producerName, long msg, byte[] message);
}


text:
AccountConfiguration.SignInAttemptWindow Property
=================================================
The amount of time that must pass before a new sign in attempt, if user exceeded the [MaxInvalidSignInAttempts][1]. Not used if [DisableOnMaxInvalidSignInAttempts][2] is true. The default is 10 minutes.

**Namespace:** [MvcAccount][3]
**Assembly:** MvcAccount (in MvcAccount.dll)

Syntax
------

```csharp
public TimeSpan SignInAttemptWindow { get; set; }
```

#### Property Value
Type: [TimeSpan][4]

See Also
--------

#### Reference
[AccountConfiguration Class][5]
[MvcAccount Namespace][3]

[1]: MaxInvalidSignInAttempts.md
[2]: DisableOnMaxInvalidSignInAttempts.md
[3]: ../README.md
[4]: http://msdn.microsoft.com/en-us/library/269ew577
[5]: README.md


text:
package org.apache.xbean.sca;

import org.osoa.sca.annotations.ComponentMetaData;
import org.osoa.sca.annotations.ComponentName;
import org.osoa.sca.annotations.Context;
import org.osoa.sca.annotations.Destroy;
import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Property;
import org.osoa.sca.annotations.Reference;
import org.osoa.sca.annotations.SessionID;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.apache.xbean.sca.impl.DefaultScaAdapter;

import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Performs SCA based dependency injection rules.
 *
 * @version $Revision$
 */
public class ScaBeanPostProcessor extends IntrospectionSupport implements DestructionAwareBeanPostProcessor, BeanFactoryPostProcessor {

    private ScaAdapter scaAdapter;

    public ScaBeanPostProcessor() {
    }

    public ScaBeanPostProcessor(ScaAdapter scaAdapter) {
        this.scaAdapter = scaAdapter;
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        List methods = findMethodsWithAnnotation(bean, Init.class);
        invokeVoidMethods(bean, methods);
        processFields(bean, beanName);
        processProperties(bean, beanName);
        return bean;
    }

    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        List methods = findMethodsWithAnnotation(bean, Destroy.class);
        invokeVoidMethods(bean, methods);
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanNames = beanFactory.getBeanDefinitionNames();
        for (int i = 0; i < beanNames.length; i++) {
            String beanName = beanNames[i];
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
            postProcessBeanDefinition(beanFactory, beanName, beanDefinition);
        }
    }

    // Properties
    // -------------------------------------------------------------------------

    public ScaAdapter getScaAdapter() {
        if (scaAdapter == null) {
            scaAdapter = createScaAdapter();
        }
        return scaAdapter;
    }

    public void setScaAdapter(ScaAdapter scaAdapter) {
        this.scaAdapter = scaAdapter;
    }

    // Implementation methods
    // -------------------------------------------------------------------------
    protected void postProcessBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName, BeanDefinition definition) throws BeansException {
        Class type = beanFactory.getType(beanName);
        BeanInfo beanInfo = getBeanInfo(type);
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            PropertyDescriptor descriptor = descriptors[i];
            processProperty(beanName, definition, descriptor);
        }
    }

    protected void processProperty(String beanName, BeanDefinition definition, PropertyDescriptor descriptor) throws BeansException {
        Method method = descriptor.getWriteMethod();
        if (method != null) {
            // TODO should we handle the property.name() attribute?
            // maybe add this to XBean code generator...

            Property property = method.getAnnotation(Property.class);
            if (property != null) {
                if (property.required()) {
                    // TODO use property.name()?
                    String propertyName = descriptor.getName();
                    MutablePropertyValues propertyValues = definition.getPropertyValues();
                    if (!propertyValues.contains(propertyName)) {
                        throw new BeanInitializationException("Mandatory property: " + propertyName + " not specified on bean: " + beanName);
                    }
                }
            }

            Reference reference = method.getAnnotation(Reference.class);
            if (reference != null) {
                if (reference.required()) {
                    // TODO use reference.name()?
                    String propertyName = descriptor.getName();
                    MutablePropertyValues propertyValues = definition.getPropertyValues();
                    if (!propertyValues.contains(propertyName)) {
                        throw new BeanInitializationException("Mandatory reference: " + propertyName + " not specified on bean: " + beanName);
                    }
                }
            }
        }
    }

    protected void processProperties(Object bean, String beanName) throws BeansException {
        BeanInfo beanInfo = getBeanInfo(bean.getClass());
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            PropertyDescriptor descriptor = descriptors[i];
            processProperty(bean, beanName, descriptor);
        }
    }

    protected void processProperty(Object bean, String beanName, PropertyDescriptor descriptor) throws BeansException {
        Method method = descriptor.getWriteMethod();
        if (method != null) {
            if (hasAnnotation(method, ComponentName.class)) {
                Object[] arguments = new Object[] { beanName };
                invokeMethod(bean, method, arguments);
            }
            if (hasAnnotation(method, ComponentMetaData.class)) {
                Object[] arguments = new Object[] { getScaAdapter().getComponentMetaData(bean, beanName) };
                invokeMethod(bean, method, arguments);
            }
            if (hasAnnotation(method, Context.class)) {
                Object[] arguments = new Object[] { getScaAdapter().getComponentContext(bean, beanName) };
                invokeMethod(bean, method, arguments);
            }
            if (hasAnnotation(method, SessionID.class)) {
                Object[] arguments = new Object[] { getScaAdapter().getBeanSessionID(bean, beanName) };
                invokeMethod(bean, method, arguments);
            }
        }
    }

    protected void processFields(Object bean, String beanName) throws BeansException {
        Class type = bean.getClass();
        while (true) {
            Field[] declaredFields = type.getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                processField(bean, beanName, field);
            }
            if (type.equals(Object.class)) {
                break;
            }
            else {
                type = type.getSuperclass();
            }
        }
    }

    protected void processField(Object bean, String beanName, Field field) {
        if (hasAnnotation(field, ComponentName.class)) {
            setField(bean, field, beanName);
        }
        if (hasAnnotation(field, ComponentMetaData.class)) {
            setField(bean, field, getScaAdapter().getComponentMetaData(bean, beanName));
        }
        if (hasAnnotation(field, Context.class)) {
            setField(bean, field, getScaAdapter().getComponentContext(bean, beanName));
        }
        if (hasAnnotation(field, SessionID.class)) {
            setField(bean, field, getScaAdapter().getBeanSessionID(bean, beanName));
        }

    }

    protected ScaAdapter createScaAdapter() {
        return new DefaultScaAdapter();
    }

}


text:
package example

import (
	"github.com/GoogleCloudPlatform/go-endpoints/endpoints"
	"github.com/luci/gae/impl/prod"
	dstore "github.com/luci/gae/service/datastore"
	"golang.org/x/net/context"
)

// ListRsp is the response from the 'List' RPC. It contains a list of Counters
// including their IDs and Values.
type ListRsp struct {
	Counters []Counter
}

// List returns a list of all the counters. Note that it's very poorly
// implemented! It's completely unpaged. I don't care :).
func (Example) List(c context.Context) (rsp *ListRsp, err error) {
	ds := dstore.Get(prod.Use(c))
	rsp = &ListRsp{}
	err = ds.GetAll(ds.NewQuery("Counter"), &rsp.Counters)
	return
}

func init() {
	mi["List"] = &endpoints.MethodInfo{
		Path: "counter",
		Desc: "Returns all of the available counters",
	}
}


text:
/**
 * @module ol/interaction/DragRotateAndZoom
 */
import {shiftKeyOnly, mouseOnly} from '../events/condition.js';
import PointerInteraction from './Pointer.js';

/**
 * @typedef {Object} Options
 * @property {import("../events/condition.js").Condition} [condition] A function that
 * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
 * boolean to indicate whether that event should be handled.
 * Default is {@link module:ol/events/condition~shiftKeyOnly}.
 * @property {number} [duration=400] Animation duration in milliseconds.
 */

/**
 * @classdesc
 * Allows the user to zoom and rotate the map by clicking and dragging
 * on the map.  By default, this interaction is limited to when the shift
 * key is held down.
 *
 * This interaction is only supported for mouse devices.
 *
 * And this interaction is not included in the default interactions.
 * @api
 */
class DragRotateAndZoom extends PointerInteraction {

  /**
   * @param {Options=} opt_options Options.
   */
  constructor(opt_options) {

    const options = opt_options ? opt_options : {};

    super(/** @type {import("./Pointer.js").Options} */ (options));

    /**
     * @private
     * @type {import("../events/condition.js").Condition}
     */
    this.condition_ = options.condition ? options.condition : shiftKeyOnly;

    /**
     * @private
     * @type {number|undefined}
     */
    this.lastAngle_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.lastMagnitude_ = undefined;

    /**
     * @private
     * @type {number}
     */
    this.lastScaleDelta_ = 0;

    /**
     * @private
     * @type {number}
     */
    this.duration_ = options.duration !== undefined ? options.duration : 400;

  }

  /**
   * @inheritDoc
   */
  handleDragEvent(mapBrowserEvent) {
    if (!mouseOnly(mapBrowserEvent)) {
      return;
    }

    const map = mapBrowserEvent.map;
    const size = map.getSize();
    const offset = mapBrowserEvent.pixel;
    const deltaX = offset[0] - size[0] / 2;
    const deltaY = size[1] / 2 - offset[1];
    const theta = Math.atan2(deltaY, deltaX);
    const magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    const view = map.getView();
    if (this.lastAngle_ !== undefined) {
      const angleDelta = this.lastAngle_ - theta;
      view.adjustRotationInternal(angleDelta);
    }
    this.lastAngle_ = theta;
    if (this.lastMagnitude_ !== undefined) {
      view.adjustResolution(this.lastMagnitude_ / magnitude);
    }
    if (this.lastMagnitude_ !== undefined) {
      this.lastScaleDelta_ = this.lastMagnitude_ / magnitude;
    }
    this.lastMagnitude_ = magnitude;
  }

  /**
   * @inheritDoc
   */
  handleUpEvent(mapBrowserEvent) {
    if (!mouseOnly(mapBrowserEvent)) {
      return true;
    }

    const map = mapBrowserEvent.map;
    const view = map.getView();
    const direction = this.lastScaleDelta_ > 1 ? 1 : -1;
    view.endInteraction(this.duration_, direction);
    this.lastScaleDelta_ = 0;
    return false;
  }

  /**
   * @inheritDoc
   */
  handleDownEvent(mapBrowserEvent) {
    if (!mouseOnly(mapBrowserEvent)) {
      return false;
    }

    if (this.condition_(mapBrowserEvent)) {
      mapBrowserEvent.map.getView().beginInteraction();
      this.lastAngle_ = undefined;
      this.lastMagnitude_ = undefined;
      return true;
    } else {
      return false;
    }
  }
}

export default DragRotateAndZoom;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="css/style.css">
    <title>{{ .Site.Title }}</title>

{{ .Site.Title }}

{{ .Site.Data.WhoWeAre.Title }}

            {{ .Site.Data.WhoWeAre.Text | markdownify }}

{{ .Site.Data.Participate.Title }}

            {{ .Site.Data.Participate.Text | markdownify }}

{{ .Site.Data.Meeting.Title }}

            {{ .Site.Data.Meeting.Text | markdownify }}

{{ .Site.Data.Dates.Title }}

            {{ .Site.Data.Dates.Text | markdownify }}
            {{ $meetups := getJSON "https://api.meetup.com/SciFiMuc/events?status=proposed" }}

            {{ range $meetups }}

{{ .name }} {{ .date }}

            {{ end }}

Images are from The Noun Project. All icons are licensed under this Creative commons license.

UFO is from Anna

Spaceship with Alien is from Bob

Rocket is from Cillia

Impressum

A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text.

Datenschutz

A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text. A very long text.


text:
package ch.vorburger.minecraft.aliases;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.command.CommandManager;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameStartingServerEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.text.Text;

import com.google.common.base.Joiner;
import com.google.common.collect.MapMaker;
import com.google.inject.Inject;

import ch.vorburger.minecraft.command.CommandExecutorAdapter;
import ch.vorburger.minecraft.command.CommandHelper;
import ch.vorburger.minecraft.command.CommandRegistry;

/**
 * Aliases. For example:
 *    /x 4 fd
 * @author Michael Vorburger
 */
//@Plugin(id = "VAliases", name = "Aliasing commands", version = "1.0")
public class AliasPlugin {

	protected @Inject Logger logger;

	// TODO Persistence.. save the aliases, to survive restarts!

	protected @Inject Game game;
	protected @Inject PluginContainer plugin;
	protected @Inject CommandRegistry commandRegistry;
	protected @Inject CommandHelper commandHelper;
	protected CommandManager commandService; // cannot @Inject this :(

	protected Map<String, Script> aliases = new MapMaker().makeMap();

	protected static final Joiner joiner = Joiner.on(' ');

	// @Command(value = "repeat command N times", aliases = { "n", "repeat", "loop" })
	public void x(CommandSource commandSource, int n, String... commandsToRepeat) {
		String joinedCommandsToRepeat = joiner.join(commandsToRepeat);
		if (joinedCommandsToRepeat.startsWith("/"))
			joinedCommandsToRepeat = joinedCommandsToRepeat.substring(1);
		for (int i = 0; i < n; i++) {
			// TODO use same impl. as alias, to be able to use Script multi-commands here also (and for same error handling)
			commandService.process(commandSource, joinedCommandsToRepeat);
			// TODO handle returned result.. but doing above change will already take care of this, differently
		}
	}

	// @Command("list all / register new / delete Alias command")
	public void alias(CommandSource commandSource, Optional<String> name, Optional<String> commandsToAlias) {
		if (name.isPresent() && commandsToAlias.isPresent())
			alias(commandSource, name.get(), commandsToAlias.get());
		else if (name.isPresent() && !commandsToAlias.isPresent())
			alias(commandSource, name.get());
		else // !name.isPresent() && !commandsToAlias.isPresent()
			alias(commandSource);
	}

	//// @Command("register a new Alias command")
	public void alias(CommandSource commandSource, String name, String commandsToAlias) {
		Script script = new Script(/*name, */commandsToAlias);
		Optional<CommandMapping> command = commandHelper.createCommand(plugin, name, script.getCommands().toString(), script.asCommandExecutor(commandService));
		if (command.isPresent())
			commandRegistry.register(command.get());
		else
			// logger.error("Failed to create CommandMapping to register: " + name);
			throw new IllegalArgumentException("Failed to create CommandMapping to register: " + name);
		aliases.put(name, script);
	}

	//// @Command("list all available Aliases commands")
	public void alias(CommandSource commandSource) {
		// TODO Format more nicely!
		if (!aliases.keySet().isEmpty())
			commandSource.sendMessage(Text.of(aliases.keySet().toString()));
	}

	//// @Command("delete an Alias command")
	public void alias(CommandSource commandSource, String name) {
		if (aliases.remove(name) != null)
			commandRegistry.unregister(name);
	}

	@Listener
	public void onServerStopping(GameStoppingServerEvent event) {
		commandRegistry.unregisterAll();
	}

	@Listener
	public void onServerStarting(GameStartingServerEvent event) {
		this.commandService = game.getCommandManager();

		commandRegistry.register(CommandSpec.builder().description(Text.of("repeat command N times")).arguments(
				// GenericArguments.playerOrSource(Text.of("player"), game)
				GenericArguments.integer(Text.of("n")),
				GenericArguments.allOf(GenericArguments.string(Text.of("commandToRepeat")))
				).executor(CommandExecutorAdapter.adapt((src, args) -> {
					// Player player = (Player) src; // TODO if instanceof
					Integer n = args.<Integer>getOne("n").get();
					Collection<String> commandsToRepeat = args.<String>getAll("commandToRepeat");
					this.x(src, n, commandsToRepeat.toArray(new String[0]));
				})).build(), "x");

		commandRegistry.register(CommandSpec.builder().description(Text.of("list all / register new / delete Alias command")).arguments(
				// GenericArguments.playerOrSource(Text.of("player"), game)
				GenericArguments.optional(GenericArguments.string(Text.of("cmd"))),
				GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("commandsToAlias")))
				).executor(CommandExecutorAdapter.adapt((src, args) -> {
					// Player player = (Player) src; // TODO if instanceof
					Optional<String> name = args.<String>getOne("cmd");
					Optional<String> commandsToAlias = args.<String>getOne("commandsToAlias");
					this.alias(src, name, commandsToAlias);
				})).build(), "def", "alias");

	}
}


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

/*
 * Runtime type representation.
 * This file exists only to provide types that 6l can turn into
 * DWARF information for use by gdb.  Nothing else uses these.
 * They should match the same types in ../reflect/type.go.
 * For comments see ../reflect/type.go.
 */

package runtime

import "unsafe"

type commonType struct {
	Kind       uint8
	align      uint8
	fieldAlign uint8
	size       uintptr
	hash       uint32

	hashfn  func(unsafe.Pointer, uintptr) uintptr
	equalfn func(unsafe.Pointer, unsafe.Pointer, uintptr) bool

	string *string
	*uncommonType
	ptrToThis *commonType
}

type _method struct {
	name    *string
	pkgPath *string
	mtyp    *commonType
	typ     *commonType
	tfn     unsafe.Pointer
}

type uncommonType struct {
	name    *string
	pkgPath *string
	methods []_method
}

type _imethod struct {
	name    *string
	pkgPath *string
	typ     *commonType
}

type interfaceType struct {
	commonType
	methods []_imethod
}


text:
function lint(text, minify, width) {
    minify = (typeof minify === "undefined") ? false : minify;
    if (minify) {
        return minify_impl(text, width);
    } else {
        return lint_impl(text, width);
    }
}

/**
 * Tokenize the text and generate words on a line until the width is satisfied,
 * then move on to the next line.
 *
 * @param text The text to minify
 * @param width How long each line should be
 */
function minify_impl(text, width) {
    width = (typeof width === "undefined") ? 1 : width;
    text = (typeof text === "undefined") ? "" : text;

    if (width < 1) {
        width = 1;
    }

    // Since we're not interested in the existing formatting, remove all line
    // breaks and treat them as spaces.
    text = text.replace(/\r\n/g, " ");
    text = text.replace(/\r/g, " ");
    text = text.replace(/\n/g, " ");

    var tokens = text.split(" ");
    var res = "";
    var curWidth = 0;

    tokens.map(function (token) {
        // See if we can add the word to this line by checking its length
        // against the current width. Don't forget to account for the extra
        // space.
        if ((curWidth + token.length + 1 <= width) || (curWidth == 0)) {
            // Acceptable to add.

            // Special case to kill space at the very beginning...
            if (curWidth === 0) {
                res += token;
                curWidth += token.length;
            } else {
                res += " " + token;
                curWidth += token.length + 1;
            }
        } else {
            // Couldn't add this word because it would push this line over the
            // limit. We _must_ add it to the next line, then. Start the line
            // width count at the width of that word. Note that this may result
            // in lines that are longer than the width if the token to be added
            // is, by itself, longer than the column limit. This is unavoidable
            // and necessary in order to fit all of the words - this token will
            // then be on the line by itself.

            // Need a newline before adding this word.
            curWidth = token.length;
            res += "\n" + token;
        }
    });

    return res;
}

/**
 * Crawl the text line by line, looking for lines that are longer than the width
 * and if one is found, flow its text into the next line, and continue flowing
 * any affected lines.
 *
 * This has the effect of limiting the column width without compressing things
 * like section headers.
 *
 * This can actually be thought of as "split the document into chunks separated
 * by blank lines and then do the minify operation on those chunks".
 *
 * @param text The text to lint
 * @param width How long each line should be, at maximum
 */
function lint_impl(text, width) {
    width = (typeof width === "undefined") ? 1 : width;
    text = (typeof text === "undefined") ? "" : text;

    if (width < 1) {
        width = 1;
    }

    // Split based on one or more blank lines
    text = text.replace(/\r\n/g, "\n");
    text = text.replace(/\n(\n)+/g, "\n\n");
    var chunks = text.split("\n\n");
    var res = "";

    chunks.map(function(chunk) {
        // Minify the chunks and put them back in a result, separated by double
        // newlines.
        res += minify_impl(chunk, width) + "\n\n";
    });

    // Trim the last added newline...
    res = res.substr(0, res.length - 1);
    return res;
}


text:
@interface HDBaseViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, assign) BOOL isCanSideBack;

@property (nonatomic, strong) UIActivityIndicatorView *aiView;
@property (nonatomic, strong) HDReminderView *hdReminderView;

@end

@implementation HDBaseViewController

static UIColor *backgroundColor;
static NSString *backImageName;
static UIEdgeInsets backImageEdgeInsets;

+ (void)setBackgroundColor:(UIColor *)color{
    backgroundColor = color;
}

+ (void)setBackImageName:(NSString *)imageName{
    backImageName = imageName;
}

+ (void)setBackImageEdgeInsets:(UIEdgeInsets)imageEdgeInsets {
    backImageEdgeInsets = imageEdgeInsets;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    if (backgroundColor) {
        self.view.backgroundColor = backgroundColor;
    }

    //默认开启滑动返回
    _isCanSideBack = YES;
    NSArray *viewControllers = self.navigationController.viewControllers;
    //不是根VC自动加上返回
    if (viewControllers.count > 1) {
        [self showBackBtn];
    }
    else{
        [self hideBackBtn];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

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

- (HDReminderView *)hdReminderView {
    if (!_hdReminderView) {
        _hdReminderView = [[HDReminderView alloc] initWithFrame:self.view.bounds];
        _hdReminderView.userInteractionEnabled = YES;
        [self.view addSubview:_hdReminderView];
        [_hdReminderView centerAlignForSuperview];
    }
    return _hdReminderView;
}

-(UIWindow *)getKeyWindow {
    NSEnumerator *frontToBackWindows = [[[UIApplication sharedApplication] windows] reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows) {
        if (window.windowLevel == UIWindowLevelNormal) {
            return window;
        }
    }
    return nil;
}

- (AppDelegate *)getAppDelegate{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return appDelegate;
}

- (UIActivityIndicatorView *)aiView {
    if (!_aiView) {
        _aiView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _aiView;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (self.navigationController.viewControllers.count <= 1 || !_isCanSideBack) {
        return NO;
    }
    return YES;
}

- (void)setCustomTitle:(NSString *)title {
    [self setCustomTitle:title color:UIColorHexFromRGB(0x030303)];
}

- (void)setCustomTitle:(NSString *)title color:(UIColor *)color {
    if (title.length > 10) {
        title = [NSString stringWithFormat:@"%@...", [title substringWithRange:NSMakeRange(0, 10)]];
    }

    UILabel *titleLabel = [HDGlobalMethods createLabel:CGRectMake(0, 0, 120, 20)
                                                 title:title
                                                  font:[UIFont systemFontOfSize:17]
                                               textCol:color];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
    self.navigationItem.titleView = titleLabel;
}

#pragma mark - 左右自定义按钮
- (UIBarButtonItem *)createBarBackButtonItem:(id)target
                                    selector:(SEL)action
{
    UIImage * img = [UIImage imageNamed:backImageName];

    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];

    [button setImage:img forState:UIControlStateNormal];
    [button setImageEdgeInsets:backImageEdgeInsets];
    [button setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    UILabel *titleLabel = [button titleLabel];
    [titleLabel sizeToFit];

    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    return barButtonItem;
}

- (void)hideBackBtn
{
    self.navigationItem.leftBarButtonItems = nil;
    static UIView *clearView = nil;
    if(clearView == nil)
    {
        clearView = [UIView new];
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clearView];
}

- (void)showBackBtn
{
    [self showBackBtnWithSelector:@selector(gotoBack)];
}

- (void)showBackBtnWithSelector:(SEL)selector
{
    UIBarButtonItem *backItem = [self createBarBackButtonItem:self selector:selector];

    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = 0;
    self.navigationItem.leftBarButtonItems = @[negativeSpacer, backItem];
}

- (void)showLeftItemWithTitle:(NSString *)title selector:(SEL) selector{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    [btn setTitleColor:[self themeColor] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(0, 0, 50, 32)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = item;
}

- (void)showLeftItemWithImage:(UIImage *)image selector:(SEL) selector {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(0, 0, 32, 32)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = item;
}

- (void)showLeftActivityView {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.aiView];
    self.navigationItem.leftBarButtonItems = @[item];
    [self.aiView startAnimating];
}

- (void)hideLeftActivityView {
    [self.aiView stopAnimating];
}

-(void) showRightItemWithTitle:(NSString *) title selector:(SEL) selector
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    [btn setTitleColor:[self themeColor] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(0, 0, 50, 32)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];

    self.navigationItem.rightBarButtonItem = item;
}

- (void)showRightItemWithTitle:(NSString *)title titleColor:(UIColor *)titleColor highlightTitleColor:(UIColor *)highlightColor selector:(SEL)selector
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitleColor:titleColor ? : [UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:highlightColor ? : [UIColor blackColor] forState:UIControlStateHighlighted];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(0, 0, 44, 32)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];

    self.navigationItem.rightBarButtonItem = item;
}

- (void)showRightBarButtonWithImage:(UIImage *)image selector:(SEL)selector
{
    if (image)
    {
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:selector];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (UIButton *)showRightBarButtonWithImage:(UIImage *)image hImage:(UIImage *)hImage selector:(SEL)selector
{
    UIButton *mRightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [mRightBtn setAutoresizesSubviews:YES];
    [mRightBtn setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
    [mRightBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [mRightBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barRButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mRightBtn];
    self.navigationItem.rightBarButtonItems = @[barRButtonItem];
    [mRightBtn setImage:image forState:UIControlStateNormal];
    if (hImage) {
        [mRightBtn setImage:hImage forState:UIControlStateHighlighted];
    }
    return mRightBtn;
}

- (void)showRightItemFixedOffsetWithTitle:(NSString *)itemTitle titleColor:(UIColor *)titleColor highlightTitleColor:(UIColor *)highlightColor itemSize:(CGSize)itemSize selector:(SEL)selector
{
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, itemSize.width, itemSize.height)];
    [rightBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:itemTitle forState:UIControlStateNormal];
    [rightBtn setTitleColor:titleColor forState:UIControlStateNormal];
    if (highlightColor)
    {
        [rightBtn setTitleColor:highlightColor forState:UIControlStateHighlighted];
    }
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    UIBarButtonItem *fixItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixItem.width = -20.0f;

    self.navigationItem.rightBarButtonItems = @[fixItem,rightItem];
}

- (NSArray <UIButton *> *)showRightBarButtonWithImage:(UIImage *)image selector:(SEL)selector
                             image2:(UIImage *)image2 selector2:(SEL)selector2 {
    UIButton *mRightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [mRightBtn setImage:image forState:UIControlStateNormal];
    [mRightBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barRButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mRightBtn];

    UIButton *mRightBtn2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [mRightBtn2 setImage:image2 forState:UIControlStateNormal];
    [mRightBtn2 addTarget:self action:selector2 forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barRButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:mRightBtn2];

    UIBarButtonItem *fixItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixItem.width = 15.0f;

    self.navigationItem.rightBarButtonItems = @[barRButtonItem2, fixItem, barRButtonItem];
    return @[mRightBtn, mRightBtn2];
}

- (void)leftAction{

}

- (void)gotoBack {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        if ([self presentingViewController]) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (void)hidePopGestureRecognizer {
    //关闭ios右滑返回
    _isCanSideBack = NO;
}

//设置下横线隐藏
- (UIImageView *)setUnderLineHidden:(BOOL)hidden
{
    if (self.navigationController) {
        UIImageView *line = [self navigationBarLine:self.navigationController.navigationBar];
        line.hidden = hidden;
        return line;
    }
    return nil;
}

- (UIImageView *)navigationBarLine:(UIView *)view{
    // 符合条件返回控件
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    // 递归查找
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self navigationBarLine:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (UIColor *)themeColor {
    return [UIColor whiteColor];
}

#pragma mark - 提示相关的代码
- (void)showReminderViewWihtType:(HDReminderType)reminderType {
    [self.hdReminderView setReminderType:reminderType];
    self.hdReminderView.hidden = NO;
    [self.view bringSubviewToFront:self.hdReminderView];
}

- (void)showReminderViewWithText:(NSString *)text {
    [self.hdReminderView customReminder:text];
    self.hdReminderView.hidden = NO;
    [self.view bringSubviewToFront:self.hdReminderView];
}

- (void)hideReminderView {
    self.hdReminderView.hidden = YES;
}

@end


text:
var _       = require('lodash'),
    moment  = require('moment'),
    path    = require('path'),
    when    = require('when'),
    baseStore;

// TODO: would probably be better to put these on the prototype and have proper constructors etc
baseStore = {
    'getTargetDir': function (baseDir) {
        var m = moment(new Date().getTime()),
            month = m.format('MMM'),
            year =  m.format('YYYY');

        if (baseDir) {
            return path.join(baseDir, year, month);
        }

        return path.join(year, month);
    },
    'generateUnique': function (store, dir, name, ext, i, done) {
        var self = this,
            filename,
            append = '';

        if (i) {
            append = '-' + i;
        }

        filename = path.join(dir, name + append + ext);

        store.exists(filename).then(function (exists) {
            if (exists) {
                setImmediate(function () {
                    i = i + 1;
                    self.generateUnique(store, dir, name, ext, i, done);
                });
            } else {
                done.resolve(filename);
            }
        });
    },
    'getUniqueFileName': function (store, image, targetDir) {
        var done = when.defer(),
            ext = path.extname(image.name),
            name = path.basename(image.name, ext).replace(/[\W]/gi, '_');

        this.generateUnique(store, targetDir, name, ext, 0, done);

        return done.promise;
    }
};

module.exports = baseStore;