text:
#include <Python.h>
#include "theano_mod_helper.h"
#include "structmember.h"
#include <sys/time.h>

#if PY_VERSION_HEX >= 0x03000000
#include "numpy/npy_3kcompat.h"
#define PyCObject_AsVoidPtr  NpyCapsule_AsVoidPtr
#define PyCObject_GetDesc  NpyCapsule_GetDesc
#define PyCObject_Check NpyCapsule_Check
#endif

#ifndef Py_TYPE
#define Py_TYPE(obj) obj->ob_type
#endif

/**

TODO:
- Check max supported depth of recursion
- CLazyLinker should add context information to errors caught during evaluation. Say what node we were on, add the traceback attached to the node.
- Clear containers of fully-useed intermediate results if allow_gc is 1
- Add timers for profiling
- Add support for profiling space used.

  */
static double pytime(const struct timeval * tv)
{
  struct timeval t;
  if (!tv)
    {
      tv = &t;
      gettimeofday(&t, NULL);
    }
  return (double) tv->tv_sec + (double) tv->tv_usec / 1000000.0;
}

/**
  Helper routine to convert a PyList of integers to a c array of integers.
  */
static int unpack_list_of_ssize_t(PyObject * pylist, Py_ssize_t **dst, Py_ssize_t *len,
                                  const char* kwname)
{
  Py_ssize_t buflen, *buf;
  if (!PyList_Check(pylist))
    {
      PyErr_Format(PyExc_TypeError, "%s must be list", kwname);
      return -1;
    }
  assert (NULL == *dst);
  *len = buflen = PyList_Size(pylist);
  *dst = buf = (Py_ssize_t*)calloc(buflen, sizeof(Py_ssize_t));
  assert(buf);
  for (int ii = 0; ii < buflen; ++ii)
    {
      PyObject * el_i = PyList_GetItem(pylist, ii);
      Py_ssize_t n_i = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
      if (PyErr_Occurred())
        {
          free(buf);
          *dst = NULL;
          return -1;
        }
      buf[ii] = n_i;
    }
  return 0;
}

/**

  CLazyLinker

  */
typedef struct {
    PyObject_HEAD
    /* Type-specific fields go here. */
    PyObject * nodes; // the python list of nodes
    PyObject * thunks; // python list of thunks
    PyObject * pre_call_clear; //list of cells to clear on call.
    int allow_gc;
    Py_ssize_t n_applies;
    int n_vars;    // number of variables in the graph
    int * var_computed; // 1 or 0 for every variable
    PyObject ** var_computed_cells;
    PyObject ** var_value_cells;
    Py_ssize_t **dependencies; // list of vars dependencies for GC
    Py_ssize_t *n_dependencies;

    Py_ssize_t n_output_vars;
    Py_ssize_t * output_vars; // variables that *must* be evaluated by call

    int * is_lazy; // 1 or 0 for every thunk

    Py_ssize_t * var_owner; // nodes[[var_owner[var_idx]]] is var[var_idx]->owner
    int * var_has_owner; //  1 or 0

    Py_ssize_t * node_n_inputs;
    Py_ssize_t * node_n_outputs;
    Py_ssize_t ** node_inputs;
    Py_ssize_t ** node_outputs;
    Py_ssize_t * node_inputs_outputs_base; // node_inputs and node_outputs point into this
    Py_ssize_t * node_n_prereqs;
    Py_ssize_t ** node_prereqs;

    Py_ssize_t * update_storage; // input cells to update with the last outputs in output_vars
    Py_ssize_t n_updates;

    void ** thunk_cptr_fn;
    void ** thunk_cptr_data;
    PyObject * call_times;
    PyObject * call_counts;
    int do_timing;
    int need_update_inputs;
    int position_of_error; // -1 for no error, otw the index into `thunks` that failed.
} CLazyLinker;

static void
CLazyLinker_dealloc(PyObject* _self)
{
  CLazyLinker* self = (CLazyLinker *) _self;
  free(self->thunk_cptr_fn);
  free(self->thunk_cptr_data);

  free(self->is_lazy);

  free(self->update_storage);

  if (self->node_n_prereqs)
    {
      for (int i = 0; i < self->n_applies; ++i)
        {
          free(self->node_prereqs[i]);
        }
    }
  free(self->node_n_prereqs);
  free(self->node_prereqs);
  free(self->node_inputs_outputs_base);
  free(self->node_n_inputs);
  free(self->node_n_outputs);
  free(self->node_inputs);
  free(self->node_outputs);

  if (self->dependencies)
    {
      for (int i = 0; i < self->n_vars; ++i)
        {
          free(self->dependencies[i]);
        }
      free(self->dependencies);
      free(self->n_dependencies);
    }

  free(self->var_owner);
  free(self->var_has_owner);
  free(self->var_computed);
  if (self->var_computed_cells)
    {
      for (int i = 0; i < self->n_vars; ++i)
        {
          Py_DECREF(self->var_computed_cells[i]);
          Py_DECREF(self->var_value_cells[i]);
        }
    }
  free(self->var_computed_cells);
  free(self->var_value_cells);
  free(self->output_vars);

  Py_XDECREF(self->nodes);
  Py_XDECREF(self->thunks);
  Py_XDECREF(self->call_times);
  Py_XDECREF(self->call_counts);
  Py_XDECREF(self->pre_call_clear);
  Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
CLazyLinker_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    CLazyLinker *self;

    self = (CLazyLinker *)type->tp_alloc(type, 0);
    if (self != NULL) {
      self->nodes = NULL;
      self->thunks = NULL;
      self->pre_call_clear = NULL;

      self->allow_gc = 1;
      self->n_applies = 0;
      self->n_vars = 0;
      self->var_computed = NULL;
      self->var_computed_cells = NULL;
      self->var_value_cells = NULL;
      self->dependencies = NULL;
      self->n_dependencies = NULL;

      self->n_output_vars = 0;
      self->output_vars = NULL;

      self->is_lazy = NULL;

      self->var_owner = NULL;
      self->var_has_owner = NULL;

      self->node_n_inputs = NULL;
      self->node_n_outputs = NULL;
      self->node_inputs = NULL;
      self->node_outputs = NULL;
      self->node_inputs_outputs_base = NULL;
      self->node_prereqs = NULL;
      self->node_n_prereqs = NULL;

      self->update_storage = NULL;
      self->n_updates = 0;

      self->thunk_cptr_data = NULL;
      self->thunk_cptr_fn = NULL;
      self->call_times = NULL;
      self->call_counts = NULL;
      self->do_timing = 0;

      self->need_update_inputs = 0;
      self->position_of_error = -1;
    }
    return (PyObject *)self;
}

