text:
#include <VolumeViz/render/3D/Cvr3DTexCube.h>

#include <limits.h>
#include <string.h>

#include <Inventor/C/glue/gl.h>
#include <Inventor/C/tidbits.h>
#include <Inventor/SbLinear.h>
#include <Inventor/SbViewVolume.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/elements/SoModelMatrixElement.h>
#include <Inventor/elements/SoProjectionMatrixElement.h>
#include <Inventor/elements/SoViewVolumeElement.h>
#include <Inventor/elements/SoViewingMatrixElement.h>
#include <Inventor/errors/SoDebugError.h>

#include <VolumeViz/elements/CvrPageSizeElement.h>
#include <VolumeViz/elements/CvrVoxelBlockElement.h>
#include <VolumeViz/elements/SoTransferFunctionElement.h>
#include <VolumeViz/misc/CvrCLUT.h>
#include <VolumeViz/misc/CvrUtil.h>
#include <VolumeViz/nodes/SoTransferFunction.h>
#include <VolumeViz/render/common/Cvr3DPaletteTexture.h>
#include <VolumeViz/render/common/Cvr3DRGBATexture.h>
#include <VolumeViz/render/3D/Cvr3DTexSubCube.h>

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

class Cvr3DTexSubCubeItem {
public:
  Cvr3DTexSubCubeItem(Cvr3DTexSubCube * p) { this->cube = p; }
  Cvr3DTexSubCube * cube;
  uint32_t volumedataid; // FIXME: seems bogus to store this here, as
                         // all sub-cubes will have the same
                         // value. 20040916 mortene.

  SbBool invisible; // If this flag is set, the value of "cube" should
                    // be NULL.

  // Distance from camera projection point (in the near plane) to the
  // sub-cube's center. Used for comparison with other sub-cubes when
  // qsort'ing by depth vs camera position.
  float distancefromcamera;

  float boundingsphereradius;
  float cameraplane2cubecenter;
};

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

Cvr3DTexCube::Cvr3DTexCube(const SoGLRenderAction * action)
{
  this->clut = NULL;
  this->subcubes = NULL;

  SoState * state = action->getState();

  this->subcubesize =
    Cvr3DTexCube::clampSubCubeSize(CvrPageSizeElement::get(state));

  if (CvrUtil::doDebugging()) {
    SoDebugError::postInfo("Cvr3DTexCube::Cvr3DTexCube",
                           "subcubedimensions==<%d, %d, %d>",
                           this->subcubesize[0],
                           this->subcubesize[1],
                           this->subcubesize[2]);
  }

  const CvrVoxelBlockElement * vbelem = CvrVoxelBlockElement::getInstance(state);
  const SbVec3s & dim = vbelem->getVoxelCubeDimensions();

  assert(dim[0] > 0);
  assert(dim[1] > 0);
  assert(dim[2] > 0);

  this->dimensions = dim;
  this->origo = SbVec3f(-((float) dim[0]) / 2.0f, -((float) dim[1]) / 2.0f, -((float) dim[2]) / 2.0f);

  this->nrcolumns = (this->dimensions[0] + this->subcubesize[0] - 1) / this->subcubesize[0];
  this->nrrows = (this->dimensions[1] + this->subcubesize[1] - 1) / this->subcubesize[1];
  this->nrdepths = (this->dimensions[2] + this->subcubesize[2] - 1) / this->subcubesize[2];

  this->abortfunc = NULL;
  this->abortfuncdata = NULL;
}

Cvr3DTexCube::~Cvr3DTexCube()
{
  this->releaseAllSubCubes();
  if (this->clut) { this->clut->unref(); }
}

void
Cvr3DTexCube::setAbortCallback(SoVolumeRenderAbortCB * func, void * userdata)
{
  this->abortfunc = func;
  this->abortfuncdata = userdata;
}

/*!
  Release resources used by a page in the slice.
*/
void
Cvr3DTexCube::releaseSubCube(const unsigned int row, const unsigned int col, const unsigned int depths)
{
  const int idx = this->calcSubCubeIdx(row, col, depths);
  Cvr3DTexSubCubeItem * p = this->subcubes[idx];
  if (p) {
    this->subcubes[idx] = NULL;
    delete p->cube;
    delete p;
  }
}

void
Cvr3DTexCube::releaseAllSubCubes(void)
{
  if (this->subcubes == NULL) return;

  for (unsigned int row = 0; row < this->nrrows; row++) {
    for (unsigned int col = 0; col < this->nrcolumns; col++) {
      for (unsigned int depth = 0; depth < this->nrdepths; depth++) {
        this->releaseSubCube(row, col, depth);
      }
    }
  }

  delete[] this->subcubes;
  this->subcubes = NULL;
}

static int
subcube_qsort_compare(const void * element1, const void * element2)
{
  Cvr3DTexSubCubeItem ** sc1 = (Cvr3DTexSubCubeItem **) element1;
  Cvr3DTexSubCubeItem ** sc2 = (Cvr3DTexSubCubeItem **) element2;

  return ((*sc1)->distancefromcamera > (*sc2)->distancefromcamera) ? -1 : 1;
}

SbVec3s
Cvr3DTexCube::clampSubCubeSize(const SbVec3s & size)
{
  // FIXME: this doesn't guarantee that we can actually use a texture
  // of this size, should instead use Coin's
  // cc_glglue_is_texture_size_legal() (at least in combination with
  // the subcubesize found here). 20040709 mortene.
  //
  // UPDATE: the above Coin cc_glglue function was introduced with
  // Coin 2.3, so we can't use this without first separating out the
  // gl-wrapper, as planned. 20040714 mortene.

  // FIXME: this design is a bit bogus. Consider this: the size can be
  // set in one GL context, but the tex-cube can later be attempted
  // used in another GL context, with a smaller max size. Not sure how
  // to fix this yet. 20041221 mortene.

  GLint maxsize = -1;
  glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &maxsize);

  // This has been reported by an external developer to hit on an ATI
  // OpenGL driver on a Linux system. As 3D texture based rendering
  // otherwise seemed to work just fine, we simply warn, correct the
  // problem, and go on.
  if (maxsize == -1) {
    static const char CVR_IGNORE_ATI_QUERY_BUG[] = "CVR_IGNORE_ATI_QUERY_BUG";
    const char * env = coin_getenv(CVR_IGNORE_ATI_QUERY_BUG);

    static SbBool first = TRUE;
    if (first && (env == NULL)) {
      SoDebugError::postWarning("Cvr3DTexCube::clampSubCubeSize",
                                "Obscure bug found with your OpenGL driver. "
                                "If you are employed by Systems in Motion, "
                                "report this occurrence to <mortene@sim.no> "
                                "for further debugging. Otherwise, you can "
                                "safely ignore this warning. (Set the "
                                "environment variable '%s' on the system to "
                                "not get this notification again.)",
                                CVR_IGNORE_ATI_QUERY_BUG);
    }
    first = FALSE;
    maxsize = 128; // this should be safe
  }

  if (CvrUtil::doDebugging()) {
    SoDebugError::postInfo("Cvr3DTexCube::clampSubCubeSize",
                           "GL_MAX_3D_TEXTURE_SIZE==%d", maxsize);
  }

  const char * envstr = coin_getenv("CVR_FORCE_SUBCUBE_SIZE");
  if (envstr) {
    short forcedsubcubesize = atoi(envstr);
    assert(forcedsubcubesize > 0);
    assert(forcedsubcubesize <= maxsize && "subcube size must be <= than max 3D texture size");
    assert(coin_is_power_of_two(forcedsubcubesize) && "subcube size must be power of two");
    return SbVec3s(forcedsubcubesize, forcedsubcubesize, forcedsubcubesize);
  }

  // FIXME: My GeforceFX 5600 card sometime fails when asking for 512 as
  // cube size even if it is supposed to handle it. (20040302 handegar)
  //maxsize = SbMin(256, maxsize);

  assert((maxsize < SHRT_MAX) && "unsafe cast");
  const short smax = (short)maxsize;
  return SbVec3s(SbMin(size[0], smax), SbMin(size[1], smax), SbMin(size[2], smax));
}

// Called by all the 'render*()' methods after the intersection test.
void
Cvr3DTexCube::renderResult(const SoGLRenderAction * action,
                           SbList <Cvr3DTexSubCubeItem *> & subcubelist)
{
  // Render all subcubes.
  for (int i=0;i<subcubelist.getLength();++i) {
    subcubelist[i]->cube->render(action);
  }
  subcubelist.truncate(0);
}