static int
CLazyLinker_init(CLazyLinker *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {
      (char*)"nodes",
      (char*)"thunks",
      (char*)"pre_call_clear",
      (char*)"allow_gc",
      (char*)"call_counts",
      (char*)"call_times",
      (char*)"compute_map_list",
      (char*)"storage_map_list",
      (char*)"base_input_output_list",
      (char*)"node_n_inputs",
      (char*)"node_n_outputs",
      (char*)"node_input_offset",
      (char*)"node_output_offset",
      (char*)"var_owner",
      (char*)"is_lazy_list",
      (char*)"output_vars",
      (char*)"node_prereqs",
      (char*)"node_output_size",
      (char*)"update_storage",
      (char*)"dependencies",
      NULL};

    PyObject *compute_map_list=NULL,
             *storage_map_list=NULL,
             *base_input_output_list=NULL,
             *node_n_inputs=NULL,
             *node_n_outputs=NULL,
             *node_input_offset=NULL,
             *node_output_offset=NULL,
             *var_owner=NULL,
             *is_lazy=NULL,
             *output_vars=NULL,
             *node_prereqs=NULL,
             *node_output_size=NULL,
             *update_storage=NULL,
             *dependencies=NULL;

    assert(!self->nodes);
    if (! PyArg_ParseTupleAndKeywords(args, kwds, "OOOiOOOOOOOOOOOOOOOO", kwlist,
                                      &self->nodes,
                                      &self->thunks,
                                      &self->pre_call_clear,
                                      &self->allow_gc,
                                      &self->call_counts,
                                      &self->call_times,
                                      &compute_map_list,
                                      &storage_map_list,
                                      &base_input_output_list,
                                      &node_n_inputs,
                                      &node_n_outputs,
                                      &node_input_offset,
                                      &node_output_offset,
                                      &var_owner,
                                      &is_lazy,
                                      &output_vars,
                                      &node_prereqs,
                                      &node_output_size,
                                      &update_storage,
                                      &dependencies
                                      ))
        return -1;
    Py_INCREF(self->nodes);
    Py_INCREF(self->thunks);
    Py_INCREF(self->pre_call_clear);
    Py_INCREF(self->call_counts);
    Py_INCREF(self->call_times);

    Py_ssize_t n_applies = PyList_Size(self->nodes);

    self->n_applies = n_applies;
    self->n_vars = PyList_Size(var_owner);

    if (PyList_Size(self->thunks) != n_applies) return -1;
    if (PyList_Size(self->call_counts) != n_applies) return -1;
    if (PyList_Size(self->call_times) != n_applies) return -1;

    // allocated and initialize thunk_cptr_data and thunk_cptr_fn
    if (n_applies)
      {
        self->thunk_cptr_data = (void**)calloc(n_applies, sizeof(void*));
        self->thunk_cptr_fn = (void**)calloc(n_applies, sizeof(void*));
        self->is_lazy = (int*)calloc(n_applies, sizeof(int));
        self->node_prereqs = (Py_ssize_t**)calloc(n_applies, sizeof(Py_ssize_t*));
        self->node_n_prereqs = (Py_ssize_t*)calloc(n_applies, sizeof(Py_ssize_t));
        assert(self->node_prereqs);
        assert(self->node_n_prereqs);
        assert(self->is_lazy);
        assert(self->thunk_cptr_fn);
        assert(self->thunk_cptr_data);

        for (int i = 0; i < n_applies; ++i)
          {
            PyObject * thunk = PyList_GetItem(self->thunks, i);
            //thunk is borrowed
            if (PyObject_HasAttrString(thunk, "cthunk"))
              {
                PyObject * cthunk = PyObject_GetAttrString(thunk, "cthunk");
                //new reference
                assert (cthunk && PyCObject_Check(cthunk));
                self->thunk_cptr_fn[i] = PyCObject_AsVoidPtr(cthunk);
                self->thunk_cptr_data[i] = PyCObject_GetDesc(cthunk);
                Py_DECREF(cthunk);
                // cthunk is kept alive by membership in self->thunks
              }

            PyObject * el_i = PyList_GetItem(is_lazy, i);
            self->is_lazy[i] = PyNumber_AsSsize_t(el_i, NULL);

            /* now get the prereqs */
            el_i = PyList_GetItem(node_prereqs, i);
            assert (PyList_Check(el_i));
            self->node_n_prereqs[i] = PyList_Size(el_i);
            if (self->node_n_prereqs[i])
              {
                self->node_prereqs[i] = (Py_ssize_t*)malloc(
                              PyList_Size(el_i)*sizeof(Py_ssize_t));
                for (int j = 0; j < PyList_Size(el_i); ++j)
                  {
                    PyObject * el_ij = PyList_GetItem(el_i, j);
                    Py_ssize_t N = PyNumber_AsSsize_t(el_ij, PyExc_IndexError);
                    if (PyErr_Occurred())
                      return -1;
                    // N < n. variables
                    assert(N < PyList_Size(var_owner));
                    self->node_prereqs[i][j] = N;
                  }
              }
          }
      }
    if (PyList_Check(base_input_output_list))
      {
        Py_ssize_t n_inputs_outputs_base = PyList_Size(base_input_output_list);
        self->node_inputs_outputs_base = (Py_ssize_t*)calloc(n_inputs_outputs_base,sizeof(Py_ssize_t));
        assert(self->node_inputs_outputs_base);
        for (int i = 0; i < n_inputs_outputs_base; ++i)
          {
            PyObject *el_i = PyList_GetItem(base_input_output_list, i);
            Py_ssize_t idx = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            self->node_inputs_outputs_base[i] = idx;
          }
        self->node_n_inputs = (Py_ssize_t*)calloc(n_applies,sizeof(Py_ssize_t));
        assert(self->node_n_inputs);
        self->node_n_outputs = (Py_ssize_t*)calloc(n_applies,sizeof(Py_ssize_t));
        assert(self->node_n_outputs);
        self->node_inputs = (Py_ssize_t**)calloc(n_applies,sizeof(Py_ssize_t*));
        assert(self->node_inputs);
        self->node_outputs = (Py_ssize_t**)calloc(n_applies,sizeof(Py_ssize_t*));
        assert(self->node_outputs);
        for (int i = 0; i < n_applies; ++i)
          {
            Py_ssize_t N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_n_inputs, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_n_inputs[i] = N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_n_outputs, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_n_outputs[i] = N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_input_offset, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_inputs[i] = &self->node_inputs_outputs_base[N];
            N = PyNumber_AsSsize_t(PyList_GetItem(node_output_offset, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_outputs[i] = &self->node_inputs_outputs_base[N];
          }
      }
    else
      {
        PyErr_SetString(PyExc_TypeError, "base_input_output_list must be list");
        return -1;
      }

    // allocation for var_owner
    if (PyList_Check(var_owner))
      {
        self->var_owner = (Py_ssize_t*)calloc(self->n_vars,sizeof(Py_ssize_t));
        self->var_has_owner = (int*)calloc(self->n_vars,sizeof(int));
        self->var_computed = (int*)calloc(self->n_vars,sizeof(int));
        self->var_computed_cells = (PyObject**)calloc(self->n_vars,sizeof(PyObject*));
        self->var_value_cells = (PyObject**)calloc(self->n_vars,sizeof(PyObject*));
        for (int i = 0; i < self->n_vars; ++i)
          {
            PyObject * el_i = PyList_GetItem(var_owner, i);
            if (el_i == Py_None)
              {
                self->var_has_owner[i] = 0;
              }
            else
              {
                Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
                if (PyErr_Occurred()) return -1;
                assert (N <= n_applies);
                self->var_owner[i] = N;
                self->var_has_owner[i] = 1;
              }
            self->var_computed_cells[i] = PyList_GetItem(compute_map_list, i);
            Py_INCREF(self->var_computed_cells[i]);
            self->var_value_cells[i] = PyList_GetItem(storage_map_list, i);
            Py_INCREF(self->var_value_cells[i]);
          }
      }
    else
      {
        PyErr_SetString(PyExc_TypeError, "var_owner must be list");
        return -1;
      }

    if (dependencies != Py_None)
      {
        self->dependencies = (Py_ssize_t**)calloc(self->n_vars, sizeof(Py_ssize_t *));
        self->n_dependencies = (Py_ssize_t*)calloc(self->n_vars, sizeof(Py_ssize_t));
        assert(self->dependencies);
        assert(self->n_dependencies);

        for (int i = 0; i < self->n_vars; ++i)
          {
            PyObject *tmp = PyList_GetItem(dependencies, i);
            // refcounting - tmp is borrowed
            if (unpack_list_of_ssize_t(tmp, &self->dependencies[i], &self->n_dependencies[i],
                                       "dependencies"))
              return -1;
          }
      }

    if (unpack_list_of_ssize_t(output_vars, &self->output_vars, &self->n_output_vars,
                               "output_vars"))
      return -1;
    for (int i = 0; i < self->n_output_vars; ++i)
      {
        assert(self->output_vars[i] < self->n_vars);
      }
    if (unpack_list_of_ssize_t(update_storage, &self->update_storage, &self->n_updates,
                               "updates_storage"))
      return -1;
    return 0;
}
static void set_position_of_error(CLazyLinker * self, int owner_idx)
{
  if (self->position_of_error == -1)
    {
      self->position_of_error = owner_idx;
    }
}
static PyObject * pycall(CLazyLinker * self, Py_ssize_t node_idx, int verbose)
{
  // call thunk to see which inputs it wants
  PyObject * thunk = PyList_GetItem(self->thunks, node_idx);
  // refcounting - thunk is borrowed
  PyObject * rval = NULL;
  if (self->do_timing)
    {
      double t0 = pytime(NULL);
      if (verbose) fprintf(stderr, "calling via Python (node %i)\n", (int)node_idx);
      rval = PyObject_CallObject(thunk, NULL);
      if (rval)
        {
          double t1 = pytime(NULL);
          double ti = PyFloat_AsDouble(
                         PyList_GetItem(self->call_times, node_idx));
          PyList_SetItem(self->call_times, node_idx,
                         PyFloat_FromDouble(t1 - t0 + ti));
          PyObject * count = PyList_GetItem(self->call_counts, node_idx);
          long icount = PyInt_AsLong(count);
          PyList_SetItem(self->call_counts, node_idx,
                         PyInt_FromLong(icount + 1));
      }
    }
  else
    {
      if (verbose)
        {
          fprintf(stderr, "calling via Python (node %i)\n", (int)node_idx);
        }
      rval = PyObject_CallObject(thunk, NULL);
    }
  return rval;
}
static int c_call(CLazyLinker * self, Py_ssize_t node_idx, int verbose)
{
  void * ptr_addr = self->thunk_cptr_fn[node_idx];
  int (*fn)(void*) = (int (*)(void*))(ptr_addr);
  if (verbose) fprintf(stderr, "calling non-lazy shortcut (node %i)\n", (int)node_idx);
  int err = 0;
  if (self->do_timing)
    {
      double t0 = pytime(NULL);
      err = fn(self->thunk_cptr_data[node_idx]);
      double t1 = pytime(NULL);
      double ti = PyFloat_AsDouble(PyList_GetItem(self->call_times, node_idx));
      PyList_SetItem(self->call_times, node_idx, PyFloat_FromDouble(t1 - t0 + ti));
      PyObject * count = PyList_GetItem(self->call_counts, node_idx);
      long icount = PyInt_AsLong(count);
      PyList_SetItem(self->call_counts, node_idx, PyInt_FromLong(icount+1));
    }
  else
    {
      err = fn(self->thunk_cptr_data[node_idx]);
    }

  if (err)
    {
      // cast the argument to a PyList (as described near line 226 of cc.py)
      PyObject * __ERROR = ((PyObject**)self->thunk_cptr_data[node_idx])[0];
      assert (PyList_Check(__ERROR));
      assert (PyList_Size(__ERROR) == 3);
      PyObject * err_type = PyList_GetItem(__ERROR, 0); //stolen ref
      PyObject * err_msg = PyList_GetItem(__ERROR, 1); //stolen ref
      PyObject * err_trace = PyList_GetItem(__ERROR, 2); //stolen ref
      PyList_SET_ITEM(__ERROR, 0, Py_None); Py_INCREF(Py_None); //clobbers old ref
      PyList_SET_ITEM(__ERROR, 1, Py_None); Py_INCREF(Py_None); //clobbers old ref
      PyList_SET_ITEM(__ERROR, 2, Py_None); Py_INCREF(Py_None); //clobbers old ref

      assert(!PyErr_Occurred()); // because CLinker hid the exception in __ERROR aka data
      PyErr_Restore(err_type, err_msg, err_trace); //steals refs to args
    }
  if (err) set_position_of_error(self, node_idx);
  return err;
}
static
int lazy_rec_eval(CLazyLinker * self, Py_ssize_t var_idx, PyObject*one, PyObject*zero)
{
  PyObject *rval = NULL;
  int verbose = 0;
  int err = 0;

  if (verbose) fprintf(stderr, "lazy_rec computing %i\n", (int)var_idx);

  if (self->var_computed[var_idx] || !self->var_has_owner[var_idx])
    return 0;

  Py_ssize_t owner_idx = self->var_owner[var_idx];

  // STEP 1: compute the pre-requirements of the node
  // Includes input nodes for non-lazy ops.
  for (int i = 0; i < self->node_n_prereqs[owner_idx]; ++i)
    {
      Py_ssize_t prereq_idx = self->node_prereqs[owner_idx][i];
      if (!self->var_computed[prereq_idx])
        {
          err = lazy_rec_eval(self, prereq_idx, one, zero);
          if (err) return err;
        }
      assert (self->var_computed[prereq_idx]);
    }

  // STEP 2: compute the node itself
  if (self->is_lazy[owner_idx])
    {
      // update the compute_map cells corresponding to the inputs of this thunk
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          int in_idx = self->node_inputs[owner_idx][i];
          if (self->var_computed[in_idx])
            {
              Py_INCREF(one);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, one);
            }
          else
            {
              Py_INCREF(zero);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, zero);
            }
          if (err) goto fail;
        }

      rval = pycall(self, owner_idx, verbose);
      // refcounting - rval is new ref
      //TODO: to prevent infinite loops
      // - consider check that a thunk does not ask for an input that is already computed
      if (rval == NULL)
        {
          assert (PyErr_Occurred());
          err = 1;
          goto fail;
        }

      //update the computed-ness of any output cells
      for (int i = 0; i < self->node_n_outputs[owner_idx]; ++i)
        {
          int out_idx = self->node_outputs[owner_idx][i];
          PyObject * el_i = PyList_GetItem(self->var_computed_cells[out_idx], 0);
          Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
          if (PyErr_Occurred())
            {
              err = -1;
              goto pyfail;
            }
          assert (N==0 || N==1);
          self->var_computed[out_idx] = N;
        }
      if (!self->var_computed[var_idx])
        {
          /*
           * If self is not computed after the call, this means that some
           * inputs are needed.  Compute the ones on the returned list
           * and try to compute the current node again (with recursive call).
           * This allows a node to request more nodes more than once before
           * finally yielding a result.
           */
          if (!PyList_Check(rval))
            {
              //TODO: More helpful error to help find *which node* made this
              // bad thunk
              PyErr_SetString(PyExc_TypeError,
                              "lazy thunk should return a list");
              err = 1;
              goto pyfail;
            }

          if (!PyList_Size(rval))
            {
              PyErr_SetString(PyExc_ValueError,
                              "lazy thunk returned empty list without computing output");
              err = 1;
              goto pyfail;
            }

          for (int i = 0; i < PyList_Size(rval); ++i)
            {
              PyObject * el_i = PyList_GetItem(rval, i);
              Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
              if (PyErr_Occurred())
                {
                  err = 1;
                  goto pyfail;
                }
              assert (N <= self->node_n_inputs[owner_idx]);
              Py_ssize_t input_idx = self->node_inputs[owner_idx][N];
              err = lazy_rec_eval(self, input_idx, one, zero);
              if (err) goto pyfail;
            }

          Py_DECREF(rval);
          /*
           * We intentionally skip all the end-of-function processing
           * (mark outputs, GC) as it will be performed by the call
           * that actually manages to compute the result.
           */
          return lazy_rec_eval(self, var_idx, one, zero);
        }

      Py_DECREF(rval);
    }
  else //owner is not a lazy op. Ensure all intputs are evaluated.
    {
      // loop over inputs to owner
      // call lazy_rec_eval on each one that is not computed.
      // if there's an error, pass it up the stack
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          Py_ssize_t input_idx = self->node_inputs[owner_idx][i];
          if (!self->var_computed[input_idx])
            {
              err = lazy_rec_eval(self, input_idx, one, zero);
              if (err) return err;
            }
          assert (self->var_computed[input_idx]);
        }

      // call the thunk for this owner.
      if (self->thunk_cptr_fn[owner_idx])
        {
          err = c_call(self, owner_idx, verbose);
          if (err) goto fail;
        }
      else
        {
          rval = pycall(self, owner_idx, verbose);
          //rval is new ref
          if (rval) //pycall returned normally (no exception)
            {
              if (rval == Py_None)
                {
                  Py_DECREF(rval); //ignore a return of None
                }
              else if (PyList_Check(rval))
                {
                  PyErr_SetString(PyExc_TypeError,
                                  "non-lazy thunk should return None, not list");
                  err = 1;
                  goto pyfail;
                }
              else // don't know what it returned, but it wasn't right.
                {
                  PyErr_SetObject(PyExc_TypeError, rval);
                  err = 1;
                  // We don't release rval since we put it in the error above
                  goto fail;
                }
            }
          else // pycall returned NULL (internal error)
            {
              err = 1;
              goto fail;
            }
        }
    }

  // loop over all outputs and mark them as computed
  for (int i = 0; i < self->node_n_outputs[owner_idx]; ++i)
    {
      self->var_computed[self->node_outputs[owner_idx][i]] = 1;
    }

  // Free vars that are not needed anymore
  if (self->allow_gc)
    {
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          int cleanup = 1;
          Py_ssize_t i_idx = self->node_inputs[owner_idx][i];
          if (!self->var_has_owner[i_idx])
            continue;

          for (int j = 0; j < self->n_output_vars; ++j)
            {
              if (i_idx == self->output_vars[j])
                {
                  cleanup = 0;
                  break;
                }
            }
          if (!cleanup) continue;

          for (int j = 0; j < self->n_dependencies[i_idx]; ++j)
            {
              if (!self->var_computed[self->dependencies[i_idx][j]])
                {
                  cleanup = 0;
                  break;
                }
            }
          if (!cleanup) continue;

          Py_INCREF(Py_None);
          err = PyList_SetItem(self->var_value_cells[i_idx], 0, Py_None);
//See the Stack gc implementation for why we change it to 2 and not 0.
          self->var_computed[i_idx] = 2;
          if (err) goto fail;
        }
    }

  return 0;
 pyfail:
  Py_DECREF(rval);
 fail:
  set_position_of_error(self, owner_idx);
  return err;
}