// Renders arbitrary positioned quad, textured for the cube (slice)
// represented by this object. Loads all the cubes needed.
void
Cvr3DTexCube::render(const SoGLRenderAction * action,
                     unsigned int numslices)
{
  // For debugging purposes, make it possible to override the number
  // of slices to render with an envvar:
  static unsigned int forcednumslices = UINT_MAX;
  if (forcednumslices == UINT_MAX) {
    const char * env = coin_getenv("CVR_DEBUG_MAX_SLICES");
    int num = 0;
    if (env) { num = atoi(env); }
    assert(num >= 0);
    forcednumslices = num;
  }
  if (forcednumslices != 0) { numslices = forcednumslices; }

  const cc_glglue * glglue = cc_glglue_instance(action->getCacheContext());

  SoState * state = action->getState();

  const SbVec3f subcubewidth(this->subcubesize[0], 0, 0);
  const SbVec3f subcubeheight(0, this->subcubesize[1], 0);
  const SbVec3f subcubedepth(0, 0, this->subcubesize[2]);

  const SbViewVolume & viewvolume = SoViewVolumeElement::get(state);
  SbViewVolume viewvolumeinv = viewvolume;
  viewvolumeinv.transform(SoModelMatrixElement::get(state).inverse());

  SbBox3f bbox(this->origo, this->origo +
               SbVec3f(this->dimensions[0],
                       this->dimensions[1],
                       this->dimensions[2]));
  bbox.transform(SoModelMatrixElement::get(state));
  float dx, dy, dz;
  bbox.getSize(dx, dy, dz);
  const float bboxradius = SbVec3f(dx, dy, dz).length() * 0.5f;

  const SbPlane camplane = viewvolume.getPlane(0.0f);
  const SbPlane invcamplane = viewvolumeinv.getPlane(0.0f);
  const SbVec3f bboxcenter = bbox.getCenter();
  const float neardistance = SbAbs(camplane.getDistance(bboxcenter)) - bboxradius;
  const float fardistance = SbAbs(camplane.getDistance(bboxcenter)) + bboxradius;
  const float distancedelta = (fardistance - neardistance) / numslices;
  const SbMatrix mat = SoModelMatrixElement::get(state).inverse();

  SbList <Cvr3DTexSubCubeItem *> subcubelist;

  unsigned int startrow = 0, endrow = this->nrrows - 1;
  unsigned int startcolumn = 0, endcolumn = this->nrcolumns - 1;
  unsigned int startdepth = 0, enddepth = this->nrdepths - 1;

  // debug: this block of code detects and forces rendering of just a
  // single sub-cube if that is wanted
  static unsigned int forcerow = UINT_MAX, forcecolumn, forcedepth;
  if (forcerow == UINT_MAX) {
    const char * str = coin_getenv("CVR_DEBUG_FORCE_SUBCUBE");
    if (str) {
      const int nr =
        sscanf(str, "%u,%u,%u", &forcerow, &forcecolumn, &forcedepth);
      assert(nr == 3 && "Invalid CVR_DEBUG_FORCE_SUBCUBE param. Expected '=X,Y,Z'");
      SoDebugError::postInfo("Cvr3DTexCube::render",
                             "debug: forced rendering of sub-cube "
                             "<%u, %u, %u> only",
                             forcerow, forcecolumn, forcedepth);
      assert(forcerow < this->nrrows);
      assert(forcecolumn < this->nrcolumns);
      assert(forcedepth < this->nrdepths);
    }
    else {
      forcerow--;
    }
  }
  if (forcerow != UINT_MAX - 1) {
    startrow = endrow = forcerow;
    startcolumn = endcolumn = forcecolumn;
    startdepth = enddepth = forcedepth;
  }
  // debug end

  for (unsigned int rowidx = startrow; rowidx <= endrow; rowidx++) {
    for (unsigned int colidx = startcolumn; colidx <= endcolumn; colidx++) {
      for (unsigned int depthidx = startdepth; depthidx <= enddepth; depthidx++) {

        Cvr3DTexSubCubeItem * cubeitem = this->getSubCube(state, colidx, rowidx, depthidx);

        const SbVec3f subcubeorigo =
          this->origo +
          subcubewidth * (float)colidx +
          subcubeheight * (float)rowidx +
          subcubedepth * (float)depthidx;

        if (cubeitem == NULL) {
          cubeitem = this->buildSubCube(action, subcubeorigo, colidx, rowidx, depthidx);
        }
        assert(cubeitem != NULL);

        if (cubeitem->invisible) continue;
        assert(cubeitem->cube != NULL);

        subcubelist.append(cubeitem);

        SbBox3f subbbox(subcubeorigo, subcubeorigo + subcubeheight + subcubewidth + subcubedepth);
        float dist = -invcamplane.getDistance(subbbox.getCenter());

        //subbbox.transform(SoModelMatrixElement::get(state));

        if (viewvolumeinv.getProjectionType() == SbViewVolume::ORTHOGRAPHIC) {
          cubeitem->distancefromcamera = dist;
        }
        else {
          SbVec3f p = viewvolumeinv.getProjectionPoint();

          cubeitem->distancefromcamera =
            (float) sqrt((viewvolumeinv.getProjectionPoint() - subbbox.getCenter()).length());

          if (dist < 0) {
            cubeitem->distancefromcamera = -cubeitem->distancefromcamera;
          }
        }

        subbbox.transform(SoModelMatrixElement::get(state));
        float sdx, sdy, sdz;
        subbbox.getSize(sdx, sdy, sdz);
        cubeitem->boundingsphereradius = SbVec3f(sdx, sdy, sdz).length() * 0.5f;
        cubeitem->cameraplane2cubecenter = SbAbs(camplane.getDistance(subbbox.getCenter()));

#if 0 // debug
        printf("cubeitem %u,%u,%u, distancefromcamera==%f, boundingsphereradius==%f, "
               "cameraplane2cubecenter==%f\n",
               rowidx, colidx, depthidx,
               cubeitem->distancefromcamera,
               cubeitem->boundingsphereradius,
               cubeitem->cameraplane2cubecenter);
#endif // debug
      }
    }
  }

  // FIXME: Can we rewrite this to support viewport shells for proper
  // perspective? (20040227 handegar)

  const SbVec2f slicecorners[4] = {
    SbVec2f(-2.0f,  2.0f),
    SbVec2f( 2.0f,  2.0f),
    SbVec2f( 2.0f, -2.0f),
    SbVec2f(-2.0f, -2.0f)
  };

  unsigned int nrofclippinginvocations = 0; // debug

  for (unsigned int i = 0; i < numslices; ++i) {

    if (this->abortfunc != NULL) { // Check user-callback status.
      SoVolumeRender::AbortCode abortcode =
        this->abortfunc(numslices, (numslices - i), this->abortfuncdata);
      if (abortcode == SoVolumeRender::ABORT) break;
      else if (abortcode == SoVolumeRender::SKIP) continue;
    }

    // FIXME: this doesn't stretch the slices all the way. 20040728 mortene.
    const float cam2slicedistance = neardistance + i*distancedelta;

    SbVec3f xformslicecorners[4];
    for (unsigned int j=0; j < 4; j++) {
      xformslicecorners[j] =
        viewvolume.getPlanePoint(cam2slicedistance, slicecorners[j]);
      mat.multVecMatrix(xformslicecorners[j], xformslicecorners[j]);
    }

    for (unsigned int cubeidx = 0; cubeidx < (unsigned int)subcubelist.getLength(); cubeidx++) {
      Cvr3DTexSubCubeItem * cubeitem = subcubelist[cubeidx];

      if (cam2slicedistance > (cubeitem->cameraplane2cubecenter + cubeitem->boundingsphereradius)) {
        continue; // We have passed the cube.
      }
      else if (cam2slicedistance < (cubeitem->cameraplane2cubecenter - cubeitem->boundingsphereradius)) {
        continue; // We haven't reached the cube yet.
      }

      cubeitem->cube->intersectSlice(xformslicecorners);
      nrofclippinginvocations++; // debug
    }
  }

#if 0 // debug
  if (CvrUtil::doDebugging()) {
    SoDebugError::postInfo("Cvr3DTexCube::render",
                           "Nr of SbClip invocations == %u",
                           nrofclippinginvocations);
  }
#endif // debug

  // Sort rendering order of the subcubes depending on the distance to
  // the camera.
  qsort((void *) subcubelist.getArrayPtr(), subcubelist.getLength(),
        sizeof(Cvr3DTexSubCubeItem *), subcube_qsort_compare);

  this->renderResult(action, subcubelist);
}

// Renders *one* slice of the volume according to the specified
// plane. Loads all the subcubes needed.
void
Cvr3DTexCube::renderObliqueSlice(const SoGLRenderAction * action,
                                 const SbPlane plane)
{

  const cc_glglue * glglue = cc_glglue_instance(action->getCacheContext());

  SoState * state = action->getState();

  SbVec3f subcubewidth = SbVec3f(this->subcubesize[0], 0, 0);
  SbVec3f subcubeheight = SbVec3f(0, this->subcubesize[1], 0);
  SbVec3f subcubedepth = SbVec3f(0, 0, this->subcubesize[2]);

  const float dist = plane.getDistanceFromOrigin();
  SbVec3f z = plane.getNormal();
  // Dummy vector based on the normal. Must not be equal to the normal
  // (or in the opposite direction). This will cause the normalization
  // of 'x' and 'z.cross(x)' to fail.
  SbVec3f y(z[1], -z[2], z[0]);
  SbVec3f x = y.cross(z);
  x.normalize();
  y = z.cross(x);
  y.normalize();

  SbMatrix m, t;
  m.makeIdentity();
  m[0][0] = x[0]; m[0][1] = x[1]; m[0][2] = x[2];
  m[1][0] = y[0]; m[1][1] = y[1]; m[1][2] = y[2];
  m[2][0] = z[0]; m[2][1] = z[1]; m[2][2] = z[2];

  t.setTranslate(plane.getNormal() * dist);
  m = m * t;

  SbViewVolume viewvolume;
  // FIXME: Is this the correct way to setup a viewvolume? The
  // important goal is that the object is completely inside the ortho
  // area. (20040628 handegar)
  const float viewvolumesize = (subcubewidth + subcubeheight + subcubedepth).length();
  viewvolume.ortho(-viewvolumesize, viewvolumesize, -viewvolumesize, viewvolumesize, 0.01f, 100.0f);
  viewvolume.transform(m);
  const SbMatrix mat = SoModelMatrixElement::get(state).inverse();

  SbList <Cvr3DTexSubCubeItem *> subcubelist;

  for (unsigned int rowidx = 0; rowidx < this->nrrows; rowidx++) {
    for (unsigned int colidx = 0; colidx < this->nrcolumns; colidx++) {
      for (unsigned int depthidx = 0; depthidx < this->nrdepths; depthidx++) {

        Cvr3DTexSubCube * cube = NULL;
        Cvr3DTexSubCubeItem * cubeitem = this->getSubCube(state, colidx, rowidx, depthidx);

        const SbVec3f subcubeorigo =
          this->origo +
          subcubewidth * (float)colidx +
          subcubeheight * (float)rowidx +
          subcubedepth * (float)depthidx;

        if (cubeitem == NULL) {
          cubeitem = this->buildSubCube(action, subcubeorigo, colidx, rowidx, depthidx);
        }
        assert(cubeitem != NULL);

        if (cubeitem->invisible) continue;
        assert(cubeitem->cube != NULL);

        cubeitem->cube->intersectSlice(viewvolume, 0, mat);
        subcubelist.append(cubeitem);

      }
    }
  }

  this->renderResult(action, subcubelist);
}

// Renders a indexed faceset inside the volume. Loads all the subcubes needed.
void
Cvr3DTexCube::renderIndexedSet(const SoGLRenderAction * action,
                               const SbVec3f * vertexarray,
                               const int * indices,
                               const unsigned int numindices,
                               const enum IndexedSetType type)
{
  assert(vertexarray);
  assert(indices);

  const cc_glglue * glglue = cc_glglue_instance(action->getCacheContext());

  SoState * state = action->getState();

  SbVec3f subcubewidth = SbVec3f(this->subcubesize[0], 0, 0);
  SbVec3f subcubeheight = SbVec3f(0, this->subcubesize[1], 0);
  SbVec3f subcubedepth = SbVec3f(0, 0, this->subcubesize[2]);

  SbList <Cvr3DTexSubCubeItem *> subcubelist;
  const SbMatrix invmodelmatrix = SoModelMatrixElement::get(state).inverse();

  for (unsigned int rowidx = 0; rowidx < this->nrrows; rowidx++) {
    for (unsigned int colidx = 0; colidx < this->nrcolumns; colidx++) {
      for (unsigned int depthidx = 0; depthidx < this->nrdepths; depthidx++) {

        Cvr3DTexSubCube * cube = NULL;
        Cvr3DTexSubCubeItem * cubeitem = this->getSubCube(state, colidx, rowidx, depthidx);

        const SbVec3f subcubeorigo =
          this->origo +
          subcubewidth * (float)colidx +
          subcubeheight * (float)rowidx +
          subcubedepth * (float)depthidx;

        if (cubeitem == NULL) {
          cubeitem = this->buildSubCube(action, subcubeorigo, colidx, rowidx, depthidx);
        }
        assert(cubeitem != NULL);

        if (cubeitem->invisible) continue;
        assert(cubeitem->cube != NULL);

        if (type == Cvr3DTexCube::INDEXEDFACE_SET) {
          cubeitem->cube->intersectIndexedFaceSet(vertexarray,
                                                  indices,
                                                  numindices,
                                                  invmodelmatrix);
        }
        else if (type == Cvr3DTexCube::INDEXEDTRIANGLESTRIP_SET) {
          cubeitem->cube->intersectIndexedTriangleStripSet(vertexarray,
                                                           indices,
                                                           numindices,
                                                           invmodelmatrix);
        }
        else assert(FALSE && "Unknown set type!");

        subcubelist.append(cubeitem);

      }
    }
  }

  this->renderResult(action, subcubelist);
}