static PyObject *
CLazyLinker_call(PyObject *_self, PyObject *args, PyObject *kwds)
{
  CLazyLinker * self = (CLazyLinker*)_self;
  static char *kwlist[] = {
    (char*)"time_thunks",
    (char *)"n_calls",
    NULL};
  int n_calls=1;
  if (! PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist,
                                    &self->do_timing,
                                    &n_calls))
    return NULL;
  int err = 0;
  self->position_of_error = -1;
  // create constants used to fill the var_compute_cells
  PyObject * one = PyInt_FromLong(1);
  PyObject * zero = PyInt_FromLong(0);

  // pre-allocate our return value
  Py_INCREF(Py_None);
  PyObject * rval = Py_None;
  //clear storage of pre_call_clear elements
  for (int call_i = 0; call_i < n_calls && (!err); ++call_i)
    {
      Py_ssize_t n_pre_call_clear = PyList_Size(self->pre_call_clear);
      assert(PyList_Check(self->pre_call_clear));
      for (int i = 0; i < n_pre_call_clear; ++i)
        {
          PyObject * el_i = PyList_GetItem(self->pre_call_clear, i);
          Py_INCREF(Py_None);
          PyList_SetItem(el_i, 0, Py_None);
        }
      //clear the computed flag out of all non-input vars
      for (int i = 0; i < self->n_vars; ++i)
        {
          self->var_computed[i] = !self->var_has_owner[i];
          if (self->var_computed[i])
            {
              Py_INCREF(one);
              PyList_SetItem(self->var_computed_cells[i], 0, one);
            }
          else
            {
              Py_INCREF(zero);
              PyList_SetItem(self->var_computed_cells[i], 0, zero);
            }
        }

      for (int i = 0; i < self->n_output_vars && (!err); ++i)
        {
          err = lazy_rec_eval(self, self->output_vars[i], one, zero);
        }

      if (!err)
        {
          // save references to outputs prior to updating storage containers
          assert (self->n_output_vars >= self->n_updates);
          Py_DECREF(rval);
          rval = PyList_New(self->n_output_vars);
          for (int i = 0; i < (self->n_output_vars); ++i)
            {
              Py_ssize_t src = self->output_vars[i];
              PyObject * item = PyList_GetItem(self->var_value_cells[src], 0);
              if (self->var_computed[src] != 1)
                {
                  err = 1;
                  PyErr_Format(PyExc_AssertionError,
                               "The compute map of output %d should contain "
                               "1 at the end of execution, not %d.",
                               i, self->var_computed[src]);
                  break;
                }
              Py_INCREF(item);
              PyList_SetItem(rval, i, item);
            }
        }

      if (!err)
        {
          // Update the inputs that have an update rule
          for (int i = 0; i < self->n_updates; ++i)
            {
              PyObject* tmp = PyList_GetItem(rval, self->n_output_vars - self->n_updates + i);
              Py_INCREF(tmp);
              Py_ssize_t dst = self->update_storage[i];
              PyList_SetItem(self->var_value_cells[dst], 0, tmp);
            }
        }
    }

  /*
    Clear everything that is left and not an output.  This is needed
    for lazy evaluation since the current GC algo is too conservative
    with lazy graphs.
  */
  if (self->allow_gc && !err)
    {
      for (Py_ssize_t i = 0; i < self->n_vars; ++i)
        {
          int do_cleanup = 1;
          if (!self->var_has_owner[i] || !self->var_computed[i])
            continue;
          for (int j = 0; j < self->n_output_vars; ++j)
            {
              if (i == self->output_vars[j])
                {
                  do_cleanup = 0;
                  break;
                }
            }
          if (!do_cleanup)
            continue;
          Py_INCREF(Py_None);
          PyList_SetItem(self->var_value_cells[i], 0, Py_None);
        }
    }
  Py_DECREF(one);
  Py_DECREF(zero);
  if (err)
    {
      Py_DECREF(rval);
      return NULL;
    }
  return rval;
}

#if 0
static PyMethodDef CLazyLinker_methods[] = {
    {
      //"name", (PyCFunction)CLazyLinker_accept, METH_VARARGS, "Return the name, combining the first and last name"
    },
    {NULL}  /* Sentinel */
};
#endif

static PyObject *
CLazyLinker_get_allow_gc(CLazyLinker *self, void *closure)
{
    return PyBool_FromLong(self->allow_gc);
}

static int
CLazyLinker_set_allow_gc(CLazyLinker *self, PyObject *value, void *closure)
{
  if(!PyBool_Check(value))
    return -1;

  if (value == Py_True)
    self->allow_gc = true;
  else
    self->allow_gc = false;
  return 0;
}

static PyGetSetDef CLazyLinker_getset[] = {
  {(char*)"allow_gc",
   (getter)CLazyLinker_get_allow_gc,
   (setter)CLazyLinker_set_allow_gc,
   (char*)"do this function support allow_gc",
   NULL},
  {NULL, NULL, NULL, NULL}  /* Sentinel */
};
static PyMemberDef CLazyLinker_members[] = {
    {(char*)"nodes", T_OBJECT_EX, offsetof(CLazyLinker, nodes), 0,
     (char*)"list of nodes"},
    {(char*)"thunks", T_OBJECT_EX, offsetof(CLazyLinker, thunks), 0,
     (char*)"list of thunks in program"},
    {(char*)"call_counts", T_OBJECT_EX, offsetof(CLazyLinker, call_counts), 0,
     (char*)"number of calls of each thunk"},
    {(char*)"call_times", T_OBJECT_EX, offsetof(CLazyLinker, call_times), 0,
     (char*)"total runtime in each thunk"},
    {(char*)"position_of_error", T_INT, offsetof(CLazyLinker, position_of_error), 0,
     (char*)"position of failed thunk"},
    {(char*)"time_thunks", T_INT, offsetof(CLazyLinker, do_timing), 0,
     (char*)"bool: nonzero means call will time thunks"},
    {(char*)"need_update_inputs", T_INT, offsetof(CLazyLinker, need_update_inputs), 0,
     (char*)"bool: nonzero means Function.__call__ must implement update mechanism"},
    {NULL}  /* Sentinel */
};

static PyTypeObject lazylinker_ext_CLazyLinkerType = {
#if defined(NPY_PY3K)
    PyVarObject_HEAD_INIT(NULL, 0)
#else
    PyObject_HEAD_INIT(NULL)
    0,                         /*ob_size*/
#endif
    "lazylinker_ext.CLazyLinker",             /*tp_name*/
    sizeof(CLazyLinker), /*tp_basicsize*/
    0,                         /*tp_itemsize*/
    CLazyLinker_dealloc,       /*tp_dealloc*/
    0,                         /*tp_print*/
    0,                         /*tp_getattr*/
    0,                         /*tp_setattr*/
    0,                         /*tp_compare*/
    0,                         /*tp_repr*/
    0,                         /*tp_as_number*/
    0,                         /*tp_as_sequence*/
    0,                         /*tp_as_mapping*/
    0,                         /*tp_hash */
    CLazyLinker_call,          /*tp_call*/
    0,                         /*tp_str*/
    0,                         /*tp_getattro*/
    0,                         /*tp_setattro*/
    0,                         /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,        /*tp_flags*/
    "CLazyLinker object",      /* tp_doc */
    0,                         /* tp_traverse */
    0,                         /* tp_clear */
    0,                         /* tp_richcompare */
    0,                         /* tp_weaklistoffset */
    0,                         /* tp_iter */
    0,                         /* tp_iternext */
    0,//CLazyLinker_methods,       /* tp_methods */
    CLazyLinker_members,       /* tp_members */
    CLazyLinker_getset,        /* tp_getset */
    0,                         /* tp_base */
    0,                         /* tp_dict */
    0,                         /* tp_descr_get */
    0,                         /* tp_descr_set */
    0,                         /* tp_dictoffset */
    (initproc)CLazyLinker_init,/* tp_init */
    0,                         /* tp_alloc */
    CLazyLinker_new,           /* tp_new */
};

static PyObject * get_version(PyObject *dummy, PyObject *args)
{
  PyObject *result = PyFloat_FromDouble(0.21);
  return result;
}

static PyMethodDef lazylinker_ext_methods[] = {
  {"get_version",  get_version, METH_VARARGS, "Get extension version."},
  {NULL, NULL, 0, NULL}        /* Sentinel */
};

#if defined(NPY_PY3K)
static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "lazylinker_ext",
        NULL,
        -1,
        lazylinker_ext_methods,
        NULL,
        NULL,
        NULL,
        NULL
};
#endif
#if defined(NPY_PY3K)
#define RETVAL m
PyMODINIT_FUNC
PyInit_lazylinker_ext(void) {
#else
#define RETVAL
PyMODINIT_FUNC
initlazylinker_ext(void)
{
#endif
    PyObject* m;

    lazylinker_ext_CLazyLinkerType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&lazylinker_ext_CLazyLinkerType) < 0)
        return RETVAL;
#if defined(NPY_PY3K)
    m = PyModule_Create(&moduledef);
#else
    m = Py_InitModule3("lazylinker_ext", lazylinker_ext_methods,
                       "Example module that creates an extension type.");
#endif
    Py_INCREF(&lazylinker_ext_CLazyLinkerType);
    PyModule_AddObject(m, "CLazyLinker", (PyObject *)&lazylinker_ext_CLazyLinkerType);

    return RETVAL;
}


text:
package service_test

import (
	"github.com/starkandwayne/cf-cli/cf/api"
	. "github.com/starkandwayne/cf-cli/cf/commands/service"
	"github.com/starkandwayne/cf-cli/cf/models"
	testapi "github.com/starkandwayne/cf-cli/testhelpers/api"
	testcmd "github.com/starkandwayne/cf-cli/testhelpers/commands"
	testconfig "github.com/starkandwayne/cf-cli/testhelpers/configuration"
	testreq "github.com/starkandwayne/cf-cli/testhelpers/requirements"
	testterm "github.com/starkandwayne/cf-cli/testhelpers/terminal"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/starkandwayne/cf-cli/testhelpers/matchers"
)

var _ = Describe("unbind-service command", func() {
	var (
		app                 models.Application
		serviceInstance     models.ServiceInstance
		requirementsFactory *testreq.FakeReqFactory
		serviceBindingRepo  *testapi.FakeServiceBindingRepo
	)

	BeforeEach(func() {
		app.Name = "my-app"
		app.Guid = "my-app-guid"

		serviceInstance.Name = "my-service"
		serviceInstance.Guid = "my-service-guid"

		requirementsFactory = &testreq.FakeReqFactory{}
		requirementsFactory.Application = app
		requirementsFactory.ServiceInstance = serviceInstance

		serviceBindingRepo = &testapi.FakeServiceBindingRepo{}
	})

	Context("when not logged in", func() {
		It("fails requirements when not logged in", func() {
			cmd := NewUnbindService(&testterm.FakeUI{}, testconfig.NewRepository(), serviceBindingRepo)
			testcmd.RunCommand(cmd, testcmd.NewContext("unbind-service", []string{"my-service", "my-app"}), requirementsFactory)
			Expect(testcmd.CommandDidPassRequirements).To(BeFalse())
		})
	})

	Context("when logged in", func() {
		BeforeEach(func() {
			requirementsFactory.LoginSuccess = true
		})

		Context("when the service instance exists", func() {
			It("unbinds a service from an app", func() {
				ui := callUnbindService([]string{"my-app", "my-service"}, requirementsFactory, serviceBindingRepo)

				Expect(requirementsFactory.ApplicationName).To(Equal("my-app"))
				Expect(requirementsFactory.ServiceInstanceName).To(Equal("my-service"))

				Expect(ui.Outputs).To(ContainSubstrings(
					[]string{"Unbinding app", "my-service", "my-app", "my-org", "my-space", "my-user"},
					[]string{"OK"},
				))
				Expect(serviceBindingRepo.DeleteServiceInstance).To(Equal(serviceInstance))
				Expect(serviceBindingRepo.DeleteApplicationGuid).To(Equal("my-app-guid"))
			})
		})

		Context("when the service instance does not exist", func() {
			BeforeEach(func() {
				serviceBindingRepo.DeleteBindingNotFound = true
			})

			It("warns the user the the service instance does not exist", func() {
				ui := callUnbindService([]string{"my-app", "my-service"}, requirementsFactory, serviceBindingRepo)

				Expect(requirementsFactory.ApplicationName).To(Equal("my-app"))
				Expect(requirementsFactory.ServiceInstanceName).To(Equal("my-service"))

				Expect(ui.Outputs).To(ContainSubstrings(
					[]string{"Unbinding app", "my-service", "my-app"},
					[]string{"OK"},
					[]string{"my-service", "my-app", "did not exist"},
				))
				Expect(serviceBindingRepo.DeleteServiceInstance).To(Equal(serviceInstance))
				Expect(serviceBindingRepo.DeleteApplicationGuid).To(Equal("my-app-guid"))
			})
		})

		It("when no parameters are given the command fails with usage", func() {
			ui := callUnbindService([]string{"my-service"}, requirementsFactory, serviceBindingRepo)
			Expect(ui.FailedWithUsage).To(BeTrue())

			ui = callUnbindService([]string{"my-app"}, requirementsFactory, serviceBindingRepo)
			Expect(ui.FailedWithUsage).To(BeTrue())

			ui = callUnbindService([]string{"my-app", "my-service"}, requirementsFactory, serviceBindingRepo)
			Expect(ui.FailedWithUsage).To(BeFalse())
		})
	})
})