// Renders a nonindexed faceset inside the volume. Loads all the subcubes needed.
void
Cvr3DTexCube::renderNonindexedSet(const SoGLRenderAction * action,
                                  const SbVec3f * vertexarray,
                                  const int * numVertices,
                                  const unsigned int listlength,
                                  const enum NonindexedSetType type)
{
  assert(vertexarray);
  assert(numVertices);

  const cc_glglue * glglue = cc_glglue_instance(action->getCacheContext());

  SoState * state = action->getState();

  SbVec3f subcubewidth = SbVec3f(this->subcubesize[0], 0, 0);
  SbVec3f subcubeheight = SbVec3f(0, this->subcubesize[1], 0);
  SbVec3f subcubedepth = SbVec3f(0, 0, this->subcubesize[2]);

  SbList <Cvr3DTexSubCubeItem *> subcubelist;
  const SbMatrix invmodelmatrix = SoModelMatrixElement::get(state).inverse();

  for (unsigned int rowidx = 0; rowidx < this->nrrows; rowidx++) {
    for (unsigned int colidx = 0; colidx < this->nrcolumns; colidx++) {
      for (unsigned int depthidx = 0; depthidx < this->nrdepths; depthidx++) {

        Cvr3DTexSubCube * cube = NULL;
        Cvr3DTexSubCubeItem * cubeitem = this->getSubCube(state, colidx, rowidx, depthidx);

        const SbVec3f subcubeorigo =
          this->origo +
          subcubewidth * (float)colidx +
          subcubeheight * (float)rowidx +
          subcubedepth * (float)depthidx;

        if (cubeitem == NULL) {
          cubeitem = this->buildSubCube(action, subcubeorigo, colidx, rowidx, depthidx);
        }
        assert(cubeitem != NULL);

        if (cubeitem->invisible) continue;
        assert(cubeitem->cube != NULL);

        if (type == Cvr3DTexCube::FACE_SET) {
          cubeitem->cube->intersectFaceSet(vertexarray,
                                           numVertices,
                                           listlength,
                                           invmodelmatrix);
        }
        else if (type == Cvr3DTexCube::TRIANGLESTRIP_SET) {
          cubeitem->cube->intersectTriangleStripSet(vertexarray,
                                                    numVertices,
                                                    listlength,
                                                    invmodelmatrix);
        }
        else assert(FALSE && "Unknown set type!");

        subcubelist.append(cubeitem);

      }
    }
  }

  this->renderResult(action, subcubelist);
}

unsigned int
Cvr3DTexCube::calcSubCubeIdx(unsigned int row, unsigned int col, unsigned int depth) const
{
  assert(row < this->nrrows);
  assert(col < this->nrcolumns);
  assert(depth < this->nrdepths);

  unsigned int idx =
    (col + (row * this->nrcolumns)) + (depth * this->nrcolumns * this->nrrows);

  assert(idx < (this->nrdepths * this->nrcolumns * this->nrrows));

  return idx;
}

// Builds a cube if it doesn't exist. Rebuilds it if it does exist.
Cvr3DTexSubCubeItem *
Cvr3DTexCube::buildSubCube(const SoGLRenderAction * action,
                           const SbVec3f & subcubeorigo,
                           unsigned int col, unsigned int row, unsigned int depth)
{
  // FIXME: optimalization idea; *crop* textures for 100%
  // transparency. 20021124 mortene.

  // FIXME: optimalization idea; detect 100% similar neighboring
  // cubes, and make cubes able to map to several "slice indices". Not
  // sure if this can be much of a gain -- but look into it. 20021124 mortene.

  assert((this->getSubCube(action->getState(), col, row, depth) == NULL) && "Subcube already created!");

  // First Cvr3DTexSubCube ever in this slice?
  if (this->subcubes == NULL) {
    if (CvrUtil::doDebugging()) {
      SoDebugError::postInfo("Cvr3DTexCube::buildSubCube",
                             "number of subcubes needed == %d (%d x %d x %d)",
                             this->nrrows * this->nrcolumns * this->nrdepths,
                             this->nrrows, this->nrcolumns, this->nrdepths);
    }

    this->subcubes = new Cvr3DTexSubCubeItem*[this->nrrows * this->nrcolumns * this->nrdepths];
    for (unsigned int i=0; i < this->nrrows; i++) {
      for (unsigned int j=0; j < this->nrcolumns; j++) {
        for (unsigned int k=0; k < this->nrdepths; k++) {
          const unsigned int idx = this->calcSubCubeIdx(i, j, k);
          this->subcubes[idx] = NULL;
        }
      }
    }
  }

  SbVec3s subcubemin, subcubemax;
  if (CvrUtil::useFlippedYAxis()) {
    // NOTE: Building subcubes 'upwards' so that the Y orientation
    // will be equal to the 2D slice rendering (the voxelchunks are
    // also flipped).
    subcubemin = SbVec3s(col * this->subcubesize[0],
                         this->dimensions[1] - (row + 1) * this->subcubesize[1],
                         depth * this->subcubesize[2]);
    subcubemax = SbVec3s((col + 1) * this->subcubesize[0],
                         this->dimensions[1] - row * this->subcubesize[1],
                         (depth + 1) * this->subcubesize[2]);
  }
  else {
    subcubemin = SbVec3s(col * this->subcubesize[0],
                         row * this->subcubesize[1],
                         depth * this->subcubesize[2]);
    subcubemax = SbVec3s((col + 1) * this->subcubesize[0],
                         (row + 1) * this->subcubesize[1],
                         (depth + 1) * this->subcubesize[2]);
  }

  // Crop subcube size
  subcubemax[0] = SbMin(subcubemax[0], this->dimensions[0]);
  subcubemax[1] = SbMin(subcubemax[1], this->dimensions[1]);
  subcubemax[2] = SbMin(subcubemax[2], this->dimensions[2]);

  subcubemin[1] = SbMax(subcubemin[1], (short) 0);

#if CVR_DEBUG && 0 // debug
  SoDebugError::postInfo("Cvr3DTexCube::buildSubCube",
                         "subcubemin=[%d, %d, %d] subcubemax=[%d, %d, %d]",
                         subcubemin[0], subcubemin[1], subcubemin[2],
                         subcubemax[0], subcubemax[1], subcubemax[2]);
#endif // debug
  const SbBox3s subcubecut(subcubemin, subcubemax);
  const CvrTextureObject * texobj = CvrTextureObject::create(action, this->clut, subcubecut);
  // if NULL is returned, it means all voxels are fully transparent

  Cvr3DTexSubCube * cube = NULL;
  if (texobj) {
    cube = new Cvr3DTexSubCube(action, texobj, subcubeorigo,
                               subcubecut.getMax() - subcubecut.getMin());
    cube->setPalette(this->clut);
  }

  SoState * state = action->getState();
  const CvrVoxelBlockElement * vbelem = CvrVoxelBlockElement::getInstance(state);
  assert(vbelem != NULL);

  Cvr3DTexSubCubeItem * pitem = new Cvr3DTexSubCubeItem(cube);
  pitem->volumedataid = vbelem->getNodeId();
  pitem->invisible = (texobj == NULL) ? TRUE : FALSE;

  const int idx = this->calcSubCubeIdx(row, col, depth);
  this->subcubes[idx] = pitem;

  return pitem;
}

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

void
Cvr3DTexCube::setPalette(const CvrCLUT * c)
{
  if (this->clut) { this->clut->unref(); }
  this->clut = c;
  this->clut->ref();

  if (this->subcubes == NULL) return;

  // Change palette for all subcubes.
  for (unsigned int col=0; col < this->nrcolumns; col++) {
    for (unsigned int row=0; row < this->nrrows; row++) {
      for (unsigned int depth = 0; depth < this->nrdepths; depth++) {
        const unsigned int idx = this->calcSubCubeIdx(row, col, depth);
        Cvr3DTexSubCubeItem * subc = this->subcubes[idx];

        // No cube was yet made in this position.
        if (subc == NULL) { continue; }

        // Only if invisible should there be no page allocated.
        assert(subc->invisible || subc->cube);

        // If this hits, the cube was RGBA and/or previously
        // invisible.  That may change when setting a new palette, so
        // remove the old cube.
        if (subc->invisible || !subc->cube->isPaletted()) {
          this->releaseSubCube(row, col, depth);
          continue;
        }

        // If paletted and previously visible, we simply migrate the new
        // palette to all sub-pages.
        subc->cube->setPalette(this->clut);
      }
    }
  }
}

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

const CvrCLUT *
Cvr3DTexCube::getPalette(void) const
{
  return this->clut;
}

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

Cvr3DTexSubCubeItem *
Cvr3DTexCube::getSubCube(SoState * state, unsigned int col, unsigned int row, unsigned int depth)
{
  if (this->subcubes == NULL) return NULL;

  assert(col < this->nrcolumns);
  assert(row < this->nrrows);
  assert(depth < this->nrdepths);

  const unsigned int idx = this->calcSubCubeIdx(row, col, depth);
  Cvr3DTexSubCubeItem * subp = this->subcubes[idx];

  if (subp) {
    const CvrVoxelBlockElement * vbelem = CvrVoxelBlockElement::getInstance(state);
    assert(vbelem != NULL);
    uint32_t volumedataid = vbelem->getNodeId();

    if (subp->volumedataid != volumedataid) {
      // FIXME: it could perhaps be a decent optimalization to store a
      // checksum value along with the subcube, to use for comparison
      // to see if this subcube really changed. 20030220 mortene.
      this->releaseSubCube(row, col, depth);
      return NULL;
    }
  }

  return subp;
}


text:
module MailerMacros
  def email_deliveries
    ActionMailer::Base.deliveries
  end

  def last_email
    email_deliveries.last
  end

  def reset_email
    ActionMailer::Base.deliveries = []
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace common\models;

use creocoder\nestedsets\NestedSetsQueryBehavior;

/**
 * This is the ActiveQuery class for [[CatalogueCategory]].
 *
 * @see CatalogueCategory
 */
class CatalogueCategoryQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/
    public function behaviors() {
        return [
            NestedSetsQueryBehavior::className(),
        ];
    }
    /**
     * @inheritdoc
     * @return CatalogueCategory[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return CatalogueCategory|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
package com.hp.hpl.jena.assembler.exceptions;

import com.hp.hpl.jena.rdf.model.*;

public class NotUniqueException extends AssemblerException
    {
    protected final Property property;

    public NotUniqueException( Resource root, Property property )
        {
        super( root, makeMessage( root, property ) );
        this.property = property;
        }

    private static String makeMessage( Resource root, Property property )
        {
        return
            "the object " + nice( root )
            + " has multiple values for the unique property " + nice( property )
            ;
        }

    public Property getProperty()
        { return property; }
    }

/*
 * (c) Copyright 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


text:
class Namespace;

//-----------------------------------------------------------------------------
// FileSystem
//
// FileSystem declares all of the related interfaces that must be implemented
// by a file system implementation as well as a number of static helper methods
// that can be used to more easily access file system functionality
//
// todo: Mount implementation needs bitmask<> treatment

class __declspec(novtable) FileSystem
{
public:

	// Forward Interface Declarations
	//
	struct __declspec(novtable) Alias;
	struct __declspec(novtable) BlockDevice;
	struct __declspec(novtable) CharacterDevice;
	struct __declspec(novtable) Directory;
	struct __declspec(novtable) File;
	struct __declspec(novtable) Handle;
	struct __declspec(novtable) Mount;
	struct __declspec(novtable) Node;
	struct __declspec(novtable) Pipe;
	struct __declspec(novtable) Socket;
	struct __declspec(novtable) SymbolicLink;

	// Forward Class Declarations
	//
	class Path;
	class PathHandle;

	// FileSystem::MountFunction
	//
	// Function signature for a file system's Mount() implementation, which must be a public static method
	using MountFunction = std::function<std::shared_ptr<Mount>(const char_t* source, uint32_t flags, const void* data, size_t datalength)>;

	// FileSystem::MaxSymbolicLinks
	//
	// Constant indicating the maximum recursion depth of a path lookup
	static const int MaxSymbolicLinks = 40;

	// FileSystem::NodeType
	//
	// Strogly typed enumeration for the S_IFxxx inode type constants
	enum class NodeType
	{
		BlockDevice			= LINUX_S_IFBLK,
		CharacterDevice		= LINUX_S_IFCHR,
		Directory			= LINUX_S_IFDIR,
		File				= LINUX_S_IFREG,
		Pipe				= LINUX_S_IFIFO,
		Socket				= LINUX_S_IFSOCK,
		SymbolicLink		= LINUX_S_IFLNK,
	};

	// FileSystem::HandleAccess
	//
	// Access modes used with handle operations
	class HandleAccess final : public bitmask<HandleAccess, uint32_t, LINUX_O_RDONLY | LINUX_O_WRONLY | LINUX_O_RDWR>
	{
	public:

		using bitmask::bitmask;

		//-------------------------------------------------------------------------
		// Fields

		// ReadOnly (static)
		//
		// Indicates that the handle should be opened in read-only mode
		static const HandleAccess ReadOnly;

		// WriteOnly (static)
		//
		// Indicates that handle should be opened in write-only mode
		static const HandleAccess WriteOnly;

		// ReadWrite (static)
		//
		// Indicates that the handle should be opened in read/write mode
		static const HandleAccess ReadWrite;
	};

	// FileSystem::HandleFlags
	//
	// Flags used with handle operations
	class HandleFlags final : public bitmask<HandleFlags, uint32_t, LINUX_O_APPEND | LINUX_O_DIRECT | LINUX_O_DSYNC | LINUX_O_NOATIME | LINUX_O_SYNC | LINUX_O_TRUNC>
	{
	public:

		using bitmask::bitmask;

		//-------------------------------------------------------------------------
		// Fields

		// Append (static)
		//
		// Indicates that the handle should be opened in append mode
		static const HandleFlags Append;

		// DataSync (static)
		//
		// Indicates that write operations should enforce data integrity
		static const HandleFlags DataSync;

		// Direct (static)
		//
		// Indicates that the handle should not buffer input/output
		static const HandleFlags Direct;

		// NoAccessTime (static)
		//
		// Indicates that the handle should not update atime after a read operation
		static const HandleFlags NoAccessTime;

		// None (static)
		//
		// Indicates that no special handle flags are present
		static const HandleFlags None;

		// Sync (static)
		//
		// Indicates that write operations should enforce both file and data integrity
		static const HandleFlags Sync;

		// Truncate (static)
		//
		// Indicates that the underlying file should be truncated on open
		static const HandleFlags Truncate;
	};

	// FileSystem::LookupFlags
	//
	// Flags used with lookup operations
	class LookupFlags final : public bitmask<LookupFlags, uint32_t, LINUX_O_DIRECTORY | LINUX_O_NOFOLLOW>
	{
	public:

		using bitmask::bitmask;

		//-------------------------------------------------------------------------
		// Fields

		// Directory (static)
		//
		// Indicates that the target of a lookup must be a directory
		static const LookupFlags Directory;

		// NoFollow (static)
		//
		// Indicates that a symbolic link final path component should not be followed
		static const LookupFlags NoFollow;

		// None (static)
		//
		// Indicates that no special lookup flags are present
		static const LookupFlags None;
	};

	//
	// FILE SYSTEM INTERFACES
	//

	// FileSystem::Alias
	//
	// Interface that must be implemented by a file system alias.  An alias is
	// a name that is used to reference a file system node (basically a hard link)
	struct __declspec(novtable) Alias
	{
		// GetName
		//
		// Reads the name assigned to this alias
		virtual uapi::size_t GetName(char_t* buffer, size_t count) const = 0;

		// Name
		//
		// Gets the name assigned to this alias
		__declspec(property(get=getName)) std::string Name;
		virtual std::string getName(void) const = 0;

		// Node
		//
		// Gets the node to which this alias refers
		__declspec(property(get=getNode)) std::shared_ptr<FileSystem::Node> Node;
		virtual std::shared_ptr<FileSystem::Node> getNode(void) const = 0;
	};

	// FileSystem::Handle
	//
	// Handle is the interface that must be implemented for a file system handle object.
	// A handle is a view of a file system node
	struct __declspec(novtable) Handle
	{
		// Duplicate
		//
		// Creates a duplicate Handle instance
		virtual std::shared_ptr<Handle> Duplicate(void) const = 0;

		// Read
		//
		// Synchronously reads data from the underlying node into a buffer
		virtual uapi::size_t Read(void* buffer, uapi::size_t count) = 0;

		// ReadAt
		//
		// Synchronously reads data from the underlying node into a buffer
		virtual uapi::size_t ReadAt(uapi::loff_t offset, void* buffer, uapi::size_t count) = 0;

		// Seek
		//
		// Changes the file position
		virtual uapi::loff_t Seek(uapi::loff_t offset, int whence) = 0;

		// Sync
		//
		// Synchronizes all metadata and data associated with the file to storage
		virtual void Sync(void) const = 0;

		// SyncData
		//
		// Synchronizes all data associated with the file to storage, not metadata
		virtual void SyncData(void) const = 0;

		// Write
		//
		// Synchronously writes data from a buffer to the underlying node
		virtual uapi::size_t Write(const void* buffer, uapi::size_t count) = 0;

		// WriteAt
		//
		// Synchronously writes data from a buffer to the underlying node
		virtual uapi::size_t WriteAt(uapi::loff_t offset, const void* buffer, uapi::size_t count) = 0;

		// Access
		//
		// Gets the access mode used when the handle was created
		__declspec(property(get=getAccess)) FileSystem::HandleAccess Access;
		virtual FileSystem::HandleAccess getAccess(void) const = 0;

		// Flags
		//
		// Gets the flags used when the handle was created
		__declspec(property(get=getFlags)) FileSystem::HandleFlags Flags;
		virtual FileSystem::HandleFlags getFlags(void) const = 0;
	};

	// FileSystem::Mount
	//
	// Interface that must be implemented by a file system mount.  A mount is a view
	// of a file system, normally associated with a specific namespace.
	struct __declspec(novtable) Mount
	{
		// Duplicate
		//
		// Duplicates this mount instance
		virtual std::shared_ptr<FileSystem::Mount> Duplicate(void) const = 0;

		// Remount
		//
		// Remounts this mount point with different flags and arguments
		virtual void Remount(uint32_t flags, const void* data, size_t datalen) = 0;

		// Stat
		//
		// Provides statistical information about the file system
		virtual void Stat(uapi::statfs* stats) const = 0;

		// Unmount
		//
		// Unmounts the file system
		virtual void Unmount(void) = 0;

		// Flags
		//
		// Gets the flags set on this mount, includes file system flags
		__declspec(property(get=getFlags)) uint32_t Flags;
		virtual uint32_t getFlags(void) const = 0;

		// Root
		//
		// Gets a reference to the root directory of the mount point
		__declspec(property(get=getRoot)) std::shared_ptr<FileSystem::Directory> Root;
		virtual std::shared_ptr<FileSystem::Directory> getRoot(void) const = 0;

		// Source
		//
		// Gets the device/name used as the source of the file system
		__declspec(property(get=getSource)) std::string Source;
		virtual std::string getSource(void) const = 0;
	};

	// FileSystem::Node
	//
	// Interface that must be implemented for a file system node object.  A node represents
	// any object (file, directory, socket, etc) that is a member of a file system
	struct __declspec(novtable) Node
	{
		// Open
		//
		// Creates a Handle instance against this node
		virtual std::shared_ptr<FileSystem::Handle> Open(std::shared_ptr<FileSystem::Mount> mount, FileSystem::HandleAccess access, FileSystem::HandleFlags flags) = 0;

		// SetOwnership
		//
		// Changes the ownership of this node
		virtual void SetOwnership(uapi::uid_t uid, uapi::gid_t gid) = 0;

		// SetPermissions
		//
		// Changes the permission flags for this node
		virtual void SetPermissions(uapi::mode_t mode) = 0;

		// Stat
		//
		// Provides statistical information about the node
		virtual void Stat(uapi::stat* stats) const = 0;

		// Type
		//
		// Gets the type of file system node being implemented
		__declspec(property(get=getType)) FileSystem::NodeType Type;
		virtual FileSystem::NodeType getType(void) const = 0;
	};

	// FileSystem::BlockDevice
	//
	// Specialization of Node for file system block device objects
	struct __declspec(novtable) BlockDevice : public Node
	{
	};

	// FileSystem::CharacterDevice
	//
	// Specialization of Node for file system character device objects
	struct __declspec(novtable) CharacterDevice : public Node
	{
	};

	// FileSystem::Directory
	//
	// Specialization of Node for file system directory objects
	struct __declspec(novtable) Directory : public Node
	{
		//// CreateCharacterDevice
		////
		//// Creates a new character device node as a child of this directory
		//virtual std::shared_ptr<FileSystem::Path> CreateCharacterDevice(std::shared_ptr<FileSystem::Mount> mount, const char_t* name, uapi::mode_t mode, uapi::dev_t device) = 0;

		// CreateDirectory
		//
		// Creates a new directory node as a child of this directory
		virtual std::shared_ptr<FileSystem::Alias> CreateDirectory(std::shared_ptr<FileSystem::Mount> mount, const char_t* name, uapi::mode_t mode) = 0;

		// CreateFile
		//
		// Creates a new regular file node as a child of this directory
		virtual std::shared_ptr<FileSystem::Alias> CreateFile(std::shared_ptr<FileSystem::Mount> mount, const char_t* name, uapi::mode_t mode) = 0;

		//// CreateSymbolicLink
		////
		//// Creates a new symbolic link as a child of this directory
		//virtual std::shared_ptr<FileSystem::Path> CreateSymbolicLink(std::shared_ptr<FileSystem::Mount> mount, const char_t* name, const char_t* target) = 0;

		// Lookup
		//
		// Looks up the alias associated with a child of this directory
		virtual std::shared_ptr<FileSystem::Alias> Lookup(std::shared_ptr<FileSystem::Mount> mount, const char_t* name) const = 0;
	};

	// FileSystem::File
	//
	// Specialization of Node for file system regular file objects
	struct __declspec(novtable) File : public Node
	{
		// OpenExec
		//
		// Creates an execute-only handle against this node; used only by the virtual machine
		virtual std::shared_ptr<FileSystem::Handle> OpenExec(std::shared_ptr<FileSystem::Mount> mount) const = 0;
	};

	// FileSystem::Pipe
	//
	// Specialization of Node for file system pipe objects
	struct __declspec(novtable) Pipe : public Node
	{
	};

	// FileSystem::Socket
	//
	// Specialization of Node for file system socket objects
	struct __declspec(novtable) Socket : public Node
	{
	};

	// FileSystem::SymbolicLink
	//
	// Specialization of Node for file system symbolic link objects
	struct __declspec(novtable) SymbolicLink : public Node
	{
		// GetTarget
		//
		// Reads the target of the symbolic link
		virtual uapi::size_t GetTarget(char_t* buffer, size_t count) const = 0;

		// Target
		//
		// Gets the symbolic link target string
		__declspec(property(get=getTarget)) std::string Target;
		virtual std::string getTarget(void) const = 0;
	};

	//
	// FILE SYSTEM CLASSES
	//

	// FileSystem::Path
	//
	// Path represents a fully resolved file system object
	class Path final
	{
	friend class FileSystem;
	public:

		// Copy Constructor
		//
		//Path(const Path& rhs);

		// Move Constructor
		//
		//Path(Path&& rhs);

		// Destructor
		//
		~Path()=default;

		//---------------------------------------------------------------------
		// Member Functions

		// Create (static)
		//
		// Creates a new Path instance from component parts
		static std::shared_ptr<Path> Create(std::shared_ptr<FileSystem::Alias> alias, std::shared_ptr<FileSystem::Mount> mount);

	private:

		Path(const Path&)=delete;
		Path& operator=(const Path&)=delete;
		//Path& operator=(Path&&)=delete;

		// Instance Constructors
		//
		Path(std::shared_ptr<FileSystem::Alias> alias, std::shared_ptr<FileSystem::Mount> mount);
		Path(std::shared_ptr<FileSystem::Path> parent, std::shared_ptr<FileSystem::Alias> alias, std::shared_ptr<FileSystem::Mount> mount);
		friend class std::_Ref_count_obj<Path>;

		//---------------------------------------------------------------------
		// Member Variables

		const std::shared_ptr<FileSystem::Path>		m_parent;	// Parent instance
		const std::shared_ptr<FileSystem::Alias>	m_alias;	// Alias reference
		const std::shared_ptr<FileSystem::Mount>	m_mount;	// Mount reference
	};

	// FileSystem::PathHandle
	//
	// Implementation of an O_PATH-based handle used by the File System API.  Individual
	// file systems do not need to implement any special handling when this flag has been
	// specified by a client call, no call to Node::Open() will take place, an instance
	// of this class will be used automatically
	class PathHandle final : public FileSystem::Handle
	{
	public:

		// Instance Constructor
		//
		PathHandle(std::shared_ptr<FileSystem::Node> node, FileSystem::HandleAccess access);

		// Destructor
		//
		~PathHandle()=default;

		//---------------------------------------------------------------------
		// FileSystem::Handle Implementation

		// Duplicate
		//
		// Creates a duplicate Handle instance
		virtual std::shared_ptr<FileSystem::Handle> Duplicate(void) const override;

		// Read
		//
		// Synchronously reads data from the underlying node into a buffer
		virtual uapi::size_t Read(void* buffer, uapi::size_t count) override;

		// ReadAt
		//
		// Synchronously reads data from the underlying node into a buffer
		virtual uapi::size_t ReadAt(uapi::loff_t offset, void* buffer, uapi::size_t count) override;

		// Seek
		//
		// Changes the file position
		virtual uapi::loff_t Seek(uapi::loff_t offset, int whence) override;

		// Sync
		//
		// Synchronizes all metadata and data associated with the file to storage
		virtual void Sync(void) const override;

		// SyncData
		//
		// Synchronizes all data associated with the file to storage, not metadata
		virtual void SyncData(void) const override;

		// Write
		//
		// Synchronously writes data from a buffer to the underlying node
		virtual uapi::size_t Write(const void* buffer, uapi::size_t count) override;

		// WriteAt
		//
		// Synchronously writes data from a buffer to the underlying node
		virtual uapi::size_t WriteAt(uapi::loff_t offset, const void* buffer, uapi::size_t count) override;

		// getAccess
		//
		// Gets the handle access mode
		virtual FileSystem::HandleAccess getAccess(void) const override;

		// getFlags
		//
		// Gets the handle flags
		virtual FileSystem::HandleFlags getFlags(void) const override;

	private:

		PathHandle(const PathHandle&)=delete;
		PathHandle& operator=(const PathHandle&)=delete;

		//---------------------------------------------------------------------
		// Member Variables

		const std::shared_ptr<FileSystem::Node>	m_node;		// Referenced node
		const FileSystem::HandleAccess			m_access;	// Handle access mode
	};

	//
	// FILE SYSTEM API
	//

	// NOTE: These should use the weakly typed flags (LINUX_O_XXXX) to make it easier for the RPC layer to just
	// pass them in from the client application

	//static void CheckPermissions(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& base, const char_t* path,
	//	int flags, uapi::mode_t mode);

	//static void CreateCharacterDevice(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& base,
	//	const char_t* path, uapi::mode_t mode, uapi::dev_t device);

	//static void CreateDirectory(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& base, const char_t* path, uapi::mode_t mode);

	// CreateFile
	//
	// Creates a new regular file
	//static std::shared_ptr<Handle> CreateFile(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& base, const char_t* path,
	//	int flags, uapi::mode_t mode);

	//static void CreateSymbolicLink(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& base, const char_t* path, const char_t* target);

	// GenerateFileSystemId
	//
	// Generates a unique file system identifier (fsid)
	static uapi::fsid_t GenerateFileSystemId(void);

	// GetAbsolutePath
	//
	// Determines the absolute file system path of an existing object
	///static void GetAbsolutePath(const std::shared_ptr<Alias>& root, const std::shared_ptr<Alias>& alias, char_t* path, size_t pathlen);

	// LookupPath
	//
	// Resolves a file system object as a FileSystem::Path instance
	static std::shared_ptr<FileSystem::Path> LookupPath(std::shared_ptr<Namespace> ns, std::shared_ptr<FileSystem::Path> root,
		std::shared_ptr<FileSystem::Path> current, const char_t* path, int flags);

	// OpenExecutable
	//
	// Opens an existing file system object as an executable
	static std::shared_ptr<FileSystem::Handle> OpenExecutable(std::shared_ptr<Namespace> ns, std::shared_ptr<Path> root,
		std::shared_ptr<Path> current, const char_t* path);

	// OpenFile
	//
	// Opens or creates a file
	static std::shared_ptr<FileSystem::Handle> OpenFile(std::shared_ptr<Namespace> ns, std::shared_ptr<FileSystem::Path> root,
		std::shared_ptr<FileSystem::Path> current, const char_t* path, int flags, uapi::mode_t mode);

	// ReadSymbolicLink
	//
	// Reads the target path associated with a symbolic link
	static size_t ReadSymbolicLink(std::shared_ptr<Namespace> ns, std::shared_ptr<FileSystem::Path> root,
		std::shared_ptr<FileSystem::Path> current, const char_t* path, char_t* buffer, size_t length);

private:

	FileSystem()=delete;
	FileSystem(const FileSystem&)=delete;
	FileSystem& operator=(const FileSystem&)=delete;

	//-------------------------------------------------------------------------
	// Private Member Functions

	// LookupPath
	//
	// Resolves a file system object as a FileSystem::Path instance
	static std::shared_ptr<FileSystem::Path> LookupPath(std::shared_ptr<Namespace> ns, std::shared_ptr<FileSystem::Path> root,
		std::shared_ptr<FileSystem::Path> current, const char_t* path, FileSystem::LookupFlags flags, int depth);
};

//-----------------------------------------------------------------------------

#pragma warning(pop)

#endif	// __FILESYSTEM_H_


text:
namespace distant::utility {

	template <class Derived>
	class static_polymorphic
	{
	public:
		const Derived& derived() const
		{
			// Downcast (const) to the derived type.
			return *static_cast<const Derived*>(this);
		}

		Derived& derived()
		{
			// Downcast to the derived type.
			return *static_cast<Derived*>(this);
		}

	protected:
		// Protected keyword allows the dervied destructor to call this one
		// Disables destruction of derived type via the base
		~static_polymorphic() = default;
	};

} // end namespace distant::utility


text:
// Contains get_min_count, the core optimization of the spreadsort algorithm.
// Also has other helper functions commonly useful across variants.

//          Copyright Steven J. Ross 2001 - 2014.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// See http://www.boost.org/libs/sort for library home page.

/*
Some improvements suggested by:
Phil Endecott and Frank Gennari
*/