func callUnbindService(args []string, requirementsFactory *testreq.FakeReqFactory, serviceBindingRepo api.ServiceBindingRepository) (fakeUI *testterm.FakeUI) {
	fakeUI = &testterm.FakeUI{}
	ctxt := testcmd.NewContext("unbind-service", args)

	config := testconfig.NewRepositoryWithDefaults()

	cmd := NewUnbindService(fakeUI, config, serviceBindingRepo)
	testcmd.RunCommand(cmd, ctxt, requirementsFactory)
	return
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react'
import { Link } from 'react-router'
import styles from './App.scss'

export default class App extends Component {
  static defaultProps = {
    title: 'Level 2'
  }

  render() {
    return (

{this.props.title}

            Router to:
            <Link to={{pathname: '/'}} className={styles.link}>Home</Link>
            <Link to={{pathname: '/about'}} className={styles.link}>About</Link>

        {this.props.children}

    );
  }
}


text:
package com.microrisc.simply.iqrf.dpa.v30x.types;

import java.util.Arrays;

/**
 * Module ID of the remotely bonded node.
 *
 * @author Michal Konopa
 */
public final class RemotelyBondedModuleId {
    /** Module ID. */
    private final short[] moduleId;

    /** User data. */
    private final short[] userData;

    private static boolean areModuleIdsEqual(short[] moduleId_1, short[] moduleId_2) {
        return Arrays.equals(moduleId_2, moduleId_1);
    }

    private static boolean areUserDataEqual(short[] userData_1, short[] userData_2) {
        return Arrays.equals(userData_2, userData_1);
    }

    /**
     * Creates new remotely bonded module ID.
     *
     * @param moduleId module ID of the remotely bonded node
     * @param userData optional bonding user data specified at Reset Custom DPA Handler event
     */
    public RemotelyBondedModuleId(short[] moduleId, short[] userData) {
        this.moduleId = new short[moduleId.length];
        System.arraycopy(moduleId, 0, this.moduleId, 0, moduleId.length);

        this.userData = new short[userData.length];
        System.arraycopy(userData, 0, this.userData, 0, userData.length);
    }

    /**
     * @return the module ID
     */
    public short[] getModuleId() {
        short[] moduleIdToReturn = new short[moduleId.length];
        System.arraycopy(moduleId, 0, moduleIdToReturn, 0, moduleId.length);
        return moduleIdToReturn;
    }

    /**
     * @return the user data
     */
    public short[] getUserData() {
        short[] userDataToReturn = new short[userData.length];
        System.arraycopy(userData, 0, userDataToReturn, 0, userData.length);
        return userDataToReturn;
    }

    @Override
    public boolean equals(Object obj) {
        if ( !(obj instanceof RemotelyBondedModuleId) ) {
            return false;
        }

        RemotelyBondedModuleId remoBondedModuleId = (RemotelyBondedModuleId) obj;

        if ( !areModuleIdsEqual(this.moduleId, remoBondedModuleId.moduleId) ) {
            return false;
        }

        if ( !areUserDataEqual(this.userData, remoBondedModuleId.userData) ) {
            return false;
        }

        return true;
    }

    public String toString() {
        StringBuilder strBuilder = new StringBuilder();
        String NEW_LINE = System.getProperty("line.separator");

        strBuilder.append(this.getClass().getSimpleName() + " { " + NEW_LINE);
        strBuilder.append(" Module ID: " + Arrays.toString(moduleId) + NEW_LINE);
        strBuilder.append(" User data: " + Arrays.toString(userData) + NEW_LINE);
        strBuilder.append("}");

        return strBuilder.toString();
    }

}


text:
package net.ontrack.core.model;

import lombok.Data;

import java.util.Set;

@Data
public class BuildValidationStampFilter {

    private final String validationStamp;
    private final Set<Status> statuses;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true"
    android:orientation="vertical"
    tools:context=".ui.activity.LoginActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/til_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/dp16"
        android:layout_marginStart="@dimen/dp16"
        android:layout_marginTop="@dimen/dp16"
        app:counterEnabled="true"
        app:counterMaxLength="11">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/et_mobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="@dimen/dp4"
            android:drawableStart="@drawable/ic_mobile"
            android:gravity="center_vertical"
            android:hint="请输入手机号"
            android:inputType="number" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/til_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dp16"
        android:layout_marginRight="@dimen/dp16"
        app:passwordToggleEnabled="true">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="@dimen/dp4"
            android:drawableStart="@drawable/ic_password"
            android:gravity="center_vertical"
            android:hint="请输入密码"
            android:inputType="textPassword" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/dp16"
        android:background="@color/colorBlueTheme"
        android:text="登录"
        android:textColor="@color/colorWhiteTheme"
        android:textSize="@dimen/sp16" />

</LinearLayout>


text:
package org.waveprotocol.box.webclient.stat;

import com.google.common.collect.Maps;

import org.waveprotocol.box.stat.ExecutionTree;
import org.waveprotocol.box.stat.RequestScope;

import java.util.Map;

/**
 * Request scope with execution tree and current execution node for use in single-thread environment.
 *
 * @author akaplanov@gmail.com (A. Kaplanov)
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public class SingleThreadedRequestScope implements RequestScope {

  private Map<Class, Value> values;

  public SingleThreadedRequestScope() {
  }

  @Override
  public void enter() {
    values = Maps.<Class, Value>newHashMap();
    values.put(ExecutionTree.class, new ExecutionTree());
  }

  @Override
  public void enter(Map<Class, Value> values) {
    this.values = Maps.<Class, Value>newHashMap(values);
  }

  @Override
  public boolean isEntered() {
    return values != null;
  }

  @Override
  public void exit() {
    checkScoping();
    values = null;
  }

  @Override
  public <T extends Value> void set(Class<T> clazz, T value) {
    checkScoping();
    values.put(clazz, value);
  }

  @Override
  public <T extends Value> T get(Class<T> clazz) {
    checkScoping();
    return (T)values.get(clazz);
  }

  @Override
  public Map<Class, Value> cloneValues() {
    checkScoping();
    Map<Class, Value> map = Maps.<Class, Value>newHashMap();
    for (Map.Entry<Class, Value> entry : values.entrySet()) {
      map.put(entry.getKey(), entry.getValue().clone());
    }
    return map;
  }

  private void checkScoping() {
    if (values == null) {
      enter();
    }
  }
}


text:
using System;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.Azure.Mobile.Server;

namespace Backend.DataObjects
{
	public class Reservation : EntityData
	{
		public string User { get; set; }
		public string RoomName { get; set; }
		public DateTime Date { get; set; }
		public TimeSpan StartingTime { get; set; }
		public TimeSpan EndingTime { get; set; }
	}
}


text:
import { module } from 'qunit';
import { run } from '@ember/runloop';
import EmberObject from '@ember/object';
import { setOwner } from '@ember/application';
import {
  task,
  restartableTask,
  dropTask,
  keepLatestTask,
  enqueueTask,
} from 'ember-concurrency';
import { decoratorTest } from '../helpers/helpers';
import { settled } from '@ember/test-helpers';

module('Unit | decorators', function () {
  decoratorTest('Basic decorators functionality', function (assert) {
    assert.expect(5);

    class TestSubject {
      @task doStuff = function* () {
        yield;
        return 123;
      };

      @restartableTask
      a = function* () {
        yield;
        return 456;
      };

      @keepLatestTask
      b = function* () {
        yield;
        return 789;
      };

      @dropTask
      c = function* () {
        yield;
        return 12;
      };

      @enqueueTask
      d = function* () {
        yield;
        return 34;
      };
    }

    let subject;
    run(() => {
      subject = new TestSubject();

      setOwner(subject, this.owner);

      subject.doStuff.perform();
      subject.a.perform();
      subject.b.perform();
      subject.c.perform();
      subject.d.perform();
    });

    assert.equal(subject.doStuff.last.value, 123);
    assert.equal(subject.a.last.value, 456);
    assert.equal(subject.b.last.value, 789);
    assert.equal(subject.c.last.value, 12);
    assert.equal(subject.d.last.value, 34);
  });

  decoratorTest('Encapsulated tasks', function (assert) {
    assert.expect(1);

    class TestSubject {
      @task encapsulated = {
        privateState: 56,
        *perform() {
          yield;
          return this.privateState;
        },
      };
    }

    let subject;
    run(() => {
      subject = new TestSubject();
      setOwner(subject, this.owner);
      subject.encapsulated.perform();
    });
    assert.equal(subject.encapsulated.last.value, 56);
  });

  decoratorTest(
    '`observes` re-performs the task every time the observed property changes in a coalesced manner',
    async function (assert) {
      assert.expect(2);

      let values = [];
      class Obj extends EmberObject {
        foo = 0;

        @task({ observes: 'foo' })
        *observingTask() {
          values.push(this.foo);
        }
      }

      let obj = Obj.create();
      await settled();

      obj.set('foo', 1);
      obj.set('foo', 2);
      obj.set('foo', 3);
      await settled();

      assert.deepEqual(values, [3]);
      values = [];

      obj.set('foo', 4);
      obj.set('foo', 5);
      obj.set('foo', 6);
      await settled();

      assert.deepEqual(values, [6]);
    }
  );
});


text:
var properties = [];
// Some properties are optional and won't show up in resolvedOptions if
// they were not requested - currency, currencyDisplay,
// minimumSignificantDigits and maximumSignificantDigits - so we request them.
var options = Intl.NumberFormat(
  undefined, {style: 'currency', currency: 'USD', currencyDisplay: 'name',
              minimumSignificantDigits: 1, maximumSignificantDigits: 5}).
    resolvedOptions();
for (var prop in options) {
  if (options.hasOwnProperty(prop)) {
    properties.push(prop);
  }
}

var expectedProperties = [
  'style', 'locale', 'numberingSystem',
  'currency', 'currencyDisplay', 'useGrouping',
  'minimumIntegerDigits', 'minimumFractionDigits',
  'maximumFractionDigits', 'minimumSignificantDigits',
  'maximumSignificantDigits'
];

assertEquals(expectedProperties.length, properties.length);

properties.forEach(function(prop) {
  assertFalse(expectedProperties.indexOf(prop) === -1);
});

taintProperties(properties);

var locale = Intl.NumberFormat(undefined,
                               {currency: 'USD', currencyDisplay: 'name',
                                minimumIntegerDigits: 2,
                                numberingSystem: 'latn'}).
    resolvedOptions().locale;


text:
package com.sign.app.constants;

import com.sign.app.net.FaceResponse;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

public class Interface {
    public interface Face {
        @Multipart
        @POST("facepp/v3/compare")
        Call<FaceResponse> faceCompare(
                @Part("api_key") RequestBody username,
                @Part("api_secret") RequestBody params,
                @Part MultipartBody.Part faceGot,
                @Part MultipartBody.Part faceSet
        );
    }

    //创建Multipart, fieldName为表单字段名
    public static MultipartBody.Part createFilePart(String fieldName, File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData(fieldName, file.getName(), requestFile);
        return body;
    }

    //创建表单的普通字段
    public static RequestBody createFormBody(String content) {
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), content);
        return body;
    }
}


text:
<?php

/**
 * Output escaping decorator class for arrays.
 *
 * @see        sfOutputEscaper
 * @package    symfony
 * @subpackage view
 * @author     Mike Squire <mike@somosis.co.uk>
 * @version    SVN: $Id$
 */
class sfOutputEscaperArrayDecorator extends sfOutputEscaperGetterDecorator implements Iterator, ArrayAccess, Countable
{
  /**
   * Used by the iterator to know if the current element is valid.
   *
   * @var int
   */
  private $count;

  /**
   * Reset the array to the beginning (as required for the Iterator interface).
   */
  public function rewind()
  {
    reset($this->value);

    $this->count = count($this->value);
  }

  /**
   * Get the key associated with the current value (as required by the Iterator interface).
   *
   * @return string The key
   */
  public function key()
  {
    return key($this->value);
  }

  /**
   * Escapes and return the current value (as required by the Iterator interface).
   *
   * This escapes the value using {@link sfOutputEscaper::escape()} with
   * whatever escaping method is set for this instance.
   *
   * @return mixed The escaped value
   */
  public function current()
  {
    return sfOutputEscaper::escape($this->escapingMethod, current($this->value));
  }

  /**
   * Moves to the next element (as required by the Iterator interface).
   */
  public function next()
  {
    next($this->value);

    $this->count --;
  }

  /**
   * Returns true if the current element is valid (as required by the Iterator interface).
   *
   * The current element will not be valid if {@link next()} has fallen off the
   * end of the array or if there are no elements in the array and {@link
   * rewind()} was called.
   *
   * @return boolean The validity of the current element; true if it is valid
   */
  public function valid()
  {
    return $this->count > 0;
  }

  /**
   * Returns true if the supplied offset is set in the array (as required by the ArrayAccess interface).
   *
   * @param string The offset of the value to check existance of
   *
   * @return boolean true if the offset exists; false otherwise
   */
  public function offsetExists($offset)
  {
    return array_key_exists($offset, $this->value);
  }

  /**
   * Returns the element associated with the offset supplied (as required by the ArrayAccess interface).
   *
   * @param string The offset of the value to get
   *
   * @return mixed The escaped value
   */
  public function offsetGet($offset)
  {
    return sfOutputEscaper::escape($this->escapingMethod, $this->value[$offset]);
  }

  /**
   * Throws an exception saying that values cannot be set (this method is
   * required for the ArrayAccess interface).
   *
   * This (and the other sfOutputEscaper classes) are designed to be read only
   * so this is an illegal operation.
   *
   * @param string (ignored)
   * @param string (ignored)
   *
   * @throws <b>sfException</b>
   */
  public function offsetSet($offset, $value)
  {
    throw new sfException('Cannot set values.');
  }

  /**
   * Throws an exception saying that values cannot be unset (this method is
   * required for the ArrayAccess interface).
   *
   * This (and the other sfOutputEscaper classes) are designed to be read only
   * so this is an illegal operation.
   *
   * @param string (ignored)
   *
   * @throws sfException
   */
  public function offsetUnset($offset)
  {
    throw new sfException('Cannot unset values.');
  }

  /**
   * Returns the size of the array (are required by the Countable interface).
   *
   * @return int The size of the array
   */
  public function count()
  {
    return count($this->value);
  }

  /**
   * Returns the (unescaped) value from the array associated with the key supplied.
   *
   * @param string The key into the array to use
   *
   * @return mixed The value
   */
  public function getRaw($key)
  {
    return $this->value[$key];
  }
}


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: kasa2
 * Date: 3/3/2016
 * Time: 1:51 PM
 */
require_once '../../queries/SelectQueries.php';
require_once '../../Caller.php';

//returning the results of the query in json format
echo getAll($allEmpByDept); //this will go back under "data" of angular call.
?>


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_profile_model extends MY_Model
{
	public function __construct()

	{
	parent::__construct();

	}

	public function seller_categories()
	{
		$sid = $this->session->userdata('seller_id');
		$this->db->select('*');
		$this->db->from('seller_categories');
		$this->db->where('seller_id', $sid);
    	$query = $this->db->get();
    	return $query->result();
	}

	// public function total_orders(){
	// 	$sid = $this->session->userdata('seller_id');
	// 	$query = $this->db->query("SELECT COUNT(order_id) AS total_order FROM orders WHERE seller_id = 8");
	// //echo  $this->db->last_query();
	// return $query->result();
	}


text:
package org.codehaus.groovy.grails.plugins;

import java.util.Set;

import junit.framework.TestCase;

public class PluginFilterFactoryTests extends TestCase {

	public void testIncludeFilterOne() throws Exception
	{
		PluginFilterRetriever fb = new PluginFilterRetriever();
		PluginFilter bean = fb.getPluginFilter("one", null);
		assertTrue(bean instanceof IncludingPluginFilter);

		IncludingPluginFilter filter = (IncludingPluginFilter) bean;
		Set suppliedNames = filter.getSuppliedNames();
		assertEquals(1, suppliedNames.size());
		assertTrue(suppliedNames.contains("one"));
	}

	public void testIncludeFilter() throws Exception
	{
		PluginFilterRetriever fb = new PluginFilterRetriever();
		PluginFilter bean = fb.getPluginFilter("one, two", " three , four ");
		assertTrue(bean instanceof IncludingPluginFilter);

		IncludingPluginFilter filter = (IncludingPluginFilter) bean;
		Set suppliedNames = filter.getSuppliedNames();
		assertEquals(2, suppliedNames.size());
		assertTrue(suppliedNames.contains("two"));
	}

	public void testExcludeFilter() throws Exception
	{
		PluginFilterRetriever fb = new PluginFilterRetriever();
		PluginFilter bean = fb.getPluginFilter(null, " three , four ");
		assertTrue(bean instanceof ExcludingPluginFilter);

		ExcludingPluginFilter filter = (ExcludingPluginFilter) bean;
		Set suppliedNames = filter.getSuppliedNames();
		assertEquals(2, suppliedNames.size());
		assertTrue(suppliedNames.contains("four"));
	}

	public void testDefaultFilter() throws Exception
	{
		PluginFilterRetriever fb = new PluginFilterRetriever();
		PluginFilter bean = fb.getPluginFilter(null, null);
		assertTrue(bean instanceof IdentityPluginFilter);
	}
}


text:
require "rails_helper"

describe "single sign on" do
  # We create an admin so they can impersonate. Otherwise behavior should be the same.
  let!(:actor) { create(:admin, id: 1234, first_name: "Tom", last_name: "Smyth", email: "tom@example.com") }
  let(:subdomain) { nil }
  let(:cluster) { Defaults.cluster }
  let(:community) { Defaults.community }
  let(:secret) { Settings.single_sign_on.secret }
  let(:valid_incoming_url) do
    qs = Rack::Utils.build_query(return_sso_url: "https://example.com/sso/login", nonce: "xyz")
    payload = Base64.strict_encode64(qs)
    sig = OpenSSL::HMAC.hexdigest("sha256", secret, payload)
    host = [subdomain, Settings.url.host].compact.join(".")
    "#{Settings.url.protocol}://#{host}:#{Settings.url.port}/sso?sso=#{CGI.escape(payload)}&sig=#{sig}"
  end
  let(:valid_redirect) do
    payload = "ZW1haWw9dG9tJTQwZXhhbXBsZS5jb20mZXh0ZXJuYWxfaWQ9MTIzNCZuYW1lPVRvbStTbXl0aCZub25jZT14eXomc"\
      "mV0dXJuX3Nzb191cmw9aHR0cHMlM0ElMkYlMkZleGFtcGxlLmNvbSUyRnNzbyUyRmxvZ2luJnVzZXJuYW1lPVRvbS"\
      "tTbXl0aCZjdXN0b20uZmlyc3RfbmFtZT1Ub20mY3VzdG9tLmxhc3RfbmFtZT1TbXl0aA=="
    sig = OpenSSL::HMAC.hexdigest("sha256", secret, payload)
    "https://example.com/sso/login?sso=#{CGI.escape(payload)}&sig=#{sig}"
  end

  before do
    cluster.update!(sso_secret: "clustersecret")
    community.update!(sso_secret: "communitysecret")
  end

  context "with signed in user" do
    before do
      # No subdomain
      login_as(actor, scope: :user)
    end

    shared_examples_for "redirects appropriately" do
      scenario do
        visit(valid_incoming_url)
        expect(current_url).to eq(valid_redirect)
      end
    end

    shared_examples_for "fails with bad signature" do
      scenario do
        visit(valid_incoming_url)
        expect(page).to have_content("Bad signature for payload.")
      end
    end

    context "with valid data" do
      context "when not impersonating" do
        context "with global secret and apex domain" do
          let(:secret) { Settings.single_sign_on.secret }
          let(:subdomain) { nil }
          it_behaves_like "redirects appropriately"
        end

        context "with cluster secret and subdomain from that cluster" do
          let(:secret) { "clustersecret" }
          let(:subdomain) { community.slug }
          it_behaves_like "redirects appropriately"
        end

        context "with community secret and subdomain for that community" do
          let(:secret) { "communitysecret" }
          let(:subdomain) { community.slug }
          it_behaves_like "redirects appropriately"
        end

        context "with global secret and subdomain for a community" do
          let(:secret) { Settings.single_sign_on.secret }
          let(:subdomain) { community.slug }
          it_behaves_like "fails with bad signature"
        end

        context "with cluster secret and apex domain" do
          let(:secret) { "clustersecret" }
          let(:subdomain) { nil }
          it_behaves_like "fails with bad signature"
        end

        context "with community secret and subdomain for a different community in the cluster" do
          let(:secret) { "communitysecret" }
          let(:community2) { create(:community) }
          let(:subdomain) { community2.slug }
          it_behaves_like "fails with bad signature"
        end
      end

      context "when impersonating" do
        let!(:user2) { create(:user, id: 1235, first_name: "X", last_name: "Z", email: "x@example.com") }

        before do
          visit("/users/1235")
          click_link("Impersonate")
        end

        it_behaves_like "redirects appropriately"
      end
    end

    context "with errant data" do
      scenario "returns error" do
        visit("/sso?sso=&sig=")
        expect(page.body).to eq("Return URL not given")
      end
    end

    context "with unauthorized user" do
      let(:actor) { create(:user, :inactive) }

      scenario "returns error" do
        visit("/sso?sso=xxx&sig=yyy")
        expect(page).to have_content("You are not permitted to view that page")
      end
    end
  end

  context "without signed in user" do
    it "redirects to home, allows sign in, then redirects" do
      visit(valid_incoming_url)
      click_on("Sign in with Password")
      fill_in("Email Address", with: "tom@example.com")
      fill_in("Password", with: FactoryBot::DEFAULT_PASSWORD)
      click_button("Sign In")
      expect(current_url).to eq(valid_redirect)
    end
  end
end


text:
package com.alibaba.excel.support;

/**
 * empty
 *
 * @author Jiaju Zhuang
 */
public class Empty {
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace KaoriStudio.Core.Binary.Formats
{
	/// <summary>
	/// Binary format structures.
	/// </summary>
	[CompilerGenerated]
	internal class NamespaceDoc
	{
	}
}


text:
module Geolocation
  VERSION = '0.1.0'
end


text:
///////////////////////////////////////////////////////////////////////////
//                   __                _      _   ________               //
//                  / /   ____  ____ _(_)____/ | / / ____/               //
//                 / /   / __ \/ __ `/ / ___/  |/ / / __                 //
//                / /___/ /_/ / /_/ / / /__/ /|  / /_/ /                 //
//               /_____/\____/\__, /_/\___/_/ |_/\____/                  //
//                           /____/                                      //
//                                                                       //
//               The Next Generation Logic Library                       //
//                                                                       //
///////////////////////////////////////////////////////////////////////////
//                                                                       //
//  Copyright 2015-20xx Christoph Zengler                                //
//                                                                       //
//  Licensed under the Apache License, Version 2.0 (the "License");      //
//  you may not use this file except in compliance with the License.     //
//  You may obtain a copy of the License at                              //
//                                                                       //
//  http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                       //
//  Unless required by applicable law or agreed to in writing, software  //
//  distributed under the License is distributed on an "AS IS" BASIS,    //
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      //
//  implied.  See the License for the specific language governing        //
//  permissions and limitations under the License.                       //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

package org.logicng.knowledgecompilation.bdds.datastructures;

import org.logicng.formulas.Variable;

import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * A node in a BDD.
 * @version 1.4.0
 * @since 1.4.0
 */
public final class BDDInnerNode implements BDDNode {

    private final Variable var;
    private final BDDNode low;
    private final BDDNode high;

    /**
     * Constructor for a new inner BDD node holding a variable.
     * @param var  the variable
     * @param low  the low child node
     * @param high the high child node
     */
    public BDDInnerNode(final Variable var, final BDDNode low, final BDDNode high) {
        this.var = var;
        this.low = low;
        this.high = high;
    }

    @Override
    public Variable label() {
        return this.var;
    }

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

    @Override
    public BDDNode low() {
        return this.low;
    }

    @Override
    public BDDNode high() {
        return this.high;
    }

    @Override
    public Set<BDDNode> nodes() {
        final Set<BDDNode> res = new HashSet<>(Collections.singleton(this));
        res.addAll(this.low.nodes());
        res.addAll(this.high.nodes());
        return res;
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.var, this.low, this.high);
    }

    @Override
    public boolean equals(final Object other) {
        if (this == other) {
            return true;
        }
        if (other instanceof BDDInnerNode) {
            final BDDInnerNode o = (BDDInnerNode) other;
            return Objects.equals(this.var, o.var)
                    && Objects.equals(this.low, o.low)
                    && Objects.equals(this.high, o.high);
        }
        return false;
    }

    @Override
    public String toString() {
        return "<" + this.var + " | low=" + this.low + " high=" + this.high + ">";
    }
}


text:
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'

module ActiveRecord
  module FinderMethods
    # Find operates with four different retrieval approaches:
    #
    # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
    #   If no record can be found for all of the listed ids, then RecordNotFound will be raised.
    # * Find first - This will return the first record matched by the options used. These options can either be specific
    #   conditions or merely an order. If no record can be matched, +nil+ is returned. Use
    #   <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
    # * Find last - This will return the last record matched by the options used. These options can either be specific
    #   conditions or merely an order. If no record can be matched, +nil+ is returned. Use
    #   <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
    # * Find all - This will return all the records matched by the options used.
    #   If no records are found, an empty array is returned. Use
    #   <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
    #
    # All approaches accept an options hash as their last parameter.
    #
    # ==== Options
    #
    # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
    #   or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
    # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
    # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
    # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
    #   <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
    # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
    # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
    #   it would skip rows 0 through 4.
    # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
    #   named associations in the same form used for the <tt>:include</tt> option, which will perform an
    #   <tt>INNER JOIN</tt> on the associated table(s),
    #   or an array containing a mixture of both strings and named associations.
    #   If the value is a string, then the records will be returned read-only since they will
    #   have attributes that do not correspond to the table's columns.
    #   Pass <tt>:readonly => false</tt> to override.
    # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
    #   to already defined associations. See eager loading under Associations.
    # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
    #   for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
    # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
    #   to an alternate table name (or even the name of a database view).
    # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
    # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
    #   <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
    #
    # ==== Examples
    #
    #   # find by id
    #   Person.find(1)       # returns the object for ID = 1
    #   Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
    #   Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
    #   Person.find([1])     # returns an array for the object with ID = 1
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
    #
    # Note that returned records may not be in the same order as the ids you
    # provide since database rows are unordered. Give an explicit <tt>:order</tt>
    # to ensure the results are sorted.
    #
    # ==== Examples
    #
    #   # find first
    #   Person.first # returns the first object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).first
    #   Person.where(["user_name = :u", { :u => user_name }]).first
    #   Person.order("created_on DESC").offset(5).first
    #
    #   # find last
    #   Person.last # returns the last object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).last
    #   Person.order("created_on DESC").offset(5).last
    #
    #   # find all
    #   Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
    #   Person.where(["category IN (?)", categories]).limit(50).all
    #   Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
    #   Person.offset(10).limit(10).all
    #   Person.includes([:account, :friends]).all
    #   Person.group("category").all
    #
    # Example for find with a lock: Imagine two concurrent transactions:
    # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
    # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
    # transaction has to wait until the first is finished; we get the
    # expected <tt>person.visits == 4</tt>.
    #
    #   Person.transaction do
    #     person = Person.lock(true).find(1)
    #     person.visits += 1
    #     person.save!
    #   end
    def find(*args)
      return to_a.find { |*block_args| yield(*block_args) } if block_given?

      options = args.extract_options!

      if options.present?
        apply_finder_options(options).find(*args)
      else
        case args.first
        when :first, :last, :all
          send(args.first)
        else
          find_with_ids(*args)
        end
      end
    end

    # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
    # same arguments to this method as you can to <tt>find(:first)</tt>.
    def first(*args)
      if args.any?
        if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
          limit(*args).to_a
        else
          apply_finder_options(args.first).first
        end
      else
        find_first
      end
    end

    # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found. Note that <tt>first!</tt> accepts no arguments.
    def first!
      first or raise RecordNotFound
    end

    # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
    # same arguments to this method as you can to <tt>find(:last)</tt>.
    def last(*args)
      if args.any?
        if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
          if order_values.empty?
            order("#{primary_key} DESC").limit(*args).reverse
          else
            to_a.last(*args)
          end
        else
          apply_finder_options(args.first).last
        end
      else
        find_last
      end
    end

    # Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found. Note that <tt>last!</tt> accepts no arguments.
    def last!
      last or raise RecordNotFound
    end

    # A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
    # same arguments to this method as you can to <tt>find(:all)</tt>.
    def all(*args)
      args.any? ? apply_finder_options(args.first).to_a : to_a
    end

    # Returns true if a record exists in the table that matches the +id+ or
    # conditions given, or false otherwise. The argument can take five forms:
    #
    # * Integer - Finds the record with this primary key.
    # * String - Finds the record with a primary key corresponding to this
    #   string (such as <tt>'5'</tt>).
    # * Array - Finds the record that matches these +find+-style conditions
    #   (such as <tt>['color = ?', 'red']</tt>).
    # * Hash - Finds the record that matches these +find+-style conditions
    #   (such as <tt>{:color => 'red'}</tt>).
    # * No args - Returns false if the table is empty, true otherwise.
    #
    # For more information about specifying conditions as a Hash or Array,
    # see the Conditions section in the introduction to ActiveRecord::Base.
    #
    # Note: You can't pass in a condition as a string (like <tt>name =
    # 'Jamie'</tt>), since it would be sanitized and then queried against
    # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
    #
    # ==== Examples
    #   Person.exists?(5)
    #   Person.exists?('5')
    #   Person.exists?(:name => "David")
    #   Person.exists?(['name LIKE ?', "%#{query}%"])
    #   Person.exists?
    def exists?(id = false)
      id = id.id if ActiveRecord::Base === id
      return false if id.nil?

      join_dependency = construct_join_dependency_for_association_find
      relation = construct_relation_for_association_find(join_dependency)
      relation = relation.except(:select, :order).select("1 AS one").limit(1)

      case id
      when Array, Hash
        relation = relation.where(id)
      else
        relation = relation.where(table[primary_key].eq(id)) if id
      end

      connection.select_value(relation, "#{name} Exists") ? true : false
    rescue ThrowResult
      false
    end

    protected

    def find_with_associations
      join_dependency = construct_join_dependency_for_association_find
      relation = construct_relation_for_association_find(join_dependency)
      rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
      join_dependency.instantiate(rows)
    rescue ThrowResult
      []
    end

    def construct_join_dependency_for_association_find
      including = (@eager_load_values + @includes_values).uniq
      ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
    end

    def construct_relation_for_association_calculations
      including = (@eager_load_values + @includes_values).uniq
      join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
      relation = except(:includes, :eager_load, :preload)
      apply_join_dependency(relation, join_dependency)
    end

    def construct_relation_for_association_find(join_dependency)
      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
      apply_join_dependency(relation, join_dependency)
    end

    def apply_join_dependency(relation, join_dependency)
      join_dependency.join_associations.each do |association|
        relation = association.join_relation(relation)
      end

      limitable_reflections = using_limitable_reflections?(join_dependency.reflections)

      if !limitable_reflections && relation.limit_value
        limited_id_condition = construct_limited_ids_condition(relation.except(:select))
        relation = relation.where(limited_id_condition)
      end

      relation = relation.except(:limit, :offset) unless limitable_reflections

      relation
    end

    def construct_limited_ids_condition(relation)
      orders = relation.order_values.map { |val| val.presence }.compact
      values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)

      relation = relation.dup

      ids_array = relation.select(values).collect {|row| row[primary_key]}
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
    end

    def find_by_attributes(match, attributes, *args)
      conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
      result = where(conditions).send(match.finder)

      if match.bang? && result.blank?
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
      else
        yield(result) if block_given?
        result
      end
    end

    def find_or_instantiator_by_attributes(match, attributes, *args)
      options = args.size > 1 && args.last(2).all?{ |a| a.is_a?(Hash) } ? args.extract_options! : {}
      protected_attributes_for_create, unprotected_attributes_for_create = {}, {}
      args.each_with_index do |arg, i|
        if arg.is_a?(Hash)
          protected_attributes_for_create = args[i].with_indifferent_access
        else
          unprotected_attributes_for_create[attributes[i]] = args[i]
        end
      end

      conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys

      record = where(conditions).first

      unless record
        record = @klass.new(protected_attributes_for_create, options) do |r|
          r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
        end
        yield(record) if block_given?
        record.send(match.save_method) if match.save_record?
      end

      record
    end

    def find_with_ids(*ids)
      return to_a.find { |*block_args| yield(*block_args) } if block_given?

      expects_array = ids.first.kind_of?(Array)
      return ids.first if expects_array && ids.first.empty?

      ids = ids.flatten.compact.uniq

      case ids.size
      when 0
        raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
      when 1
        result = find_one(ids.first)
        expects_array ? [ result ] : result
      else
        find_some(ids)
      end
    end

    def find_one(id)
      id = id.id if ActiveRecord::Base === id

      if IdentityMap.enabled? && where_values.blank? &&
        limit_value.blank? && order_values.blank? &&
        includes_values.blank? && preload_values.blank? &&
        readonly_value.nil? && joins_values.blank? &&
        !@klass.locking_enabled? &&
        record = IdentityMap.get(@klass, id)
        return record
      end

      column = columns_hash[primary_key]

      substitute = connection.substitute_at(column, @bind_values.length)
      relation = where(table[primary_key].eq(substitute))
      relation.bind_values = [[column, id]]
      record = relation.first

      unless record
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
      end

      record
    end

    def find_some(ids)
      result = where(table[primary_key].in(ids)).all

      expected_size =
        if @limit_value && ids.size > @limit_value
          @limit_value
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
      if @offset_value && (ids.size - @offset_value < expected_size)
        expected_size = ids.size - @offset_value
      end

      if result.size == expected_size
        result
      else
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions

        error = "Couldn't find all #{@klass.name.pluralize} with IDs "
        error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
        raise RecordNotFound, error
      end
    end

    def find_first
      if loaded?
        @records.first
      else
        @first ||= limit(1).to_a[0]
      end
    end

    def find_last
      if loaded?
        @records.last
      else
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
            reverse_order.limit(1).to_a[0]
          end
      end
    end

    def using_limitable_reflections?(reflections)
      reflections.none? { |r| r.collection? }
    end
  end
end


text:
<?php

namespace Kanboard\Model;

use Kanboard\Core\Security\Role;

/**
 * Project Permission
 *
 * @package  model
 * @author   Frederic Guillot
 */
class ProjectPermission extends Base
{
    /**
     * Get query for project users overview
     *
     * @access public
     * @param  array    $project_ids
     * @param  string   $role
     * @return \PicoDb\Table
     */
    public function getQueryByRole(array $project_ids, $role)
    {
        if (empty($project_ids)) {
            $project_ids = array(-1);
        }

        return $this
            ->db
            ->table(ProjectUserRole::TABLE)
            ->join(User::TABLE, 'id', 'user_id')
            ->join(Project::TABLE, 'id', 'project_id')
            ->eq(ProjectUserRole::TABLE.'.role', $role)
            ->eq(Project::TABLE.'.is_private', 0)
            ->in(Project::TABLE.'.id', $project_ids)
            ->columns(
                User::TABLE.'.id',
                User::TABLE.'.username',
                User::TABLE.'.name',
                Project::TABLE.'.name AS project_name',
                Project::TABLE.'.id'
            );
    }

    /**
     * Get all usernames (fetch users from groups)
     *
     * @access public
     * @param  integer $project_id
     * @param  string  $input
     * @return array
     */
    public function findUsernames($project_id, $input)
    {
        $userMembers = $this->projectUserRoleFilter->create()->filterByProjectId($project_id)->startWithUsername($input)->findAll('username');
        $groupMembers = $this->projectGroupRoleFilter->create()->filterByProjectId($project_id)->startWithUsername($input)->findAll('username');
        $members = array_unique(array_merge($userMembers, $groupMembers));

        sort($members);

        return $members;
    }

    /**
     * Return true if everybody is allowed for the project
     *
     * @access public
     * @param  integer   $project_id   Project id
     * @return bool
     */
    public function isEverybodyAllowed($project_id)
    {
        return $this->db
                    ->table(Project::TABLE)
                    ->eq('id', $project_id)
                    ->eq('is_everybody_allowed', 1)
                    ->exists();
    }

    /**
     * Return true if the user is allowed to access a project
     *
     * @param integer $project_id
     * @param integer $user_id
     * @return boolean
     */
    public function isUserAllowed($project_id, $user_id)
    {
        if ($this->userSession->isAdmin()) {
            return true;
        }

        return in_array(
            $this->projectUserRole->getUserRole($project_id, $user_id),
            array(Role::PROJECT_MANAGER, Role::PROJECT_MEMBER, Role::PROJECT_VIEWER)
        );
    }

    /**
     * Return true if the user is assignable
     *
     * @access public
     * @param  integer  $project_id
     * @param  integer  $user_id
     * @return boolean
     */
    public function isAssignable($project_id, $user_id)
    {
        return $this->user->isActive($user_id) &&
            in_array($this->projectUserRole->getUserRole($project_id, $user_id), array(Role::PROJECT_MEMBER, Role::PROJECT_MANAGER));
    }

    /**
     * Return true if the user is member
     *
     * @access public
     * @param  integer  $project_id
     * @param  integer  $user_id
     * @return boolean
     */
    public function isMember($project_id, $user_id)
    {
        return in_array($this->projectUserRole->getUserRole($project_id, $user_id), array(Role::PROJECT_MEMBER, Role::PROJECT_MANAGER, Role::PROJECT_VIEWER));
    }

    /**
     * Get active project ids by user
     *
     * @access public
     * @param  integer $user_id
     * @return array
     */
    public function getActiveProjectIds($user_id)
    {
        return array_keys($this->projectUserRole->getActiveProjectsByUser($user_id));
    }

    /**
     * Copy permissions to another project
     *
     * @param  integer  $project_src_id  Project Template
     * @param  integer  $project_dst_id  Project that receives the copy
     * @return boolean
     */
    public function duplicate($project_src_id, $project_dst_id)
    {
        return $this->projectUserRole->duplicate($project_src_id, $project_dst_id) &&
            $this->projectGroupRole->duplicate($project_src_id, $project_dst_id);
    }
}


text:
#include "pocl_cl.h"
#include "pocl_mem_management.h"
#include "pocl_shared.h"
#include "pocl_util.h"

CL_API_ENTRY cl_int
POname (clCommandFillBufferKHR) (
    cl_command_buffer_khr command_buffer, cl_command_queue command_queue,
    cl_mem buffer, const void *pattern, size_t pattern_size, size_t offset,
    size_t size, cl_uint num_sync_points_in_wait_list,
    const cl_sync_point_khr *sync_point_wait_list,
    cl_sync_point_khr *sync_point,
    cl_mutable_command_khr *mutable_handle) CL_API_SUFFIX__VERSION_1_2
{
  cl_int errcode;
  _cl_command_node *cmd = NULL;

  CMDBUF_VALIDATE_COMMON_HANDLES;

  errcode = pocl_fill_buffer_common (command_buffer, command_queue, buffer,
                                     pattern, pattern_size, offset, size,
                                     num_sync_points_in_wait_list, NULL, NULL,
                                     sync_point_wait_list, sync_point, &cmd);

  if (errcode != CL_SUCCESS)
    return errcode;

  errcode = pocl_command_record (command_buffer, cmd, sync_point);
  if (errcode != CL_SUCCESS)
    goto ERROR;

  return CL_SUCCESS;

ERROR:
  pocl_mem_manager_free_command (cmd);
  return errcode;
}
POsym (clCommandFillBufferKHR)


text:
package io.shaoshuai.rms.system.dao;

import io.shaoshuai.common.dao.IBaseMapper;
import io.shaoshuai.rms.system.po.Dictionary;
import io.shaoshuai.rms.system.po.DictionaryExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface DictionaryMapper extends IBaseMapper<Dictionary, Integer> {

    int countByExample(DictionaryExample example);

    int deleteByExample(DictionaryExample example);

    List<Dictionary> selectByExample(DictionaryExample example);

    int updateByExampleSelective(@Param("record") Dictionary record, @Param("example") DictionaryExample example);

    int updateByExample(@Param("record") Dictionary record, @Param("example") DictionaryExample example);

}


text:
require 'addressable/uri'
require "net/http"
require 'omniauth'
require "openid_connect"

module OmniAuth
  module Strategies
    class OpenIDConnect
      include OmniAuth::Strategy

      option :client_options, {
        identifier: nil,
        secret: nil,
        redirect_uri: nil,
        scheme: "https",
        host: nil,
        port: 443,
        authorization_endpoint: "/authorize",
        token_endpoint: "/token",
        userinfo_endpoint: "/userinfo"
      }
      option :scope, [:openid]
      option :response_type, "code"
      option :state
      option :response_mode
      option :display, nil#, [:page, :popup, :touch, :wap]
      option :prompt, nil#, [:none, :login, :consent, :select_account]
      option :max_age
      option :ui_locales
      option :id_token_hint
      option :login_hint
      option :acr_values
      option :client_auth_method
      option :send_nonce, true

      uid { user_info.sub }

      info do
        {
          name: user_info.name,
          email: user_info.email,
          nickname: user_info.preferred_username,
          first_name: user_info.given_name,
          last_name: user_info.family_name,
          image: user_info.picture,
          phone: user_info.phone_number,
          urls: { website: user_info.website }
        }
      end

      extra do
        { raw_info: fix_user_info(user_info).as_json } # UserInfo#as_json actually returns a hash
      end

      credentials do
        { token: access_token.access_token }
      end

      def client
        @client ||= ::OpenIDConnect::Client.new(client_options)
      end

      def request_phase
        redirect authorize_uri
      end

      def callback_phase
        if !session["state"].nil? && session["state"] != request.params["state"]
          return Rack::Response.new(['401 Unauthorized'], 401).finish
        end

        if !request.params["code"]
          return fail!(:missing_code, OmniAuth::OpenIDConnect::MissingCodeError.new(request.params["error"]))
        end

        client.redirect_uri = client_options.redirect_uri
        client.authorization_code = authorization_code
        access_token

        super
      end

      def authorization_code
        request.params["code"]
      end

      def authorize_uri
        client.redirect_uri = client_options.redirect_uri

        opts = {
          response_type: options.response_type,
          scope: options.scope,
          nonce: (nonce if options.send_nonce),
          state: (session["state"] = options.state.call if options.state.respond_to? :call)
        }
        client.authorization_uri(opts.reject { |_,v| v.nil? })
      end

      private

      def user_info
        @user_info ||= access_token.userinfo!
      end

      ##
      # Google sends the string "true" as the value for the field 'email_verified' while a boolean is expected.
      def fix_user_info(user_info)
        if user_info.email_verified.is_a? String
          user_info.email_verified = (user_info.email_verified == "true")
        end
        user_info.gender = nil # in case someone picks something else than male or female, we don't need it anyway
        user_info
      end

      def access_token
        @access_token ||= client.access_token!(:client_auth_method => options.client_auth_method)
      end

      def client_options
        options.client_options
      end

      def nonce
        session[:nonce] = SecureRandom.hex(16)
      end

      def session
        @env.nil? ? {} : super
      end
    end
  end
end

OmniAuth.config.add_camelization 'openid_connect', 'OpenIDConnect'


text:
from chatterbot.adapters.storage import StorageAdapter
from chatterbot.conversation import Statement, Response
from jsondb import Database
import warnings

class JsonFileStorageAdapter(StorageAdapter):
    """
    This adapter allows ChatterBot to store conversation
    data in a file in JSON format.
    """

    def __init__(self, **kwargs):
        super(JsonFileStorageAdapter, self).__init__(**kwargs)

        if not kwargs.get('silence_performance_warning', False):
            warnings.warn(
                'The JsonFileStorageAdapter is not recommended for production application environments.',
                self.UnsuitableForProductionWarning
            )

        database_path = self.kwargs.get('database', 'database.db')
        self.database = Database(database_path)

        self.adapter_supports_queries = False

    def _keys(self):
        # The value has to be cast as a list for Python 3 compatibility
        return list(self.database[0].keys())

    def count(self):
        return len(self._keys())

    def find(self, statement_text):
        values = self.database.data(key=statement_text)

        if not values:
            return None

        values['text'] = statement_text

        return self.json_to_object(values)

    def remove(self, statement_text):
        """
        Removes the statement that matches the input text.
        Removes any responses from statements if the response text matches the
        input text.
        """
        for statement in self.filter(in_response_to__contains=statement_text):
            statement.remove_response(statement_text)
            self.update(statement)

        self.database.delete(statement_text)

    def deserialize_responses(self, response_list):
        """
        Takes the list of response items and returns
        the list converted to Response objects.
        """
        proxy_statement = Statement('')

        for response in response_list:
            data = response.copy()
            text = data['text']
            del(data['text'])

            proxy_statement.add_response(
                Response(text, **data)
            )

        return proxy_statement.in_response_to

    def json_to_object(self, statement_data):

        # Don't modify the referenced object
        statement_data = statement_data.copy()

        # Build the objects for the response list
        statement_data['in_response_to'] = self.deserialize_responses(
            statement_data['in_response_to']
        )

        # Remove the text attribute from the values
        text = statement_data.pop('text')

        return Statement(text, **statement_data)

    def _all_kwargs_match_values(self, kwarguments, values):
        for kwarg in kwarguments:

            if '__' in kwarg:
                kwarg_parts = kwarg.split('__')

                key = kwarg_parts[0]
                identifier = kwarg_parts[1]

                if identifier == 'contains':
                    text_values = []
                    for val in values[key]:
                        text_values.append(val['text'])

                    if (kwarguments[kwarg] not in text_values) and (
                            kwarguments[kwarg] not in values[key]):
                        return False

            if kwarg in values:
                if values[kwarg] != kwarguments[kwarg]:
                    return False

        return True

    def filter(self, **kwargs):
        """
        Returns a list of statements in the database
        that match the parameters specified.
        """
        results = []

        for key in self._keys():
            values = self.database.data(key=key)

            # Add the text attribute to the values
            values['text'] = key

            if self._all_kwargs_match_values(kwargs, values):

                results.append(self.json_to_object(values))

        return results

    def update(self, statement, **kwargs):
        # Do not alter the database unless writing is enabled
        if not self.read_only:
            data = statement.serialize()

            # Remove the text key from the data
            del(data['text'])
            self.database.data(key=statement.text, value=data)

            # Make sure that an entry for each response exists
            for response_statement in statement.in_response_to:
                response = self.find(response_statement.text)
                if not response:
                    response = Statement(response_statement.text)
                    self.update(response)

        return statement

    def get_random(self):
        from random import choice

        if self.count() < 1:
            raise self.EmptyDatabaseException()

        statement = choice(self._keys())
        return self.find(statement)

    def drop(self):
        """
        Remove the json file database completely.
        """
        import os

        if os.path.exists(self.database.path):
            os.remove(self.database.path)

    class UnsuitableForProductionWarning(Warning):
        pass