#ifndef BOOST_SORT_SPREADSORT_DETAIL_SPREAD_SORT_COMMON_HPP
#define BOOST_SORT_SPREADSORT_DETAIL_SPREAD_SORT_COMMON_HPP
#include <algorithm>
#include <vector>
#include <cstring>
#include <limits>
#include <functional>
#include <boost/static_assert.hpp>
#include <boost/serialization/static_warning.hpp>
#include <boost/sort/spreadsort/detail/constants.hpp>
#include <boost/cstdint.hpp>

namespace boost {
namespace sort {
namespace spreadsort {
 namespace detail {
    //This only works on unsigned data types
    template <typename T>
    inline unsigned
    rough_log_2_size(const T& input)
    {
      unsigned result = 0;
      //The && is necessary on some compilers to avoid infinite loops
      //it doesn't significantly impair performance
      while ((result < (8*sizeof(T))) && (input >> result)) ++result;
      return result;
    }

    //Gets the minimum size to call spreadsort on to control worst-case runtime.
    //This is called for a set of bins, instead of bin-by-bin, to minimize
    //runtime overhead.
    //This could be replaced by a lookup table of sizeof(Div_type)*8 but this
    //function is more general.
    template<unsigned log_mean_bin_size,
      unsigned log_min_split_count, unsigned log_finishing_count>
    inline size_t
    get_min_count(unsigned log_range)
    {
      const size_t typed_one = 1;
      const unsigned min_size = log_mean_bin_size + log_min_split_count;
      //Assuring that constants have valid settings
      BOOST_STATIC_ASSERT(log_min_split_count <= max_splits &&
                          log_min_split_count > 0);
      BOOST_STATIC_ASSERT(max_splits > 1 &&
                          max_splits < (8 * sizeof(unsigned)));
      BOOST_STATIC_ASSERT(max_finishing_splits >= max_splits &&
                          max_finishing_splits < (8 * sizeof(unsigned)));
      BOOST_STATIC_ASSERT(log_mean_bin_size >= 0);
      BOOST_STATIC_ASSERT(log_finishing_count >= 0);
      //if we can complete in one iteration, do so
      //This first check allows the compiler to optimize never-executed code out
      if (log_finishing_count < min_size) {
        if (log_range <= min_size && log_range <= max_splits) {
          //Return no smaller than a certain minimum limit
          if (log_range <= log_finishing_count)
            return typed_one << log_finishing_count;
          return typed_one << log_range;
        }
      }
      const unsigned base_iterations = max_splits - log_min_split_count;
      //sum of n to n + x = ((x + 1) * (n + (n + x)))/2 + log_mean_bin_size
      const unsigned base_range =
          ((base_iterations + 1) * (max_splits + log_min_split_count))/2
          + log_mean_bin_size;
      //Calculating the required number of iterations, and returning
      //1 << (iteration_count + min_size)
      if (log_range < base_range) {
        unsigned result = log_min_split_count;
        for (unsigned offset = min_size; offset < log_range;
          offset += ++result);
        //Preventing overflow; this situation shouldn't occur
        if ((result + log_mean_bin_size) >= (8 * sizeof(size_t)))
          return typed_one << ((8 * sizeof(size_t)) - 1);
        return typed_one << (result + log_mean_bin_size);
      }
      //A quick division can calculate the worst-case runtime for larger ranges
      unsigned remainder = log_range - base_range;
      //the max_splits - 1 is used to calculate the ceiling of the division
      unsigned bit_length = ((((max_splits - 1) + remainder)/max_splits)
        + base_iterations + min_size);
      //Preventing overflow; this situation shouldn't occur
      if (bit_length >= (8 * sizeof(size_t)))
        return typed_one << ((8 * sizeof(size_t)) - 1);
      //n(log_range)/max_splits + C, optimizing worst-case performance
      return typed_one << bit_length;
    }

    // Resizes the bin cache and bin sizes, and initializes each bin size to 0.
    // This generates the memory overhead to use in radix sorting.
    template <class RandomAccessIter>
    inline RandomAccessIter *
    size_bins(size_t *bin_sizes, std::vector<RandomAccessIter>
  &bin_cache, unsigned cache_offset, unsigned &cache_end, unsigned bin_count)
    {
      // Clear the bin sizes
      for (size_t u = 0; u < bin_count; u++)
        bin_sizes[u] = 0;
      //Make sure there is space for the bins
      cache_end = cache_offset + bin_count;
      if (cache_end > bin_cache.size())
        bin_cache.resize(cache_end);
      return &(bin_cache[cache_offset]);
    }
  }
}
}
}

#endif


text:
package org.camunda.bpm.engine.test.api.repository;

import java.util.Date;
import java.util.List;

import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.impl.calendar.DateTimeUtil;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentQuery;
import org.camunda.bpm.engine.repository.ProcessApplicationDeployment;

/**
 * @author Tom Baeyens
 * @author Ingo Richtsmeier
 */
public class DeploymentQueryTest extends PluggableProcessEngineTestCase {

  private String deploymentOneId;
  private String deploymentTwoId;

  @Override
  protected void setUp() throws Exception {
    deploymentOneId = repositoryService
      .createDeployment()
      .name("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
      .addClasspathResource("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
      .source(ProcessApplicationDeployment.PROCESS_APPLICATION_DEPLOYMENT_SOURCE)
      .deploy()
      .getId();

    deploymentTwoId = repositoryService
      .createDeployment()
      .name("org/camunda/bpm/engine/test/repository/two_.bpmn20.xml")
      .addClasspathResource("org/camunda/bpm/engine/test/repository/two.bpmn20.xml")
      .deploy()
      .getId();

    super.setUp();
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
    repositoryService.deleteDeployment(deploymentOneId, true);
    repositoryService.deleteDeployment(deploymentTwoId, true);
  }

  public void testQueryNoCriteria() {
    DeploymentQuery query = repositoryService.createDeploymentQuery();
    assertEquals(2, query.list().size());
    assertEquals(2, query.count());

    try {
      query.singleResult();
      fail();
    } catch (ProcessEngineException e) {}
  }

  public void testQueryByDeploymentId() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId(deploymentOneId);
    assertNotNull(query.singleResult());
    assertEquals(1, query.list().size());
    assertEquals(1, query.count());
  }

  public void testQueryByInvalidDeploymentId() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId("invalid");
    assertNull(query.singleResult());
    assertEquals(0, query.list().size());
    assertEquals(0, query.count());

    try {
      repositoryService.createDeploymentQuery().deploymentId(null);
      fail();
    } catch (ProcessEngineException e) {}
  }

  public void testQueryByName() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("org/camunda/bpm/engine/test/repository/two_.bpmn20.xml");
    assertNotNull(query.singleResult());
    assertEquals(1, query.list().size());
    assertEquals(1, query.count());
  }

  public void testQueryByInvalidName() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("invalid");
    assertNull(query.singleResult());
    assertEquals(0, query.list().size());
    assertEquals(0, query.count());

    try {
      repositoryService.createDeploymentQuery().deploymentName(null);
      fail();
    } catch (ProcessEngineException e) {}
  }

  public void testQueryByNameLike() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("%camunda%");
    assertEquals(2, query.list().size());
    assertEquals(2, query.count());

    query = repositoryService.createDeploymentQuery().deploymentNameLike("%two\\_%");
    assertEquals(1, query.list().size());
    assertEquals(1, query.count());
    assertEquals("org/camunda/bpm/engine/test/repository/two_.bpmn20.xml", query.singleResult().getName());
  }

  public void testQueryByInvalidNameLike() {
    DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("invalid");
    assertNull(query.singleResult());
    assertEquals(0, query.list().size());
    assertEquals(0, query.count());

    try {
      repositoryService.createDeploymentQuery().deploymentNameLike(null);
      fail();
    } catch (ProcessEngineException e) {}
  }

  public void testQueryByDeploymentBefore() throws Exception {
    Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
    Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();

    long count = repositoryService.createDeploymentQuery().deploymentBefore(later).count();
    assertEquals(2, count);

    count = repositoryService.createDeploymentQuery().deploymentBefore(earlier).count();
    assertEquals(0, count);

    try {
      repositoryService.createDeploymentQuery().deploymentBefore(null);
      fail("Exception expected");
    } catch (NullValueException e) {
      // expected
    }
  }

  public void testQueryDeploymentAfter() throws Exception {
    Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
    Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();

    long count = repositoryService.createDeploymentQuery().deploymentAfter(later).count();
    assertEquals(0, count);

    count = repositoryService.createDeploymentQuery().deploymentAfter(earlier).count();
    assertEquals(2, count);

    try {
      repositoryService.createDeploymentQuery().deploymentAfter(null);
      fail("Exception expected");
    } catch (NullValueException e) {
      // expected
    }
  }

  public void testQueryBySource() {
    DeploymentQuery query = repositoryService
        .createDeploymentQuery()
        .deploymentSource(ProcessApplicationDeployment.PROCESS_APPLICATION_DEPLOYMENT_SOURCE);

    assertEquals(1, query.list().size());
    assertEquals(1, query.count());
  }

  public void testQueryByNullSource() {
    DeploymentQuery query = repositoryService
        .createDeploymentQuery()
        .deploymentSource(null);

    assertEquals(1, query.list().size());
    assertEquals(1, query.count());
  }

  public void testQueryByInvalidSource() {
    DeploymentQuery query = repositoryService
        .createDeploymentQuery()
        .deploymentSource("invalid");

    assertEquals(0, query.list().size());
    assertEquals(0, query.count());
  }

  public void testQueryDeploymentBetween() throws Exception {
    Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
    Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();

    long count = repositoryService
        .createDeploymentQuery()
        .deploymentAfter(earlier)
        .deploymentBefore(later).count();
    assertEquals(2, count);

    count = repositoryService
      .createDeploymentQuery()
      .deploymentAfter(later)
      .deploymentBefore(later)
      .count();
    assertEquals(0, count);

    count = repositoryService
      .createDeploymentQuery()
      .deploymentAfter(earlier)
      .deploymentBefore(earlier)
      .count();
    assertEquals(0, count);

    count = repositoryService
        .createDeploymentQuery()
        .deploymentAfter(later)
        .deploymentBefore(earlier)
        .count();
    assertEquals(0, count);
  }

  public void testVerifyDeploymentProperties() {
    List<Deployment> deployments = repositoryService.createDeploymentQuery()
      .orderByDeploymentName()
      .asc()
      .list();

    Deployment deploymentOne = deployments.get(0);
    assertEquals("org/camunda/bpm/engine/test/repository/one.bpmn20.xml", deploymentOne.getName());
    assertEquals(deploymentOneId, deploymentOne.getId());
    assertEquals(ProcessApplicationDeployment.PROCESS_APPLICATION_DEPLOYMENT_SOURCE, deploymentOne.getSource());
    assertNull(deploymentOne.getTenantId());

    Deployment deploymentTwo = deployments.get(1);
    assertEquals("org/camunda/bpm/engine/test/repository/two_.bpmn20.xml", deploymentTwo.getName());
    assertEquals(deploymentTwoId, deploymentTwo.getId());
    assertNull(deploymentTwo.getSource());
    assertNull(deploymentTwo.getTenantId());
  }

  public void testQuerySorting() {
    assertEquals(2, repositoryService.createDeploymentQuery()
        .orderByDeploymentName()
        .asc()
        .list()
        .size());

    assertEquals(2, repositoryService.createDeploymentQuery()
      .orderByDeploymentId()
      .asc()
      .list()
      .size());

    assertEquals(2, repositoryService.createDeploymentQuery()
      .orderByDeploymenTime()
      .asc()
      .list()
      .size());

    assertEquals(2, repositoryService.createDeploymentQuery()
      .orderByDeploymentTime()
      .asc()
      .list()
      .size());
  }

}


text:
ALTER TABLE IACUC_PROTOCOL_NOTEPAD
ADD CONSTRAINT FK_IACUC_PROTOCOL_NOTEPAD
FOREIGN KEY (PROTOCOL_ID_FK)
REFERENCES IACUC_PROTOCOL (PROTOCOL_ID)
/


text:
/* */
'use strict';
var $ = require("./$"),
    IteratorPrototype = {};
require("./$.hide")(IteratorPrototype, require("./$.wks")('iterator'), function() {
  return this;
});
module.exports = function(Constructor, NAME, next) {
  Constructor.prototype = $.create(IteratorPrototype, {next: require("./$.property-desc")(1, next)});
  require("./$.tag")(Constructor, NAME + ' Iterator');
};


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GOScript4 : MonoBehaviour {

	//Settings for the gameobject
    public decimal lt, ln;
    public int id;
	public string name;
    private float speed = 50f;
    public int score;
    public GameObject gameManager;
    private GameManager4 gmScript;
    private bool first;

	//Finding GameManager
    private void Awake() {
        gameManager = GameObject.FindGameObjectWithTag("GameManager");
        gmScript = gameManager.GetComponent<GameManager4>();
        first = true;
    }

    // Use this for initialization
    void Start() {

    }

    // Update is called once per frame
    void Update() {

    }

	//Set values and moving the gameobject
    public void SetValues(decimal lt, decimal ln, int id, int score, string name) {

		//bug.Log(lt + ", " + ln + ", " + this.name);

        this.id = id;
        this.score = score;

		if(this.name == "") {
			this.name = name;
		}

		if (this.CompareTag("Hunter") && first == false)
        {
			gmScript.UpdateScore(id, score, this.name);
        }

        //Checking if object is located on the field irl
        if (lt < gmScript.northernmostPoint && lt > gmScript.southernmosttPoint && ln < gmScript.easternmostPoint && ln > gmScript.westernmostPoint) {
            this.lt = lt;
            this.ln = ln;

			//If its first time to enter field, teleport object to position
            if (first == true) {
				transform.position = gmScript.MakeVector((float)ln, (float)lt);
                first = false;
            }
            this.GetComponent<Renderer>().enabled = true;
            transform.position = Vector3.MoveTowards(transform.position, gmScript.MakeVector((float)ln, (float)lt), speed * Time.deltaTime);
        }
        else {
            this.GetComponent<Renderer>().enabled = false;
			first = true;
        }
    }

}


text:
WebivaBarChart = function(opts) {
  var $ = jQuery;
  var data = opts.data;
  var labels = opts.labels ? opts.labels : null;
  var columns = opts.columns ? opts.columns : null;
  var urls = opts.urls ? opts.urls : null;
  var sortCol = opts.sortCol ? opts.sortCol : 0;
  var sortDesc = opts.sortDesc ? opts.sortDesc : true;
  var canvas = opts.canvas ? opts.canvas : 'chart_canvas';
  var container = opts.container ? opts.container : null;
  var maxValue = 0;
  var dataTable = new Array();
  var chartWidth = opts.width ? opts.width : 600;
  var chartHeight = opts.height ? opts.height : 600;
  var fontSize = opts.fontSize ? opts.fontSize : 10.5;
  var fontFamily = opts.fontFamily ? opts.fontFamily : 'san-serif';
  var font = fontSize + 'px ' + fontFamily;
  var chartType = opts.type ? opts.type : 'column';
  var currentWidth = 0;

  for(var i=0; i<data.length; i++) {
    maxValue = Math.max(maxValue, data[i].max());
    dataTable.push({data: data[i], url: urls ? urls[i] : null, label: labels ? labels[i] : null});
  }

  function sort(col) {
    if(col != undefined) {
      if(sortCol == col) {
        sortDesc = ! sortDesc;
      } else {
        sortDesc = true;
      }
      sortCol = col;
    }

    dataTable.sort(function(a, b) {
                     if(sortDesc) {
                       return b.data[sortCol] - a.data[sortCol];
                     }
                     return a.data[sortCol] - b.data[sortCol];
                   });
  }

  function canvasWidth() {
    var width = chartWidth;
    if(container) {
      width = $('#' + container).width();
    } else {
      width = $('#' + canvas).width();
    }
    return width > chartWidth ? width : chartWidth;
  }

  function canvasHeight() {
    var height = chartHeight;
    if(container) {
      height = $('#' + container).height();
    } else {
      height = $('#' + canvas).height();
    }
    return height > chartHeight ? height : chartHeight;
  }

  function truncate(str, length) {
    length = length ? length : 25;

    if(str.length > length) {
      return str.substring(0, length-3) + '...';
    }

    return str;
  }

  function gotoUrl(url) {
    if(url) {
      document.location = url;
    }
  }

  function getTextDims(txt) {
    var box = $('#webiva-font-box');
    if(box.length == 0) {
      $('').appendTo('body');
      box = $('#webiva-font-box');
    }
    box.text(txt);
    return {width: box.width(), height: box.height()};
  }

  function draw(force) {
    if(dataTable.length == 0) {
      return;
    }

    var chart = chartType == 'bar' ? drawBarChart(force) : drawColumnChart(force);

    if(container) {
      $(window).resize(function() {draw();});
    }

    return chart;
  }

  function drawBarChart(force) {
    var textDim = getTextDims(new Array((maxValue+'').length+1).join('0'));
    textDim.width += 10;

    var legendDim = {width:5, height:5};
    if(columns) {
      for(var i=0; i<columns.length; i++) {
        dim = getTextDims(columns[i]);
        if(legendDim == null || dim.width > legendDim.width) {
          legendDim = dim;
        }
      }
      legendDim.width += 30;
    }

    var labelDim = getTextDims('X');
    if(labels) {
      for(var i=0; i<labels.length; i++) {
        dim = getTextDims(labels[i]);
        if(labelDim == null || dim.width > labelDim.width) {
          labelDim = dim;
        }
      }
      labelDim.height += 5;
    }

    /* Sizing and scales. */
    var rows = dataTable.length,
        barsPerRow = dataTable[0].data.length,
        marginTop = 5,
        marginBottom = labelDim.height,
        marginLeft = textDim.width,
        marginRight = legendDim.width,
        w = canvasWidth() - (marginLeft + marginRight),
        h = canvasHeight() - (marginTop + marginBottom),
        x = pv.Scale.ordinal(pv.range(rows)).splitBanded(0, w, 4/5),
        y = pv.Scale.linear(0, maxValue).range(0, h)
        legendWidth = marginRight - 5,
        legendX = (w + 5),
        legendSize = 5,
        legendY = 0,
        fontColor = '#603813',
        colors = pv.colors('#C7CB2D', '#754C28');

    if(currentWidth == w) {
      return;
    }
    currentWidth = w;

    /* The root panel. */
    var vis = new pv.Panel()
       .width(w)
       .height(h)
       .bottom(marginBottom)
       .left(marginLeft)
       .right(marginRight)
       .top(marginTop)
       .canvas(canvas);

    /* The bars. */
    var bar = vis.add(pv.Panel)
       .data(dataTable)
       .left(function() {return x(this.index);})
       .width(x.range().band)
       .add(pv.Bar)
       .data(function(d) {return d.data;})
       .bottom(0)
       .height(y)
       .left(function() {return this.index * x.range().band / barsPerRow;})
       .width(x.range().band / barsPerRow)
       .fillStyle(colors.by(pv.index))
       .textStyle(fontColor)
       .font(font)
       .text(function(d) {return d + (columns ? ' ' + columns[this.index] : '');})
       .event("mouseover", pv.Behavior.tipsy({gravity: "s", fade: true}));

    if(columns) {
      /* The legend. */
      vis.add(pv.Bar)
         .data(columns)
         .top(function() {return this.index * 14 + marginTop;})
         .height(12)
         .left(legendX)
         .width(12)
         .fillStyle(colors.by(pv.index))
         .event("click", function() {sort(this.index); draw(true);})
         .anchor("right").add(pv.Label)
         .textMargin(5)
         .textAlign("left")
         .textStyle(fontColor)
         .font(font)
         .text(function() {return columns[this.index];})
         .events("all")
         .event("click", function() {sort(this.index); draw(true);});
     }

    if(labels) {
      /* The variable label. */
      bar.parent.anchor("bottom").add(pv.Label)
         .textBaseline("top")
         .textMargin(6)
         .textAlign("center")
         .textStyle(fontColor)
         .font(font)
         .text(function() {return truncate(dataTable[this.parent.index].label, 25);})
         .title(function() {return dataTable[this.parent.index].label;})
         .events("all")
         .event("click", function() {gotoUrl(dataTable[this.parent.index].url);});
    }

    var numTicks = 5;
    if(maxValue < 5) {
      numTicks = maxValue;
    }

    /* Y-axis ticks. */
    vis.add(pv.Rule)
        .data(y.ticks(numTicks))
        .bottom(y)
        .strokeStyle(function(d) {return d ? "rgba(255,255,255,.3)" : "#000";})
        .add(pv.Rule)
        .left(function(d) {return d ? -2 : 0;})
        .width(5)
        .strokeStyle(fontColor)
        .anchor("left").add(pv.Label)
        .textStyle(fontColor)
        .font(font)
        .text(y.tickFormat);

    /* X-axis ticks. */
    vis.add(pv.Rule)
        .bottom(0)
        .left(0)
        .height(h);

    vis.render();
  }

  function drawColumnChart(force) {
    var textDim = getTextDims(new Array((maxValue+'').length+1).join('0'));
    var legendDim = {width:5, height:5};
    if(columns) {
      for(var i=0; i<columns.length; i++) {
        dim = getTextDims(columns[i]);
        if(legendDim == null || dim.width > legendDim.width) {
          legendDim = dim;
        }
      }
      legendDim.width += 30;
    }

    var labelDim = getTextDims('X');
    if(labels) {
      for(var i=0; i<labels.length; i++) {
        dim = getTextDims(labels[i]);
        if(labelDim == null || dim.width > labelDim.width) {
          labelDim = dim;
        }
      }
      labelDim.width += 10;
    }

    /* Sizing and scales. */
    var rows = dataTable.length,
        barsPerRow = dataTable[0].data.length,
        marginTop = 5,
        marginBottom = textDim.height,
        marginLeft = labelDim.width,
        marginRight = legendDim.width,
        w = canvasWidth() - (marginLeft + marginRight),
        h = (rows * (barsPerRow * 12 + 5)),
        x = pv.Scale.linear(0, maxValue).range(0, w),
        y = pv.Scale.ordinal(pv.range(rows)).splitBanded(0, h, 4/5),
        legendWidth = marginRight - 5,
        legendX = (w + 5),
        legendSize = 5,
        legendY = 0,
        fontColor = '#603813',
        colors = pv.colors('#C7CB2D', '#754C28');

    if(currentWidth == w) {
      return;
    }
    currentWidth = w;

    /* The root panel. */
    var vis = new pv.Panel()
        .width(w)
        .height(h)
        .bottom(marginBottom)
        .left(marginLeft)
        .right(marginRight)
        .top(marginTop)
        .canvas(canvas);

    /* The bars. */
    var bar = vis.add(pv.Panel)
       .data(dataTable)
       .top(function() {return y(this.index);})
       .height(y.range().band)
       .add(pv.Bar)
       .data(function(d) {return d.data;})
       .top(function() {return this.index * y.range().band / barsPerRow;})
       .height(y.range().band / barsPerRow)
       .left(0)
       .width(x)
       .fillStyle(colors.by(pv.index))
       .textStyle(fontColor)
       .font(font)
       .text(function(d) {return d + (columns ? ' ' + columns[this.index] : '');})
       .event("mouseover", pv.Behavior.tipsy({gravity: "w", fade: true}));

    if(columns) {
      /* The legend. */
      vis.add(pv.Bar)
         .data(columns)
         .top(function() {return this.index * 14 + marginTop;})
         .height(12)
         .left(legendX)
         .width(12)
         .fillStyle(colors.by(pv.index))
         .event("click", function() {sort(this.index); draw(true);})
         .anchor("right").add(pv.Label)
         .textMargin(5)
         .textAlign("left")
         .textStyle(fontColor)
         .font(font)
         .text(function() {return columns[this.index];})
         .events("all")
         .event("click", function() {sort(this.index); draw(true);});
     }

    if(urls) {
      /* The label urls. */
      bar.parent.add(pv.Bar)
         .left(-marginLeft)
         .height(y.range().band)
         .width(marginLeft-1)
         .fillStyle('#FFF')
         .event("click", function() {gotoUrl(dataTable[this.parent.index].url);});
    }

    if(labels) {
      /* The variable label. */
      bar.parent.anchor("left").add(pv.Label)
         .textMargin(5)
         .textAlign("right")
         .textStyle(fontColor)
         .font(font)
         .text(function() {return truncate(dataTable[this.parent.index].label, 40);})
         .title(function() {return dataTable[this.parent.index].label;})
         .events("all");
    }

    var numTicks = 5;
    if(maxValue < 5) {
      numTicks = maxValue;
    }

    /* X-axis ticks. */
    vis.add(pv.Rule)
        .data(x.ticks(numTicks))
        .left(x)
        .strokeStyle(function(d) {return d ? "rgba(255,255,255,.3)" : "#000";})
        .add(pv.Rule)
        .bottom(0)
        .height(5)
        .strokeStyle(fontColor)
        .anchor("bottom").add(pv.Label)
        .textStyle(fontColor)
        .font(font)
        .text(x.tickFormat);

    vis.render();
  }

  return {draw: draw, sort: sort};
};

WebivaBarChart.fetch = function(url, opts) {
  if(opts == undefined) { opts = {}; }
  $j.getJSON(url, function(res) {
               opts.data = res.data;
               opts.columns = res.columns;
               var chart = WebivaBarChart(opts);
               if(opts.sortCol) { chart.sort(opts.sortCol); }
               chart.draw();
             });
};


text:
"use strict";

const assert = require("assert");
const tf = require("@tensorflow/tfjs");
const tfn = require("@tensorflow/tfjs-node");
const {createSandbox} = require("./_common");

const MODEL_URL = "data/mlHideIfGraphMatches/model.json";
const OTHER_MODEL_URL = "data/mlHideIfGraphMatches/otherModel.json";

describe("ML", function()
{
  let ML = null;

  beforeEach(function()
  {
    let sandboxedRequire = createSandbox();
    (
      {ML} = sandboxedRequire("../lib/ml")
    );
  });

  describe("#constructor()", function()
  {
    // A TensorFlow library must be specified.
    it("should throw when lib is missing", function()
    {
      assert.throws(() => new ML(), Error);
    });

    it("should throw when lib is null", function()
    {
      assert.throws(() => new ML(null), Error);
    });

    // Should work with tf library specified.
    it("should not throw when lib is non-null", function()
    {
      assert.doesNotThrow(() => new ML(tf));
    });
  });

  describe("#get modelURL()", function()
  {
    let ml = null;
    let modelURL = null;
    let otherModelURL = null;

    beforeEach(function()
    {
      ml = new ML(tf);
      modelURL = tfn.io.fileSystem(MODEL_URL);
      otherModelURL = tfn.io.fileSystem(OTHER_MODEL_URL);
    });

    it("should return null if not set", function()
    {
      assert.strictEqual(ml.modelURL, null);
    });

    it("should return value if set", function()
    {
      ml.modelURL = modelURL;
      assert.strictEqual(ml.modelURL, modelURL);
    });

    it("should return null if reset to null", function()
    {
      ml.modelURL = modelURL;
      ml.modelURL = null;
      assert.strictEqual(ml.modelURL, null);
    });

    it("should return value if set to different value", function()
    {
      ml.modelURL = modelURL;
      ml.modelURL = otherModelURL;
      assert.strictEqual(ml.modelURL, otherModelURL);
    });
  });

  describe("#set modelURL()", function()
  {
    let ml = null;
    let modelURL = null;
    let otherModelURL = null;

    beforeEach(function()
    {
      ml = new ML(tf);
      modelURL = tfn.io.fileSystem(MODEL_URL);
      otherModelURL = tfn.io.fileSystem(OTHER_MODEL_URL);
    });

    it("should not throw when set", function()
    {
      assert.doesNotThrow(() => ml.modelURL = modelURL);
    });

    it("should not throw when reset to null", function()
    {
      ml.modelURL = modelURL;
      assert.doesNotThrow(() => ml.modelURL = null);
    });

    it("should not throw when set to different value", function()
    {
      ml.modelURL = modelURL;
      assert.doesNotThrow(() => ml.modelURL = otherModelURL);
    });
  });
});


text:
/*
 * This an unstable interface of wlroots. No guarantees are made regarding the
 * future consistency of this API.
 */
#ifndef WLR_USE_UNSTABLE
#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features"
#endif

#ifndef WLR_TYPES_WLR_TOUCH_H
#define WLR_TYPES_WLR_TOUCH_H

#include <stdint.h>
#include <wayland-server-core.h>

struct wlr_touch_impl;

struct wlr_touch {
	const struct wlr_touch_impl *impl;

	struct {
		struct wl_signal down; // struct wlr_event_touch_down
		struct wl_signal up; // struct wlr_event_touch_up
		struct wl_signal motion; // struct wlr_event_touch_motion
		struct wl_signal cancel; // struct wlr_event_touch_cancel
		struct wl_signal frame;
	} events;

	void *data;
};

struct wlr_event_touch_down {
	struct wlr_input_device *device;
	uint32_t time_msec;
	int32_t touch_id;
	// From 0..1
	double x, y;
};

struct wlr_event_touch_up {
	struct wlr_input_device *device;
	uint32_t time_msec;
	int32_t touch_id;
};

struct wlr_event_touch_motion {
	struct wlr_input_device *device;
	uint32_t time_msec;
	int32_t touch_id;
	// From 0..1
	double x, y;
};

struct wlr_event_touch_cancel {
	struct wlr_input_device *device;
	uint32_t time_msec;
	int32_t touch_id;
};

#endif


text:
class OnQueue

end


text:
The Sidecar will be enabled in a Studio if there is an implementations of the part `part:@sanity/default-layout/sidecar`

### `part:@sanity/default-layout/sidecar`

An implementation of `part:@sanity/default-layout/sidecar` _must_ export these:

 - `SidecarToggleButton` React component. The button which will appear in the Navbar to toggle on/off the Sidecar
 - `SidecarLayout` React component. The content of the Sidecar (once it appears)
 - `isSidecarEnabled` Function. Call this to check if the Sidecar implementation is happy and good to go (typically, the sidecar impl. wants to verify if config is present)

If you need inspiration, the `@sanity/studio-hints` package is an implementation of this part.

### `part:@sanity/default-layout/sidecar-datastore`

In addition, Sidecar relies on `part:@sanity/default-layout/sidecar-datastore`. This part already exists and shouldn't be overridden unless there's a good reason. This part exports:

- `isSidecarOpenSetting` listen to this to get realtime updates on the sidecar open/close state
- `toggleSidecarOpenState` call this to flip the sidecar open/close state


text:
package org.assertj.core.internal;

import static org.assertj.core.test.ExpectedException.none;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import java.io.File;

import org.assertj.core.test.ExpectedException;
import org.assertj.core.util.diff.Delta;
import org.junit.Before;
import org.junit.Rule;

/**
 * Base class for testing {@link Files}, set up diff and failures attributes (which is why it is in
 * org.assertj.core.internal package.
 *
 * @author Joel Costigliola
 */
public class FilesBaseTest {

  @Rule
  public ExpectedException thrown = none();
  protected File actual;
  protected Failures failures;
  protected Files files;
  protected Files unMockedFiles;
  protected Diff diff;
  protected Delta<String> delta;
  protected BinaryDiff binaryDiff;

  @SuppressWarnings("unchecked")
  @Before
  public void setUp() {
    actual = mock(File.class);
    failures = spy(new Failures());
    files = new Files();
    unMockedFiles = new Files();
    files.failures = failures;
    diff = mock(Diff.class);
    delta = mock(Delta.class);
    when(delta.toString()).thenReturn("Extra lines at line 2 : [line1a, line1b]");
    files.diff = diff;
    binaryDiff = mock(BinaryDiff.class);
    files.binaryDiff = binaryDiff;
  }

}


text:
declare module 'pump' {
  function pump<T extends NodeJS.ReadableStream>(
    ...args: Array<T | NodeJS.ReadableStream | pump.Callback>
  ): T

  namespace pump {
    type Callback = (error?: Error | null) => unknown
  }

  export = pump
}


text:
var core = require('../../core');
var generateBlurVertSource  = require('./generateBlurVertSource');
var generateBlurFragSource  = require('./generateBlurFragSource');
var getMaxBlurKernelSize    = require('./getMaxBlurKernelSize');

/**
 * The BlurYFilter applies a horizontal Gaussian blur to an object.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */
function BlurYFilter(strength, quality, resolution)
{
    var vertSrc = generateBlurVertSource(5, false);
    var fragSrc = generateBlurFragSource(5);

    core.Filter.call(this,
        // vertex shader
        vertSrc,
        // fragment shader
        fragSrc
    );

    this.resolution = resolution || 1;

    this._quality = 0;

    this.quality = quality || 4;
    this.strength = strength || 8;

    this.firstRun = true;
}

BlurYFilter.prototype = Object.create(core.Filter.prototype);
BlurYFilter.prototype.constructor = BlurYFilter;
module.exports = BlurYFilter;

BlurYFilter.prototype.apply = function (filterManager, input, output, clear)
{
    if(this.firstRun)
    {
        var gl = filterManager.renderer.gl;
        var kernelSize = getMaxBlurKernelSize(gl);

        this.vertexSrc = generateBlurVertSource(kernelSize, false);
        this.fragmentSrc = generateBlurFragSource(kernelSize);

        this.firstRun = false;
    }

    this.uniforms.strength = (1/output.size.height) * (output.size.height/input.size.height); /// // *  2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width);

    this.uniforms.strength *= this.strength;
    this.uniforms.strength /= this.passes;

    if(this.passes === 1)
    {
        filterManager.applyFilter(this, input, output, clear);
    }
    else
    {
        var renderTarget = filterManager.getRenderTarget(true);
        var flip = input;
        var flop = renderTarget;

        for(var i = 0; i < this.passes-1; i++)
        {
            filterManager.applyFilter(this, flip, flop, true);

           var temp = flop;
           flop = flip;
           flip = temp;
        }

        filterManager.applyFilter(this, flip, output, clear);

        filterManager.returnRenderTarget(renderTarget);
    }
};

Object.defineProperties(BlurYFilter.prototype, {
    /**
     * Sets the strength of both the blur.
     *
     * @member {number}
     * @memberof PIXI.filters.BlurYFilter#
     * @default 2
     */
    blur: {
        get: function ()
        {
            return  this.strength;
        },
        set: function (value)
        {
            this.padding = Math.abs(value) * 2;
            this.strength = value;
        }
    },

    /**
     * Sets the quality of the blur by modifying the number of passes. More passes means higher quaility bluring but the lower the performance.
     *
     * @member {number}
     * @memberof PIXI.filters.BlurXFilter#
     * @default 4
     */
    quality: {
        get: function ()
        {
            return  this._quality;
        },
        set: function (value)
        {
            this._quality = value;
            this.passes = value;
        }
    }
});


text:
package org.kabuki.utils;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.TreeMap;

public class UnsafeUtils {
    public static final Unsafe unsafe;

    static {
        try {
            Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
            unsafeField.setAccessible(true);
            unsafe = (Unsafe) unsafeField.get(null);

        } catch (Throwable exception) {
            throw new Error("Can't get unsafe", exception);
        }
    }

    public static long getDeclaredFieldOffset(Class<?> type, String name) {
        try {
            return unsafe.objectFieldOffset(type.getDeclaredField(name));
        } catch (NoSuchFieldException | SecurityException e) {
            throw new RuntimeException(e);
        }
    }

    // TODO: do special version for java 8 ?
    public static int getAndIncrementInt(Object object, long offset) {
        for (;;) {
            int current = unsafe.getIntVolatile(object, offset);
            int next = current + 1;
            if (compareAndSet(object, offset, current, next)) {
                return current;
            }
        }
    }

    public static boolean compareAndSet(Object object, long offset, int expect, int update) {
        return unsafe.compareAndSwapInt(object, offset, expect, update);
    }

    public static boolean compareAndSet(Object object, long offset, long expect, long update) {
        return unsafe.compareAndSwapLong(object, offset, expect, update);
    }

    public static void putOrderedInt(Object object, long offset, int update) {
        unsafe.putOrderedInt(object, offset, update);
    }

    public static String getLayout(Class c) {
        TreeMap<Long, Field> fields = new TreeMap<>();
        for (Field field : c.getDeclaredFields()) {
            if ((field.getModifiers() & Modifier.STATIC) == 0) {
                fields.put(unsafe.objectFieldOffset(field), field);
            }
        }
        StringBuilder s = new StringBuilder(c.getCanonicalName()).append("[");
        for (Map.Entry<Long, Field> field : fields.entrySet()) {
            s.append(field.getKey()).append(":").append(field.getValue().getName()).append(", ");
        }
        if (!fields.isEmpty()) {
            s.setLength(s.length() - 2);
        }
        s.append("]");
        return s.toString();
    }
}


text:
using System;
using System.Runtime.Serialization;
using CacheProvider.Interface;

namespace CacheProvider.Model
{
	[Serializable, DataContract]
	public class CacheModel : ICacheModel
    {
		[DataMember]
		public string CacheKey { get; set; }
		[DataMember]
		public DateTime Expires { get; set; }
		[DataMember]
		public CacheObject CacheObject { get; set; }
		[DataMember]
		public CacheOptions CacheOptions { get; set; }
    }
}


text:
package org.gradoop.temporal.model.impl.operators.matching.single.cypher.operators.filter.functions;

import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.util.Collector;
import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.CNF;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.temporal.model.impl.operators.matching.single.cypher.pojos.EmbeddingTPGMFactory;
import org.gradoop.temporal.model.impl.pojo.TemporalVertex;

import java.util.List;

/**
 * Applies a given predicate on a {@link org.gradoop.temporal.model.impl.pojo.TemporalVertex}
 * and projects specified property values to the output embedding.
 */
public class FilterAndProjectTemporalVertex extends RichFlatMapFunction<TemporalVertex, Embedding> {

  /**
   * Predicates used for filtering
   */
  private final CNF predicates;
  /**
   * Property keys used for value projection
   */
  private final List<String> projectionPropertyKeys;

  /**
   * New vertex filter function
   *
   * @param predicates             predicates used for filtering
   * @param projectionPropertyKeys property keys that will be used for projection
   */
  public FilterAndProjectTemporalVertex(CNF predicates, List<String> projectionPropertyKeys) {
    this.predicates = predicates;
    this.projectionPropertyKeys = projectionPropertyKeys;
  }

  @Override
  public void flatMap(TemporalVertex vertex, Collector<Embedding> out) throws Exception {
    if (predicates.evaluate(vertex)) {
      out.collect(EmbeddingTPGMFactory.fromVertex(vertex, projectionPropertyKeys));
    }
  }
}


text:
require 'active_merchant/billing/gateways/maxipago/maxipago_common_api'

module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    # This module is included in MaxipagoGateway
    module MaxipagoRecurringAPI
      # Create a recurring payment.
      #
      # This transaction creates a recurring payment transaction
      # ==== Parameters
      #
      # * <tt>amount</tt> -- The amount to be charged to the customer at each interval as an Integer value in cents.
      # * <tt>credit_card</tt> -- The CreditCard details for the transaction.
      # * <tt>options</tt> -- A hash of parameters.
      #
      # ==== Options
      #
      # * <tt>:period</tt> -- [monthly, weekly, daily] (REQUIRED)
      # * <tt>:frequency</tt> -- a number (REQUIRED)
      # * <tt>:installments</tt> -- Limit to certain # of cycles (REQUIRED)
      # * <tt>:start_date</tt> -- When does the charging starts (REQUIRED)
      def recurring(amount, credit_card, options = {})
        options[:amount] = amount

        extract_params(options, options[:subscription])

        requires!(options, :start_date, :period, :frequency, :amount, :installments)

        post = {}
        add_aux_data(post, options)
        add_amount(post, amount)
        add_creditcard(post, credit_card)
        add_name(post, credit_card)
        add_address(post, options)
        add_recurring(post, options)

        commit(build_sale_request(post, "recurringPayment"))
      end

      def cancel_recurring(order_id, options = {})
        commit(build_api_request('cancel-recurring', order_id), :api)
      end

      private

      def extract_params(options, subscription)
        return unless subscription
        options[:start_date] = Time.now + subscription[:trials].to_i
        options[:period] = subscription[:period]
        options[:frequency] = subscription[:frequency] || 1
        options[:installments] = subscription[:cicles] || 12
      end

      def add_recurring(post, options)
        post[:recurring] = {}
        post[:recurring][:start_date] = options[:start_date].strftime('%Y-%m-%d')
        post[:recurring][:frequency] = options[:frequency]
        post[:recurring][:period] = options[:period]
        post[:recurring][:installments] = options[:installments]
        post[:recurring][:failureThreshold] = options[:failureThreshold] || 1
      end

    end
  end
end