text:
#include <cilantro/3rd_party/libqhull_r/qhull_ra.h>

/*======== functions in alphabetical order ==========*/

/*---------------------------------

  qh_appendfacet(qh, facet )
    appends facet to end of qh.facet_list,

  returns:
    updates qh.newfacet_list, facet_next, facet_list
    increments qh.numfacets

  notes:
    assumes qh.facet_list/facet_tail is defined (createsimplex)

  see:
    qh_removefacet()

*/
void qh_appendfacet(qhT *qh, facetT *facet) {
  facetT *tail= qh->facet_tail;

  if (tail == qh->newfacet_list)
    qh->newfacet_list= facet;
  if (tail == qh->facet_next)
    qh->facet_next= facet;
  facet->previous= tail->previous;
  facet->next= tail;
  if (tail->previous)
    tail->previous->next= facet;
  else
    qh->facet_list= facet;
  tail->previous= facet;
  qh->num_facets++;
  trace4((qh, qh->ferr, 4044, "qh_appendfacet: append f%d to facet_list\n", facet->id));
} /* appendfacet */

/*---------------------------------

  qh_appendvertex(qh, vertex )
    appends vertex to end of qh.vertex_list,

  returns:
    sets vertex->newlist
    updates qh.vertex_list, newvertex_list
    increments qh.num_vertices

  notes:
    assumes qh.vertex_list/vertex_tail is defined (createsimplex)

*/
void qh_appendvertex(qhT *qh, vertexT *vertex) {
  vertexT *tail= qh->vertex_tail;

  if (tail == qh->newvertex_list)
    qh->newvertex_list= vertex;
  vertex->newlist= True;
  vertex->previous= tail->previous;
  vertex->next= tail;
  if (tail->previous)
    tail->previous->next= vertex;
  else
    qh->vertex_list= vertex;
  tail->previous= vertex;
  qh->num_vertices++;
  trace4((qh, qh->ferr, 4045, "qh_appendvertex: append v%d to vertex_list\n", vertex->id));
} /* appendvertex */

/*---------------------------------

  qh_attachnewfacets(qh, )
    attach horizon facets to new facets in qh.newfacet_list
    newfacets have neighbor and ridge links to horizon but not vice versa
    only needed for qh.ONLYgood

  returns:
    set qh.NEWfacets
    horizon facets linked to new facets
      ridges changed from visible facets to new facets
      simplicial ridges deleted
    qh.visible_list, no ridges valid
    facet->f.replace is a newfacet (if any)

  design:
    delete interior ridges and neighbor sets by
      for each visible, non-simplicial facet
        for each ridge
          if last visit or if neighbor is simplicial
            if horizon neighbor
              delete ridge for horizon's ridge set
            delete ridge
        erase neighbor set
    attach horizon facets and new facets by
      for all new facets
        if corresponding horizon facet is simplicial
          locate corresponding visible facet {may be more than one}
          link visible facet to new facet
          replace visible facet with new facet in horizon
        else it's non-simplicial
          for all visible neighbors of the horizon facet
            link visible neighbor to new facet
            delete visible neighbor from horizon facet
          append new facet to horizon's neighbors
          the first ridge of the new facet is the horizon ridge
          link the new facet into the horizon ridge
*/
void qh_attachnewfacets(qhT *qh /* qh.visible_list, newfacet_list */) {
  facetT *newfacet= NULL, *neighbor, **neighborp, *horizon, *visible;
  ridgeT *ridge, **ridgep;

  qh->NEWfacets= True;
  trace3((qh, qh->ferr, 3012, "qh_attachnewfacets: delete interior ridges\n"));
  qh->visit_id++;
  FORALLvisible_facets {
    visible->visitid= qh->visit_id;
    if (visible->ridges) {
      FOREACHridge_(visible->ridges) {
        neighbor= otherfacet_(ridge, visible);
        if (neighbor->visitid == qh->visit_id
            || (!neighbor->visible && neighbor->simplicial)) {
          if (!neighbor->visible)  /* delete ridge for simplicial horizon */
            qh_setdel(neighbor->ridges, ridge);
          qh_setfree(qh, &(ridge->vertices)); /* delete on 2nd visit */
          qh_memfree(qh, ridge, (int)sizeof(ridgeT));
        }
      }
      SETfirst_(visible->ridges)= NULL;
    }
    SETfirst_(visible->neighbors)= NULL;
  }
  trace1((qh, qh->ferr, 1017, "qh_attachnewfacets: attach horizon facets to new facets\n"));
  FORALLnew_facets {
    horizon= SETfirstt_(newfacet->neighbors, facetT);
    if (horizon->simplicial) {
      visible= NULL;
      FOREACHneighbor_(horizon) {   /* may have more than one horizon ridge */
        if (neighbor->visible) {
          if (visible) {
            if (qh_setequal_skip(newfacet->vertices, 0, horizon->vertices,
                                  SETindex_(horizon->neighbors, neighbor))) {
              visible= neighbor;
              break;
            }
          }else
            visible= neighbor;
        }
      }
      if (visible) {
        visible->f.replace= newfacet;
        qh_setreplace(qh, horizon->neighbors, visible, newfacet);
      }else {
        qh_fprintf(qh, qh->ferr, 6102, "qhull internal error (qh_attachnewfacets): couldn't find visible facet for horizon f%d of newfacet f%d\n",
                 horizon->id, newfacet->id);
        qh_errexit2(qh, qh_ERRqhull, horizon, newfacet);
      }
    }else { /* non-simplicial, with a ridge for newfacet */
      FOREACHneighbor_(horizon) {    /* may hold for many new facets */
        if (neighbor->visible) {
          neighbor->f.replace= newfacet;
          qh_setdelnth(qh, horizon->neighbors,
                        SETindex_(horizon->neighbors, neighbor));
          neighborp--; /* repeat */
        }
      }
      qh_setappend(qh, &horizon->neighbors, newfacet);
      ridge= SETfirstt_(newfacet->ridges, ridgeT);
      if (ridge->top == horizon)
        ridge->bottom= newfacet;
      else
        ridge->top= newfacet;
      }
  } /* newfacets */
  if (qh->PRINTstatistics) {
    FORALLvisible_facets {
      if (!visible->f.replace)
        zinc_(Zinsidevisible);
    }
  }
} /* attachnewfacets */

/*---------------------------------

  qh_checkflipped(qh, facet, dist, allerror )
    checks facet orientation to interior point

    if allerror set,
      tests against qh.DISTround
    else
      tests against 0 since tested against DISTround before

  returns:
    False if it flipped orientation (sets facet->flipped)
    distance if non-NULL
*/
boolT qh_checkflipped(qhT *qh, facetT *facet, realT *distp, boolT allerror) {
  realT dist;

  if (facet->flipped && !distp)
    return False;
  zzinc_(Zdistcheck);
  qh_distplane(qh, qh->interior_point, facet, &dist);
  if (distp)
    *distp= dist;
  if ((allerror && dist > -qh->DISTround)|| (!allerror && dist >= 0.0)) {
    facet->flipped= True;
    zzinc_(Zflippedfacets);
    trace0((qh, qh->ferr, 19, "qh_checkflipped: facet f%d is flipped, distance= %6.12g during p%d\n",
              facet->id, dist, qh->furthest_id));
    qh_precision(qh, "flipped facet");
    return False;
  }
  return True;
} /* checkflipped */

/*---------------------------------

  qh_delfacet(qh, facet )
    removes facet from facet_list and frees up its memory

  notes:
    assumes vertices and ridges already freed
*/
void qh_delfacet(qhT *qh, facetT *facet) {
  void **freelistp; /* used if !qh_NOmem by qh_memfree_() */

  trace4((qh, qh->ferr, 4046, "qh_delfacet: delete f%d\n", facet->id));
  if (facet == qh->tracefacet)
    qh->tracefacet= NULL;
  if (facet == qh->GOODclosest)
    qh->GOODclosest= NULL;
  qh_removefacet(qh, facet);
  if (!facet->tricoplanar || facet->keepcentrum) {
    qh_memfree_(qh, facet->normal, qh->normal_size, freelistp);
    if (qh->CENTERtype == qh_ASvoronoi) {   /* braces for macro calls */
      qh_memfree_(qh, facet->center, qh->center_size, freelistp);
    }else /* AScentrum */ {
      qh_memfree_(qh, facet->center, qh->normal_size, freelistp);
    }
  }
  qh_setfree(qh, &(facet->neighbors));
  if (facet->ridges)
    qh_setfree(qh, &(facet->ridges));
  qh_setfree(qh, &(facet->vertices));
  if (facet->outsideset)
    qh_setfree(qh, &(facet->outsideset));
  if (facet->coplanarset)
    qh_setfree(qh, &(facet->coplanarset));
  qh_memfree_(qh, facet, (int)sizeof(facetT), freelistp);
} /* delfacet */

/*---------------------------------

  qh_deletevisible()
    delete visible facets and vertices

  returns:
    deletes each facet and removes from facetlist
    at exit, qh.visible_list empty (== qh.newfacet_list)

  notes:
    ridges already deleted
    horizon facets do not reference facets on qh.visible_list
    new facets in qh.newfacet_list
    uses   qh.visit_id;
*/
void qh_deletevisible(qhT *qh /*qh.visible_list*/) {
  facetT *visible, *nextfacet;
  vertexT *vertex, **vertexp;
  int numvisible= 0, numdel= qh_setsize(qh, qh->del_vertices);

  trace1((qh, qh->ferr, 1018, "qh_deletevisible: delete %d visible facets and %d vertices\n",
         qh->num_visible, numdel));
  for (visible= qh->visible_list; visible && visible->visible;
                visible= nextfacet) { /* deleting current */
    nextfacet= visible->next;
    numvisible++;
    qh_delfacet(qh, visible);
  }
  if (numvisible != qh->num_visible) {
    qh_fprintf(qh, qh->ferr, 6103, "qhull internal error (qh_deletevisible): qh->num_visible %d is not number of visible facets %d\n",
             qh->num_visible, numvisible);
    qh_errexit(qh, qh_ERRqhull, NULL, NULL);
  }
  qh->num_visible= 0;
  zadd_(Zvisfacettot, numvisible);
  zmax_(Zvisfacetmax, numvisible);
  zzadd_(Zdelvertextot, numdel);
  zmax_(Zdelvertexmax, numdel);
  FOREACHvertex_(qh->del_vertices)
    qh_delvertex(qh, vertex);
  qh_settruncate(qh, qh->del_vertices, 0);
} /* deletevisible */

/*---------------------------------

  qh_facetintersect(qh, facetA, facetB, skipa, skipB, prepend )
    return vertices for intersection of two simplicial facets
    may include 1 prepended entry (if more, need to settemppush)

  returns:
    returns set of qh.hull_dim-1 + prepend vertices
    returns skipped index for each test and checks for exactly one

  notes:
    does not need settemp since set in quick memory

  see also:
    qh_vertexintersect and qh_vertexintersect_new
    use qh_setnew_delnthsorted to get nth ridge (no skip information)

  design:
    locate skipped vertex by scanning facet A's neighbors
    locate skipped vertex by scanning facet B's neighbors
    intersect the vertex sets
*/
setT *qh_facetintersect(qhT *qh, facetT *facetA, facetT *facetB,
                         int *skipA,int *skipB, int prepend) {
  setT *intersect;
  int dim= qh->hull_dim, i, j;
  facetT **neighborsA, **neighborsB;

  neighborsA= SETaddr_(facetA->neighbors, facetT);
  neighborsB= SETaddr_(facetB->neighbors, facetT);
  i= j= 0;
  if (facetB == *neighborsA++)
    *skipA= 0;
  else if (facetB == *neighborsA++)
    *skipA= 1;
  else if (facetB == *neighborsA++)
    *skipA= 2;
  else {
    for (i=3; i < dim; i++) {
      if (facetB == *neighborsA++) {
        *skipA= i;
        break;
      }
    }
  }
  if (facetA == *neighborsB++)
    *skipB= 0;
  else if (facetA == *neighborsB++)
    *skipB= 1;
  else if (facetA == *neighborsB++)
    *skipB= 2;
  else {
    for (j=3; j < dim; j++) {
      if (facetA == *neighborsB++) {
        *skipB= j;
        break;
      }
    }
  }
  if (i >= dim || j >= dim) {
    qh_fprintf(qh, qh->ferr, 6104, "qhull internal error (qh_facetintersect): f%d or f%d not in others neighbors\n",
            facetA->id, facetB->id);
    qh_errexit2(qh, qh_ERRqhull, facetA, facetB);
  }
  intersect= qh_setnew_delnthsorted(qh, facetA->vertices, qh->hull_dim, *skipA, prepend);
  trace4((qh, qh->ferr, 4047, "qh_facetintersect: f%d skip %d matches f%d skip %d\n",
          facetA->id, *skipA, facetB->id, *skipB));
  return(intersect);
} /* facetintersect */

/*---------------------------------

  qh_gethash(qh, hashsize, set, size, firstindex, skipelem )
    return hashvalue for a set with firstindex and skipelem

  notes:
    returned hash is in [0,hashsize)
    assumes at least firstindex+1 elements
    assumes skipelem is NULL, in set, or part of hash

    hashes memory addresses which may change over different runs of the same data
    using sum for hash does badly in high d
*/
int qh_gethash(qhT *qh, int hashsize, setT *set, int size, int firstindex, void *skipelem) {
  void **elemp= SETelemaddr_(set, firstindex, void);
  ptr_intT hash = 0, elem;
  unsigned result;
  int i;
#ifdef _MSC_VER                   /* Microsoft Visual C++ -- warn about 64-bit issues */
#pragma warning( push)            /* WARN64 -- ptr_intT holds a 64-bit pointer */
#pragma warning( disable : 4311)  /* 'type cast': pointer truncation from 'void*' to 'ptr_intT' */
#endif

  switch (size-firstindex) {
  case 1:
    hash= (ptr_intT)(*elemp) - (ptr_intT) skipelem;
    break;
  case 2:
    hash= (ptr_intT)(*elemp) + (ptr_intT)elemp[1] - (ptr_intT) skipelem;
    break;
  case 3:
    hash= (ptr_intT)(*elemp) + (ptr_intT)elemp[1] + (ptr_intT)elemp[2]
      - (ptr_intT) skipelem;
    break;
  case 4:
    hash= (ptr_intT)(*elemp) + (ptr_intT)elemp[1] + (ptr_intT)elemp[2]
      + (ptr_intT)elemp[3] - (ptr_intT) skipelem;
    break;
  case 5:
    hash= (ptr_intT)(*elemp) + (ptr_intT)elemp[1] + (ptr_intT)elemp[2]
      + (ptr_intT)elemp[3] + (ptr_intT)elemp[4] - (ptr_intT) skipelem;
    break;
  case 6:
    hash= (ptr_intT)(*elemp) + (ptr_intT)elemp[1] + (ptr_intT)elemp[2]
      + (ptr_intT)elemp[3] + (ptr_intT)elemp[4]+ (ptr_intT)elemp[5]
      - (ptr_intT) skipelem;
    break;
  default:
    hash= 0;
    i= 3;
    do {     /* this is about 10% in 10-d */
      if ((elem= (ptr_intT)*elemp++) != (ptr_intT)skipelem) {
        hash ^= (elem <> (32-i));
        i += 3;
        if (i >= 32)
          i -= 32;
      }
    }while (*elemp);
    break;
  }
  if (hashsize<0) {
    qh_fprintf(qh, qh->ferr, 6202, "qhull internal error: negative hashsize %d passed to qh_gethash [poly.c]\n", hashsize);
    qh_errexit2(qh, qh_ERRqhull, NULL, NULL);
  }
  result= (unsigned)hash;
  result %= (unsigned)hashsize;
  /* result= 0; for debugging */
  return result;
#ifdef _MSC_VER
#pragma warning( pop)
#endif
} /* gethash */

/*---------------------------------

  qh_makenewfacet(qh, vertices, toporient, horizon )
    creates a toporient? facet from vertices

  returns:
    returns newfacet
      adds newfacet to qh.facet_list
      newfacet->vertices= vertices
      if horizon
        newfacet->neighbor= horizon, but not vice versa
    newvertex_list updated with vertices
*/
facetT *qh_makenewfacet(qhT *qh, setT *vertices, boolT toporient,facetT *horizon) {
  facetT *newfacet;
  vertexT *vertex, **vertexp;

  FOREACHvertex_(vertices) {
    if (!vertex->newlist) {
      qh_removevertex(qh, vertex);
      qh_appendvertex(qh, vertex);
    }
  }
  newfacet= qh_newfacet(qh);
  newfacet->vertices= vertices;
  newfacet->toporient= (unsigned char)toporient;
  if (horizon)
    qh_setappend(qh, &(newfacet->neighbors), horizon);
  qh_appendfacet(qh, newfacet);
  return(newfacet);
} /* makenewfacet */

/*---------------------------------

  qh_makenewplanes()
    make new hyperplanes for facets on qh.newfacet_list

  returns:
    all facets have hyperplanes or are marked for   merging
    doesn't create hyperplane if horizon is coplanar (will merge)
    updates qh.min_vertex if qh.JOGGLEmax

  notes:
    facet->f.samecycle is defined for facet->mergehorizon facets
*/
void qh_makenewplanes(qhT *qh /* qh.newfacet_list */) {
  facetT *newfacet;

  FORALLnew_facets {
    if (!newfacet->mergehorizon)
      qh_setfacetplane(qh, newfacet);
  }
  if (qh->JOGGLEmax < REALmax/2)
    minimize_(qh->min_vertex, -wwval_(Wnewvertexmax));
} /* makenewplanes */

/*---------------------------------

  qh_makenew_nonsimplicial(qh, visible, apex, numnew )
    make new facets for ridges of a visible facet

  returns:
    first newfacet, bumps numnew as needed
    attaches new facets if !qh.ONLYgood
    marks ridge neighbors for simplicial visible
    if (qh.ONLYgood)
      ridges on newfacet, horizon, and visible
    else
      ridge and neighbors between newfacet and   horizon
      visible facet's ridges are deleted

  notes:
    qh.visit_id if visible has already been processed
    sets neighbor->seen for building f.samecycle
      assumes all 'seen' flags initially false

  design:
    for each ridge of visible facet
      get neighbor of visible facet
      if neighbor was already processed
        delete the ridge (will delete all visible facets later)
      if neighbor is a horizon facet
        create a new facet
        if neighbor coplanar
          adds newfacet to f.samecycle for later merging
        else
          updates neighbor's neighbor set
          (checks for non-simplicial facet with multiple ridges to visible facet)
        updates neighbor's ridge set
        (checks for simplicial neighbor to non-simplicial visible facet)
        (deletes ridge if neighbor is simplicial)

*/
#ifndef qh_NOmerge
facetT *qh_makenew_nonsimplicial(qhT *qh, facetT *visible, vertexT *apex, int *numnew) {
  void **freelistp; /* used if !qh_NOmem by qh_memfree_() */
  ridgeT *ridge, **ridgep;
  facetT *neighbor, *newfacet= NULL, *samecycle;
  setT *vertices;
  boolT toporient;
  int ridgeid;

  FOREACHridge_(visible->ridges) {
    ridgeid= ridge->id;
    neighbor= otherfacet_(ridge, visible);
    if (neighbor->visible) {
      if (!qh->ONLYgood) {
        if (neighbor->visitid == qh->visit_id) {
          qh_setfree(qh, &(ridge->vertices));  /* delete on 2nd visit */
          qh_memfree_(qh, ridge, (int)sizeof(ridgeT), freelistp);
        }
      }
    }else {  /* neighbor is an horizon facet */
      toporient= (ridge->top == visible);
      vertices= qh_setnew(qh, qh->hull_dim); /* makes sure this is quick */
      qh_setappend(qh, &vertices, apex);
      qh_setappend_set(qh, &vertices, ridge->vertices);
      newfacet= qh_makenewfacet(qh, vertices, toporient, neighbor);
      (*numnew)++;
      if (neighbor->coplanar) {
        newfacet->mergehorizon= True;
        if (!neighbor->seen) {
          newfacet->f.samecycle= newfacet;
          neighbor->f.newcycle= newfacet;
        }else {
          samecycle= neighbor->f.newcycle;
          newfacet->f.samecycle= samecycle->f.samecycle;
          samecycle->f.samecycle= newfacet;
        }
      }
      if (qh->ONLYgood) {
        if (!neighbor->simplicial)
          qh_setappend(qh, &(newfacet->ridges), ridge);
      }else {  /* qh_attachnewfacets */
        if (neighbor->seen) {
          if (neighbor->simplicial) {
            qh_fprintf(qh, qh->ferr, 6105, "qhull internal error (qh_makenew_nonsimplicial): simplicial f%d sharing two ridges with f%d\n",
                   neighbor->id, visible->id);
            qh_errexit2(qh, qh_ERRqhull, neighbor, visible);
          }
          qh_setappend(qh, &(neighbor->neighbors), newfacet);
        }else
          qh_setreplace(qh, neighbor->neighbors, visible, newfacet);
        if (neighbor->simplicial) {
          qh_setdel(neighbor->ridges, ridge);
          qh_setfree(qh, &(ridge->vertices));
          qh_memfree(qh, ridge, (int)sizeof(ridgeT));
        }else {
          qh_setappend(qh, &(newfacet->ridges), ridge);
          if (toporient)
            ridge->top= newfacet;
          else
            ridge->bottom= newfacet;
        }
      trace4((qh, qh->ferr, 4048, "qh_makenew_nonsimplicial: created facet f%d from v%d and r%d of horizon f%d\n",
            newfacet->id, apex->id, ridgeid, neighbor->id));
      }
    }
    neighbor->seen= True;
  } /* for each ridge */
  if (!qh->ONLYgood)
    SETfirst_(visible->ridges)= NULL;
  return newfacet;
} /* makenew_nonsimplicial */
#else /* qh_NOmerge */
facetT *qh_makenew_nonsimplicial(qhT *qh, facetT *visible, vertexT *apex, int *numnew) {
  return NULL;
}
#endif /* qh_NOmerge */

/*---------------------------------

  qh_makenew_simplicial(qh, visible, apex, numnew )
    make new facets for simplicial visible facet and apex

  returns:
    attaches new facets if (!qh.ONLYgood)
      neighbors between newfacet and horizon

  notes:
    nop if neighbor->seen or neighbor->visible(see qh_makenew_nonsimplicial)

  design:
    locate neighboring horizon facet for visible facet
    determine vertices and orientation
    create new facet
    if coplanar,
      add new facet to f.samecycle
    update horizon facet's neighbor list
*/
facetT *qh_makenew_simplicial(qhT *qh, facetT *visible, vertexT *apex, int *numnew) {
  facetT *neighbor, **neighborp, *newfacet= NULL;
  setT *vertices;
  boolT flip, toporient;
  int horizonskip= 0, visibleskip= 0;

  FOREACHneighbor_(visible) {
    if (!neighbor->seen && !neighbor->visible) {
      vertices= qh_facetintersect(qh, neighbor,visible, &horizonskip, &visibleskip, 1);
      SETfirst_(vertices)= apex;
      flip= ((horizonskip & 0x1) ^ (visibleskip & 0x1));
      if (neighbor->toporient)
        toporient= horizonskip & 0x1;
      else
        toporient= (horizonskip & 0x1) ^ 0x1;
      newfacet= qh_makenewfacet(qh, vertices, toporient, neighbor);
      (*numnew)++;
      if (neighbor->coplanar && (qh->PREmerge || qh->MERGEexact)) {
#ifndef qh_NOmerge
        newfacet->f.samecycle= newfacet;
        newfacet->mergehorizon= True;
#endif
      }
      if (!qh->ONLYgood)
        SETelem_(neighbor->neighbors, horizonskip)= newfacet;
      trace4((qh, qh->ferr, 4049, "qh_makenew_simplicial: create facet f%d top %d from v%d and horizon f%d skip %d top %d and visible f%d skip %d, flip? %d\n",
            newfacet->id, toporient, apex->id, neighbor->id, horizonskip,
              neighbor->toporient, visible->id, visibleskip, flip));
    }
  }
  return newfacet;
} /* makenew_simplicial */

/*---------------------------------

  qh_matchneighbor(qh, newfacet, newskip, hashsize, hashcount )
    either match subridge of newfacet with neighbor or add to hash_table

  returns:
    duplicate ridges are unmatched and marked by qh_DUPLICATEridge

  notes:
    ridge is newfacet->vertices w/o newskip vertex
    do not allocate memory (need to free hash_table cleanly)
    uses linear hash chains

  see also:
    qh_matchduplicates

  design:
    for each possible matching facet in qh.hash_table
      if vertices match
        set ismatch, if facets have opposite orientation
        if ismatch and matching facet doesn't have a match
          match the facets by updating their neighbor sets
        else
          indicate a duplicate ridge
          set facet hyperplane for later testing
          add facet to hashtable
          unless the other facet was already a duplicate ridge
            mark both facets with a duplicate ridge
            add other facet (if defined) to hash table
*/
void qh_matchneighbor(qhT *qh, facetT *newfacet, int newskip, int hashsize, int *hashcount) {
  boolT newfound= False;   /* True, if new facet is already in hash chain */
  boolT same, ismatch;
  int hash, scan;
  facetT *facet, *matchfacet;
  int skip, matchskip;

  hash= qh_gethash(qh, hashsize, newfacet->vertices, qh->hull_dim, 1,
                     SETelem_(newfacet->vertices, newskip));
  trace4((qh, qh->ferr, 4050, "qh_matchneighbor: newfacet f%d skip %d hash %d hashcount %d\n",
          newfacet->id, newskip, hash, *hashcount));
  zinc_(Zhashlookup);
  for (scan= hash; (facet= SETelemt_(qh->hash_table, scan, facetT));
       scan= (++scan >= hashsize ? 0 : scan)) {
    if (facet == newfacet) {
      newfound= True;
      continue;
    }
    zinc_(Zhashtests);
    if (qh_matchvertices(qh, 1, newfacet->vertices, newskip, facet->vertices, &skip, &same)) {
      if (SETelem_(newfacet->vertices, newskip) ==
          SETelem_(facet->vertices, skip)) {
        qh_precision(qh, "two facets with the same vertices");
        qh_fprintf(qh, qh->ferr, 6106, "qhull precision error: Vertex sets are the same for f%d and f%d.  Can not force output.\n",
          facet->id, newfacet->id);
        qh_errexit2(qh, qh_ERRprec, facet, newfacet);
      }
      ismatch= (same == (boolT)((newfacet->toporient ^ facet->toporient)));
      matchfacet= SETelemt_(facet->neighbors, skip, facetT);
      if (ismatch && !matchfacet) {
        SETelem_(facet->neighbors, skip)= newfacet;
        SETelem_(newfacet->neighbors, newskip)= facet;
        (*hashcount)--;
        trace4((qh, qh->ferr, 4051, "qh_matchneighbor: f%d skip %d matched with new f%d skip %d\n",
           facet->id, skip, newfacet->id, newskip));
        return;
      }
      if (!qh->PREmerge && !qh->MERGEexact) {
        qh_precision(qh, "a ridge with more than two neighbors");
        qh_fprintf(qh, qh->ferr, 6107, "qhull precision error: facets f%d, f%d and f%d meet at a ridge with more than 2 neighbors.  Can not continue.\n",
                 facet->id, newfacet->id, getid_(matchfacet));
        qh_errexit2(qh, qh_ERRprec, facet, newfacet);
      }
      SETelem_(newfacet->neighbors, newskip)= qh_DUPLICATEridge;
      newfacet->dupridge= True;
      if (!newfacet->normal)
        qh_setfacetplane(qh, newfacet);
      qh_addhash(newfacet, qh->hash_table, hashsize, hash);
      (*hashcount)++;
      if (!facet->normal)
        qh_setfacetplane(qh, facet);
      if (matchfacet != qh_DUPLICATEridge) {
        SETelem_(facet->neighbors, skip)= qh_DUPLICATEridge;
        facet->dupridge= True;
        if (!facet->normal)
          qh_setfacetplane(qh, facet);
        if (matchfacet) {
          matchskip= qh_setindex(matchfacet->neighbors, facet);
          if (matchskip<0) {
              qh_fprintf(qh, qh->ferr, 6260, "qhull internal error (qh_matchneighbor): matchfacet f%d is in f%d neighbors but not vice versa.  Can not continue.\n",
                  matchfacet->id, facet->id);
              qh_errexit2(qh, qh_ERRqhull, matchfacet, facet);
          }
          SETelem_(matchfacet->neighbors, matchskip)= qh_DUPLICATEridge; /* matchskip>=0 by QH6260 */
          matchfacet->dupridge= True;
          if (!matchfacet->normal)
            qh_setfacetplane(qh, matchfacet);
          qh_addhash(matchfacet, qh->hash_table, hashsize, hash);
          *hashcount += 2;
        }
      }
      trace4((qh, qh->ferr, 4052, "qh_matchneighbor: new f%d skip %d duplicates ridge for f%d skip %d matching f%d ismatch %d at hash %d\n",
           newfacet->id, newskip, facet->id, skip,
           (matchfacet == qh_DUPLICATEridge ? -2 : getid_(matchfacet)),
           ismatch, hash));
      return; /* end of duplicate ridge */
    }
  }
  if (!newfound)
    SETelem_(qh->hash_table, scan)= newfacet;  /* same as qh_addhash */
  (*hashcount)++;
  trace4((qh, qh->ferr, 4053, "qh_matchneighbor: no match for f%d skip %d at hash %d\n",
           newfacet->id, newskip, hash));
} /* matchneighbor */

/*---------------------------------

  qh_matchnewfacets()
    match newfacets in qh.newfacet_list to their newfacet neighbors

  returns:
    qh.newfacet_list with full neighbor sets
      get vertices with nth neighbor by deleting nth vertex
    if qh.PREmerge/MERGEexact or qh.FORCEoutput
      sets facet->flippped if flipped normal (also prevents point partitioning)
    if duplicate ridges and qh.PREmerge/MERGEexact
      sets facet->dupridge
      missing neighbor links identifies extra ridges to be merging (qh_MERGEridge)

  notes:
    newfacets already have neighbor[0] (horizon facet)
    assumes qh.hash_table is NULL
    vertex->neighbors has not been updated yet
    do not allocate memory after qh.hash_table (need to free it cleanly)

  design:
    delete neighbor sets for all new facets
    initialize a hash table
    for all new facets
      match facet with neighbors
    if unmatched facets (due to duplicate ridges)
      for each new facet with a duplicate ridge
        match it with a facet
    check for flipped facets
*/
void qh_matchnewfacets(qhT *qh /* qh.newfacet_list */) {
  int numnew=0, hashcount=0, newskip;
  facetT *newfacet, *neighbor;
  int dim= qh->hull_dim, hashsize, neighbor_i, neighbor_n;
  setT *neighbors;
#ifndef qh_NOtrace
  int facet_i, facet_n, numfree= 0;
  facetT *facet;
#endif

  trace1((qh, qh->ferr, 1019, "qh_matchnewfacets: match neighbors for new facets.\n"));
  FORALLnew_facets {
    numnew++;
    {  /* inline qh_setzero(qh, newfacet->neighbors, 1, qh->hull_dim); */
      neighbors= newfacet->neighbors;
      neighbors->e[neighbors->maxsize].i= dim+1; /*may be overwritten*/
      memset((char *)SETelemaddr_(neighbors, 1, void), 0, dim * SETelemsize);
    }
  }

  qh_newhashtable(qh, numnew*(qh->hull_dim-1)); /* twice what is normally needed,
                                     but every ridge could be DUPLICATEridge */
  hashsize= qh_setsize(qh, qh->hash_table);
  FORALLnew_facets {
    for (newskip=1; newskip<qh->hull_dim; newskip++) /* furthest/horizon already matched */
      /* hashsize>0 because hull_dim>1 and numnew>0 */
      qh_matchneighbor(qh, newfacet, newskip, hashsize, &hashcount);
#if 0   /* use the following to trap hashcount errors */
    {
      int count= 0, k;
      facetT *facet, *neighbor;

      count= 0;
      FORALLfacet_(qh->newfacet_list) {  /* newfacet already in use */
        for (k=1; k < qh->hull_dim; k++) {
          neighbor= SETelemt_(facet->neighbors, k, facetT);
          if (!neighbor || neighbor == qh_DUPLICATEridge)
            count++;
        }
        if (facet == newfacet)
          break;
      }
      if (count != hashcount) {
        qh_fprintf(qh, qh->ferr, 8088, "qh_matchnewfacets: after adding facet %d, hashcount %d != count %d\n",
                 newfacet->id, hashcount, count);
        qh_errexit(qh, qh_ERRqhull, newfacet, NULL);
      }
    }
#endif  /* end of trap code */
  }
  if (hashcount) {
    FORALLnew_facets {
      if (newfacet->dupridge) {
        FOREACHneighbor_i_(qh, newfacet) {
          if (neighbor == qh_DUPLICATEridge) {
            qh_matchduplicates(qh, newfacet, neighbor_i, hashsize, &hashcount);
                    /* this may report MERGEfacet */
          }
        }
      }
    }
  }
  if (hashcount) {
    qh_fprintf(qh, qh->ferr, 6108, "qhull internal error (qh_matchnewfacets): %d neighbors did not match up\n",
        hashcount);
    qh_printhashtable(qh, qh->ferr);
    qh_errexit(qh, qh_ERRqhull, NULL, NULL);
  }
#ifndef qh_NOtrace
  if (qh->IStracing >= 2) {
    FOREACHfacet_i_(qh, qh->hash_table) {
      if (!facet)
        numfree++;
    }
    qh_fprintf(qh, qh->ferr, 8089, "qh_matchnewfacets: %d new facets, %d unused hash entries .  hashsize %d\n",
             numnew, numfree, qh_setsize(qh, qh->hash_table));
  }
#endif /* !qh_NOtrace */
  qh_setfree(qh, &qh->hash_table);
  if (qh->PREmerge || qh->MERGEexact) {
    if (qh->IStracing >= 4)
      qh_printfacetlist(qh, qh->newfacet_list, NULL, qh_ALL);
    FORALLnew_facets {
      if (newfacet->normal)
        qh_checkflipped(qh, newfacet, NULL, qh_ALL);
    }
  }else if (qh->FORCEoutput)
    qh_checkflipped_all(qh, qh->newfacet_list);  /* prints warnings for flipped */
} /* matchnewfacets */

/*---------------------------------

  qh_matchvertices(qh, firstindex, verticesA, skipA, verticesB, skipB, same )
    tests whether vertices match with a single skip
    starts match at firstindex since all new facets have a common vertex

  returns:
    true if matched vertices
    skip index for each set
    sets same iff vertices have the same orientation

  notes:
    assumes skipA is in A and both sets are the same size

  design:
    set up pointers
    scan both sets checking for a match
    test orientation
*/
boolT qh_matchvertices(qhT *qh, int firstindex, setT *verticesA, int skipA,
       setT *verticesB, int *skipB, boolT *same) {
  vertexT **elemAp, **elemBp, **skipBp=NULL, **skipAp;

  elemAp= SETelemaddr_(verticesA, firstindex, vertexT);
  elemBp= SETelemaddr_(verticesB, firstindex, vertexT);
  skipAp= SETelemaddr_(verticesA, skipA, vertexT);
  do if (elemAp != skipAp) {
    while (*elemAp != *elemBp++) {
      if (skipBp)
        return False;
      skipBp= elemBp;  /* one extra like FOREACH */
    }
  }while (*(++elemAp));
  if (!skipBp)
    skipBp= ++elemBp;
  *skipB= SETindex_(verticesB, skipB); /* i.e., skipBp - verticesB */
  *same= !((skipA & 0x1) ^ (*skipB & 0x1)); /* result is 0 or 1 */
  trace4((qh, qh->ferr, 4054, "qh_matchvertices: matched by skip %d(v%d) and skip %d(v%d) same? %d\n",
          skipA, (*skipAp)->id, *skipB, (*(skipBp-1))->id, *same));
  return(True);
} /* matchvertices */

/*---------------------------------

  qh_newfacet(qh)
    return a new facet

  returns:
    all fields initialized or cleared   (NULL)
    preallocates neighbors set
*/
facetT *qh_newfacet(qhT *qh) {
  facetT *facet;
  void **freelistp; /* used if !qh_NOmem by qh_memalloc_() */

  qh_memalloc_(qh, (int)sizeof(facetT), freelistp, facet, facetT);
  memset((char *)facet, (size_t)0, sizeof(facetT));
  if (qh->facet_id == qh->tracefacet_id)
    qh->tracefacet= facet;
  facet->id= qh->facet_id++;
  facet->neighbors= qh_setnew(qh, qh->hull_dim);
#if !qh_COMPUTEfurthest
  facet->furthestdist= 0.0;
#endif
#if qh_MAXoutside
  if (qh->FORCEoutput && qh->APPROXhull)
    facet->maxoutside= qh->MINoutside;
  else
    facet->maxoutside= qh->DISTround;
#endif
  facet->simplicial= True;
  facet->good= True;
  facet->newfacet= True;
  trace4((qh, qh->ferr, 4055, "qh_newfacet: created facet f%d\n", facet->id));
  return(facet);
} /* newfacet */

/*---------------------------------

  qh_newridge()
    return a new ridge
*/
ridgeT *qh_newridge(qhT *qh) {
  ridgeT *ridge;
  void **freelistp;   /* used if !qh_NOmem by qh_memalloc_() */

  qh_memalloc_(qh, (int)sizeof(ridgeT), freelistp, ridge, ridgeT);
  memset((char *)ridge, (size_t)0, sizeof(ridgeT));
  zinc_(Ztotridges);
  if (qh->ridge_id == UINT_MAX) {
    qh_fprintf(qh, qh->ferr, 7074, "\
qhull warning: more than 2^32 ridges.  Qhull results are OK.  Since the ridge ID wraps around to 0, two ridges may have the same identifier.\n");
  }
  ridge->id= qh->ridge_id++;
  trace4((qh, qh->ferr, 4056, "qh_newridge: created ridge r%d\n", ridge->id));
  return(ridge);
} /* newridge */

/*---------------------------------

  qh_pointid(qh, point )
    return id for a point,
    returns qh_IDnone(-3) if null, qh_IDinterior(-2) if interior, or qh_IDunknown(-1) if not known

  alternative code if point is in qh.first_point...
    unsigned long id;
    id= ((unsigned long)point - (unsigned long)qh.first_point)/qh.normal_size;

  notes:
    Valid points are non-negative
    WARN64 -- id truncated to 32-bits, at most 2G points
    NOerrors returned (QhullPoint::id)
    if point not in point array
      the code does a comparison of unrelated pointers.
*/
int qh_pointid(qhT *qh, pointT *point) {
  ptr_intT offset, id;

  if (!point || !qh)
    return qh_IDnone;
  else if (point == qh->interior_point)
    return qh_IDinterior;
  else if (point >= qh->first_point
  && point < qh->first_point + qh->num_points * qh->hull_dim) {
    offset= (ptr_intT)(point - qh->first_point);
    id= offset / qh->hull_dim;
  }else if ((id= qh_setindex(qh->other_points, point)) != -1)
    id += qh->num_points;
  else
    return qh_IDunknown;
  return (int)id;
} /* pointid */

/*---------------------------------

  qh_removefacet(qh, facet )
    unlinks facet from qh.facet_list,

  returns:
    updates qh.facet_list .newfacet_list .facet_next visible_list
    decrements qh.num_facets

  see:
    qh_appendfacet
*/
void qh_removefacet(qhT *qh, facetT *facet) {
  facetT *next= facet->next, *previous= facet->previous;

  if (facet == qh->newfacet_list)
    qh->newfacet_list= next;
  if (facet == qh->facet_next)
    qh->facet_next= next;
  if (facet == qh->visible_list)
    qh->visible_list= next;
  if (previous) {
    previous->next= next;
    next->previous= previous;
  }else {  /* 1st facet in qh->facet_list */
    qh->facet_list= next;
    qh->facet_list->previous= NULL;
  }
  qh->num_facets--;
  trace4((qh, qh->ferr, 4057, "qh_removefacet: remove f%d from facet_list\n", facet->id));
} /* removefacet */

/*---------------------------------

  qh_removevertex(qh, vertex )
    unlinks vertex from qh.vertex_list,

  returns:
    updates qh.vertex_list .newvertex_list
    decrements qh.num_vertices
*/
void qh_removevertex(qhT *qh, vertexT *vertex) {
  vertexT *next= vertex->next, *previous= vertex->previous;

  if (vertex == qh->newvertex_list)
    qh->newvertex_list= next;
  if (previous) {
    previous->next= next;
    next->previous= previous;
  }else {  /* 1st vertex in qh->vertex_list */
    qh->vertex_list= vertex->next;
    qh->vertex_list->previous= NULL;
  }
  qh->num_vertices--;
  trace4((qh, qh->ferr, 4058, "qh_removevertex: remove v%d from vertex_list\n", vertex->id));
} /* removevertex */

/*---------------------------------

  qh_updatevertices()
    update vertex neighbors and delete interior vertices

  returns:
    if qh.VERTEXneighbors, updates neighbors for each vertex
      if qh.newvertex_list,
         removes visible neighbors  from vertex neighbors
      if qh.newfacet_list
         adds new facets to vertex neighbors
    if qh.visible_list
       interior vertices added to qh.del_vertices for later partitioning

  design:
    if qh.VERTEXneighbors
      deletes references to visible facets from vertex neighbors
      appends new facets to the neighbor list for each vertex
      checks all vertices of visible facets
        removes visible facets from neighbor lists
        marks unused vertices for deletion
*/
void qh_updatevertices(qhT *qh /*qh.newvertex_list, newfacet_list, visible_list*/) {
  facetT *newfacet= NULL, *neighbor, **neighborp, *visible;
  vertexT *vertex, **vertexp;

  trace3((qh, qh->ferr, 3013, "qh_updatevertices: delete interior vertices and update vertex->neighbors\n"));
  if (qh->VERTEXneighbors) {
    FORALLvertex_(qh->newvertex_list) {
      FOREACHneighbor_(vertex) {
        if (neighbor->visible)
          SETref_(neighbor)= NULL;
      }
      qh_setcompact(qh, vertex->neighbors);
    }
    FORALLnew_facets {
      FOREACHvertex_(newfacet->vertices)
        qh_setappend(qh, &vertex->neighbors, newfacet);
    }
    FORALLvisible_facets {
      FOREACHvertex_(visible->vertices) {
        if (!vertex->newlist && !vertex->deleted) {
          FOREACHneighbor_(vertex) { /* this can happen under merging */
            if (!neighbor->visible)
              break;
          }
          if (neighbor)
            qh_setdel(vertex->neighbors, visible);
          else {
            vertex->deleted= True;
            qh_setappend(qh, &qh->del_vertices, vertex);
            trace2((qh, qh->ferr, 2041, "qh_updatevertices: delete vertex p%d(v%d) in f%d\n",
                  qh_pointid(qh, vertex->point), vertex->id, visible->id));
          }
        }
      }
    }
  }else {  /* !VERTEXneighbors */
    FORALLvisible_facets {
      FOREACHvertex_(visible->vertices) {
        if (!vertex->newlist && !vertex->deleted) {
          vertex->deleted= True;
          qh_setappend(qh, &qh->del_vertices, vertex);
          trace2((qh, qh->ferr, 2042, "qh_updatevertices: delete vertex p%d(v%d) in f%d\n",
                  qh_pointid(qh, vertex->point), vertex->id, visible->id));
        }
      }
    }
  }
} /* updatevertices */


text:
export function removeClass (node:HTMLElement, className:string) {
	node.className = node.className.replace(_classNameRegexp(className), function (everything, leftDelimiter, name, rightDelimiter) {
		return leftDelimiter.length + rightDelimiter.length === 2 ? ' ' : '';
	});
}

//// [parserArgumentList1.js]
"use strict";
exports.__esModule = true;
function removeClass(node, className) {
    node.className = node.className.replace(_classNameRegexp(className), function (everything, leftDelimiter, name, rightDelimiter) {
        return leftDelimiter.length + rightDelimiter.length === 2 ? ' ' : '';
    });
}
exports.removeClass = removeClass;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;

namespace SAssemblies.Miscs
{
    class AntiNexusTurret
    {
        public static Menu.MenuItemSettings AntiNexusTurretMisc = new Menu.MenuItemSettings(typeof(AntiNexusTurret));

        public AntiNexusTurret()
        {
            Obj_AI_Base.OnNewPath += Obj_AI_Hero_OnNewPath;
            Game.OnUpdate += Game_OnGameUpdate;
            //ThreadHelper.GetInstance().Called += Game_OnGameUpdate;
        }

        ~AntiNexusTurret()
        {
            Obj_AI_Base.OnNewPath -= Obj_AI_Hero_OnNewPath;
            Game.OnUpdate -= Game_OnGameUpdate;
            //ThreadHelper.GetInstance().Called -= Game_OnGameUpdate;
        }

        public bool IsActive()
        {
#if MISCS
            return Misc.Miscs.GetActive() && AntiNexusTurretMisc.GetActive();
#else
            return AntiNexusTurretMisc.GetActive();
#endif
        }

        public static Menu.MenuItemSettings SetupMenu(LeagueSharp.Common.Menu menu)
        {
            AntiNexusTurretMisc.Menu = menu.AddSubMenu(new LeagueSharp.Common.Menu(Language.GetString("MISCS_ANTINEXUSTURRET_MAIN"), "SAssembliesMiscsAntiNexusTurret"));
            AntiNexusTurretMisc.MenuItems.Add(AntiNexusTurretMisc.CreateActiveMenuItem("SAssembliesMiscsAntiNexusTurretActive", () => new AntiNexusTurret()));
            return AntiNexusTurretMisc;
        }

        void Game_OnGameUpdate(EventArgs args)
        {
            if (!IsActive())
                return;

            Obj_AI_Turret baseTurret = ObjectManager.Get<Obj_AI_Turret>().Find(turret => IsBaseTurret(turret, 1410, true, ObjectManager.Player.ServerPosition));
            if (baseTurret != null)
            {
                Obj_AI_Turret baseAllyTurret = ObjectManager.Get<Obj_AI_Turret>().Find(turret => IsBaseTurret(turret, 999999999, false, ObjectManager.Player.ServerPosition));
                Vector3 newPos = baseTurret.ServerPosition.Extend(baseAllyTurret.ServerPosition, 1425);
                ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, newPos);
            }
        }

        void Obj_AI_Hero_OnNewPath(Obj_AI_Base sender, GameObjectNewPathEventArgs args)
        {
            if(!IsActive() || !sender.IsMe)
                return;

            for (int i = 0; i < args.Path.Length; i++)
            {
                var point = args.Path[i];
                Obj_AI_Turret baseTurret = ObjectManager.Get<Obj_AI_Turret>().Find(turret => IsBaseTurret(turret, 1425, true, point));
                if (baseTurret != null)
                {
                    float dist =
                        args.Path[i - 1].Distance(
                            baseTurret.ServerPosition) - 1425f - 20f;
                    Vector3 newPos = args.Path[i - 1].Extend(point, dist);
                    ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, newPos);
                }
            }
        }

        public static bool IsBaseTurret(Obj_AI_Turret unit,
            float range,
            bool enemyTeam,
            Vector3 from)
        {
            if (unit == null || !unit.IsValid)
            {
                return false;
            }

            if (enemyTeam && unit.Team == ObjectManager.Player.Team)
            {
                return false;
            }
            else if (!enemyTeam && unit.Team != ObjectManager.Player.Team)
            {
                return false;
            }

            if (!unit.Name.Contains("TurretShrine_A"))
            {
                return false;
            }

            var @base = unit as Obj_AI_Base;
            var unitPosition = @base != null ? @base.ServerPosition : unit.Position;

            return !(range < float.MaxValue) ||
                   !(Vector2.DistanceSquared(
                       (@from.To2D().IsValid() ? @from : ObjectManager.Player.ServerPosition).To2D(),
                       unitPosition.To2D()) > range * range);
        }
    }
}


text:
BPSNCPD3 ;BHAM ISC/LJE - Continuation of BPSNCPDP - DUR HANDLING ;06/16/2004
 ;;1.0;E CLAIMS MGMT ENGINE;**1,5,6,7,8,10**;JUN 2004;Build 27
 ;;Per VHA Directive 2004-038, this routine should not be modified.
 ;
 ; Due to space considerations, these comments were moved from BPSNPCPD
 ;   to this routine.
 ;
 ; ------------------ Beginning of BPSNCPDP comments ------------------
 ;Input
 ; BRXIEN = Prescription IEN
 ; BFILL = Fill Number
 ; BFILLDAT = Fill Date of current prescription and fill number
 ; BWHERE (RX Action)
 ;    ARES = Resubmit for an auto-reversed claim was released while waiting
 ;           for the payer response
 ;    AREV = Auto-Reversal
 ;    BB   = Back Billing
 ;    CRLB = CMOP Release & Rebill
 ;    CRLR = CMOP Release & Reverse (successful release)
 ;    CRLX = CMOP unsuccessful release & reverse
 ;    DC   = Discontinue - only reverse un-released PAYABLE DC's, release date check
 ;           should be in calling routine.
 ;    DDED = Delete in edit
 ;    DE   = Delete
 ;    ED   = Edit
 ;    ERES = Resubmit from ECME user screen
 ;    EREV = Reversal from ECME user screen
 ;    HLD  = Put prescription on Hold
 ;    OF   = Original Fill
 ;    PC   = Pull CMOPs
 ;    PE   = Pull early from suspense
 ;    PL   = Pull local from suspense
 ;    PP   = PP from Patient Prescription Processing option
 ;    RF   = Refill
 ;    RL   = Release Rx NDC check - Rebill if billed NDC doesn't match release NDC
 ;    RN   = Renew
 ;    RRL  = Original claim rejected, submit another claim, no reversal
 ;    RS   = Return-to-Stock
 ; BILLNDC = Valid NDC# with format 5-4-2
 ; REVREAS = Reversal Reason
 ; DURREC  = String of DUR info - Three "^" pieces
 ;                Professional Service Code
 ;                Reason for Service Code
 ;                Result of Service Code
 ; BPOVRIEN = Pointer to BPS NCPDP OVERIDE file.  This parameter will
 ;            only be passed if there are overrides entered by the
 ;            user via the Resubmit with Edits (RED) option in the
 ;            user screen.
 ; BPSAUTH  = pre-authorization code (preauth. code^preauth number)
 ; BPSCLARF = Submission Clarification Code (external value from #9002313.25), entered by
 ;            pharmacist and passed by Outpatient Pharmacy to ECME to put into the claim
 ; BPCOBIND = (optional, default is Primary) for COB indicators - so when the API is called for the particular
 ;            COB claim the BPSNCPDP can handle it.
 ; BPJOBFLG = (optional, default is "F") B - if is called by unqueueing logic in background, F - by other (foreground) process,
 ; BPREQIEN = (optional) ien of BPS REQUEST file record, that needs to be unqueued
 ; BPSCLOSE = (optional) local array used with BWHERE="EREV" only, if the user had chosen to close the claim after reversal
 ;   if claim needs to be closed then
 ;   BPSCLOSE("CLOSE AFT REV")=1
 ;   BPSCLOSE("CLOSE AFT REV REASON")=<#356.8 ien>
 ;   BPSCLOSE("CLOSE AFT REV COMMENT")=<some text>
 ; BPSPLAN  = (optional) IEN of the entry in the GROUP INSURANCE PLAN file (#355.3)
 ; BPSPRDAT = (optional) local array passed by reference. Contains primary claim data needed to submit a secondary claim.
 ;            Format:  BPSPRDAT(NCPDP field)
 ; BPSRTYPE = (optional) rate type ( ien of the file #399.3)
 ; BPSDELAY = Delay Reason Code (IEN of BPS NCPDP DELAY REASON CODE (#9002313.29), entered by the user
 ;            in the Back Billing option of Claims Tracking and passed to ECME to put into the claim.
 ;
 ;Output (RESPONSE^MESSAGE^ELIGIBILITY^CLAIMSTATUS^COB^RXCOB^INSURANCE)
 ; RESPONSE
 ;    0  Submitted through ECME
 ;    1  No submission through ECME
 ;    2  IB not billable
 ;    3  Claim was closed, not submitted (RTS/Deletes)
 ;    4  Unable to queue claim
 ;    5  Incorrect information supplied to ECME
 ;    6  Inactive ECME - Primarily used for Tricare to say ok to process rx
 ;    10 Reversal but no resubmit
 ; MESSAGE = Message associated with the response (error/submitted)
 ; ELIGIBILITY = V - VA, T - Tricare
 ; CLAIMSTATUS = claim status (null or IN PROGRESS/E PAYABLE/etc...)
 ; COB  = Coordination Of Benefit indicator of the insurance as it is stored in the PATIENT file: 1- primary, 2 -secondary, 3 -tertiary
 ; RXCOB =  the payer sequence indicator of the claim which was sent to the payer as a result of this call: 1- primary, 2 -secondary)
 ; INSURANCE = Name of the insurance company that was billed as a result of this call
 ;
 ; ----------------- End of BPSNCPDP comments ----------------------
 ;
 ; ----------------- DUR1 ------------------------------------------
 ; DUR1 is called by PSO to get the reject information
 ;
 ;
 ; IA 4560 supports OP's use of this procedure
 ;
 ; Function call for DUR INFORMATION
 ; Parameters: BRXIEN = Prescription IEN
 ;             BFILL = fill number
 ;             DUR = DUR info passed back
 ;             ERROR = error passed back
 ;             BPRXCOB = payer sequence
 ; Note:
 ;    DUR("BILLED")=0 if ecme off for pharmacy or no transaction in ECME
 ;    DUR(<Insurance counter>,"BILLED")=1 if billed through ecme
DUR1(BRXIEN,BFILL,DUR,ERROR,BPRXCOB) ;
 N SITE,IEN59,DUR1,DURIEN
 I '$G(BRXIEN) S DUR("BILLED")=0 Q
 I $G(BFILL)="" S DUR("BILLED")=0 Q
 S BPRXCOB=+$G(BPRXCOB)
 I BPRXCOB=0 S BPRXCOB=1 ;default is Primary
 ;
 ; Get Site info and check is ECME is turned on
 ; If not, set DUR("BILLED")=0 and quit
 I '$G(BFILL) S SITE=$$RXAPI1^BPSUTIL1(BRXIEN,20,"I")
 I $G(BFILL) S SITE=$$RXSUBF1^BPSUTIL1(BRXIEN,52,52.1,BFILL,8,"I")
 I '$$ECMEON^BPSUTIL(SITE) S DUR("BILLED")=0 Q
 ;
 ; Set up the Transaction IEN
 S IEN59=$$IEN59^BPSOSRX(BRXIEN,BFILL,BPRXCOB)
 I IEN59="" S DUR("BILLED")=0 Q
 ;
 ; If the transaction record does not exist, set DUR("BILLED")=0 and quit
 I '$D(^BPST(IEN59)) S DUR("BILLED")=0 Q
 ;
 S DUR(BPRXCOB,"BILLED")=1
 ;
 S DUR(BPRXCOB,"ELIGBLT")=$P($G(^BPST(IEN59,9)),U,4)
 ; Get Insurance Info and set into DUR array
 D GETS^DIQ(9002313.59902,"1,"_IEN59_",","902.05;902.06;902.24;902.25;902.26","E","DUR1","ERROR")
 S DUR(BPRXCOB,"INSURANCE NAME")=$G(DUR1(9002313.59902,"1,"_IEN59_",",902.24,"E"))  ; Insurance Company Name
 S DUR(BPRXCOB,"GROUP NUMBER")=$G(DUR1(9002313.59902,"1,"_IEN59_",",902.05,"E"))    ; Insurance Group Number
 S DUR(BPRXCOB,"GROUP NAME")=$G(DUR1(9002313.59902,"1,"_IEN59_",",902.25,"E"))      ; Insurance Group Name
 S DUR(BPRXCOB,"PLAN CONTACT")=$G(DUR1(9002313.59902,"1,"_IEN59_",",902.26,"E"))    ; Insurance Contact Number
 S DUR(BPRXCOB,"CARDHOLDER ID")=$G(DUR1(9002313.59902,"1,"_IEN59_",",902.06,"E"))   ; Cardholder ID
 ;
 ; Get Response IEN and Data
 S DURIEN="",DURIEN=$P(^BPST(IEN59,0),"^",5)
 D DURRESP(DURIEN,.DUR,BPRXCOB) ; Note: In the future, we may need to get/store DURIEN for each COB
 Q
 ;
DURRESP(DURIEN,DUR,BPRXCOB) ;
 I '$G(DURIEN) Q
 S BPRXCOB=+$G(BPRXCOB)
 I BPRXCOB=0 S BPRXCOB=1 ;default is Primary
 N ADDMESS,I,DUR1
 S DUR(BPRXCOB,"RESPONSE IEN")=DURIEN
 ;
 ; Get the Transmission specific data (Message)
 S DUR(BPRXCOB,"MESSAGE")=$$GET1^DIQ(9002313.03,DURIEN_",",504,"E")
 ;
 ; Get the Additional Message Information from the transaction
 D ADDMESS^BPSSCRLG(DURIEN,1,.ADDMESS)
 M DUR(BPRXCOB,"PAYER MESSAGE")=ADDMESS
 ;
 ; Get the other transaction level data
 D GETS^DIQ(9002313.0301,"1,"_DURIEN_",","501;567.01*","E","DUR1","ERROR")
 S DUR(BPRXCOB,"STATUS")=$G(DUR1(9002313.0301,"1,"_DURIEN_",",501,"E"))                  ;Status of Response
 ;
 ; The following four fields are redundant with the fields in the DUR PPS
 ;   multiple but are needed for backwards compatibility with the OP code
 S DUR(BPRXCOB,"REASON")=$G(DUR1(9002313.1101,"1,1,"_DURIEN_",",439,"E"))                ;Reason for Service Code
 S DUR(BPRXCOB,"PREV FILL DATE")=$G(DUR1(9002313.1101,"1,1,"_DURIEN_",",530,"E"))        ;Previous Date of Fill
 S DUR(BPRXCOB,"DUR FREE TEXT DESC")=$G(DUR1(9002313.1101,"1,1,"_DURIEN_",",544,"E"))    ;DUR Free Text Message from Payer
 S DUR(BPRXCOB,"DUR ADD MSG TEXT")=$G(DUR1(9002313.1101,"1,1,"_DURIEN_",",570,"E"))      ;DUR Additional Message Text from Payer
 ;
 ; Get DUR PPS RESPONSE multiple values
 S DUR(BPRXCOB,"DUR PPS RESPONSE")=""
 F I=1:1 Q:'$D(DUR1(9002313.1101,I_",1,"_DURIEN_",",.01))  D
 . S DUR(BPRXCOB,"DUR PPS RESPONSE")=I
 . S DUR(BPRXCOB,"DUR PPS",I,"DUR PPS RESPONSE")=DUR1(9002313.1101,I_",1,"_DURIEN_",",.01,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"REASON FOR SERVICE CODE")=DUR1(9002313.1101,I_",1,"_DURIEN_",",439,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"CLINICAL SIGNIFICANCE CODE")=DUR1(9002313.1101,I_",1,"_DURIEN_",",528,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"OTHER PHARMACY INDICATOR")=DUR1(9002313.1101,I_",1,"_DURIEN_",",529,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"PREVIOUS DATE OF FILL")=DUR1(9002313.1101,I_",1,"_DURIEN_",",530,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"QUANTITY OF PREVIOUS FILL")=DUR1(9002313.1101,I_",1,"_DURIEN_",",531,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"DATABASE INDICATOR")=DUR1(9002313.1101,I_",1,"_DURIEN_",",532,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"OTHER PRESCRIBER INDICATOR")=DUR1(9002313.1101,I_",1,"_DURIEN_",",533,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"DUR FREE TEXT MESSAGE")=DUR1(9002313.1101,I_",1,"_DURIEN_",",544,"E")
 . S DUR(BPRXCOB,"DUR PPS",I,"DUR ADDITIONAL TEXT")=DUR1(9002313.1101,I_",1,"_DURIEN_",",570,"E")
 ;
 ; Get DUR reject codes and description and store in DUR
 D GETS^DIQ(9002313.0301,"1,"_DURIEN_",","511*","I","DUR1","ERROR") ;get DUR codes and descriptions
 S DUR(BPRXCOB,"REJ CODE LST")=""
 F I=1:1 Q:'$D(DUR1(9002313.03511,I_",1,"_DURIEN_","))  D
 . S DUR(BPRXCOB,"REJ CODES",I,DUR1(9002313.03511,I_",1,"_DURIEN_",",.01,"I"))=$$GET1^DIQ(9002313.93,DUR1(9002313.03511,I_",1,"_DURIEN_",",.01,"I"),".02")
 . S DUR(BPRXCOB,"REJ CODE LST")=DUR(BPRXCOB,"REJ CODE LST")_","_DUR1(9002313.03511,I_",1,"_DURIEN_",",.01,"I")
 S DUR(BPRXCOB,"REJ CODE LST")=$E(DUR(BPRXCOB,"REJ CODE LST"),2,9999)
 Q
 ;


text:
package com.prunatic.domain.user;

public class UserCredentials {
    private String username;

    private UserCredentials(String username) {
        this.username = username;
    }

    public static UserCredentials fromUsername(String username) {
        return new UserCredentials(username);
    }

    public String username() {
        return username;
    }

    @Override
    public boolean equals(Object obj) {
        UserCredentials other = (UserCredentials) obj;
        return this.username.equals(other.username());
    }
}


text:
{% extends "base.html" %}
{% block body %}

          Enable SMS based Two-Factor Auth

      {% if 'sms_sent' in opts and opts['sms_sent'] %}

        <button type="button" class="close" data-dismiss="alert">×</button>
	An SMS has been sent to the phone number you entered.
	When you get the SMS,
	enter the code in the SMS where it says "Enter your verification code" below.

      {% elif 'sms_sent' in opts %}

        <button type="button" class="close" data-dismiss="alert">×</button>
	There was an error sending you a SMS.
	Please check that you entered your mobile phone number
	correctly and try again.

      {% endif %}
      {% if opts['token_error'] %}

        <button type="button" class="close" data-dismiss="alert">×</button>
	There was an error verifying your token. Please try again.

      {% endif %}
      {% if opts['user'].account['totp_enabled_via_sms'] %}

        <button type="button" class="close" data-dismiss="alert">×</button>
	You are set up for Two-Factor Authentication via Twilio SMS!

      {% else %}

        Enabling SMS based Two-Factor Authentication on your account is a two
        step process:

            Enter your mobile phone number below and press the "Submit" button:

            A 6-digit verification code will be sent to your mobile phone. When you
            receive that number, enter it below:

      <form method="POST">
        <formset>
          Your mobile phone number:
          <input type="text" name="phone_number" placeholder="(415) 555-1212"/>
          <button type="submit" class="btn">Send verification code</button>
	  Cancel
          Enter your verification code:
          <input type="text" name="token" placeholder="123456" />
          <button type="submit" class="btn">Submit and verify</button>
	  Cancel
        </formset>
        </form>
      {% endif %}

{% endblock %}


text:
<?php
/* @var $this yii\web\View */
/* @var $model common\models\Article */
/* @var $categories common\models\ArticleCategory[] */

$this->title = Yii::t('backend', 'Create {modelClass}', [
    'modelClass' => 'Article',
]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('backend', 'Articles'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="article-create">

    <?php echo $this->render('_form', [
        'model' => $model,
        'modelUk'=> $modelUk,
        'categories' => $categories,
        'categoriesUk' => $categoriesUk,

    ]) ?>

</div>


text:
import logging
import time
import shlex
import getpass
import re

from beeswaxd import BeeswaxService
from beeswaxd.BeeswaxService import QueryState
from datetime import datetime
try:
  # If Exec Summary is not implemented in Impala, this cannot be imported
  from ExecStats.ttypes import TExecStats
except ImportError:
  pass
from ImpalaService import ImpalaService
from tests.util.thrift_util import create_transport
from thrift.transport.TTransport import TTransportException
from thrift.protocol import TBinaryProtocol
from thrift.Thrift import TApplicationException

LOG = logging.getLogger('impala_beeswax')

# Custom exception wrapper.
# All exceptions coming from thrift/beeswax etc. go through this wrapper.
# __str__ preserves the exception type.
# TODO: Add the ability to print some of the stack.
class ImpalaBeeswaxException(Exception):
  __name__ = "ImpalaBeeswaxException"
  def __init__(self, message, inner_exception):
    self.__message = message
    self.inner_exception = inner_exception

  def __str__(self):
    return "%s:\n %s" % (self.__name__, self.__message)

class ImpalaBeeswaxResult(object):
  def __init__(self, **kwargs):
    self.query = kwargs.get('query', None)
    self.query_id = kwargs['query_id']
    self.success = kwargs.get('success', False)
    # Insert returns an int, convert into list to have a uniform data type.
    # TODO: We should revisit this if we have more datatypes to deal with.
    self.data = kwargs.get('data', None)
    if not isinstance(self.data, list):
      self.data = str(self.data)
      self.data = [self.data]
    self.log = None
    self.time_taken = kwargs.get('time_taken', 0)
    self.summary = kwargs.get('summary', str())
    self.schema = kwargs.get('schema', None)
    self.column_types = None
    self.column_labels = None
    if self.schema is not None:
      # Extract labels and types so there is a shared interface with HS2ResultSet.
      self.column_types = [fs.type.upper() for fs in self.schema.fieldSchemas]
      self.column_labels = [fs.name.upper() for fs in self.schema.fieldSchemas]
    self.runtime_profile = kwargs.get('runtime_profile', str())
    self.exec_summary = kwargs.get('exec_summary', None)

  def get_data(self):
    return self.__format_data()

  def __format_data(self):
    if self.data:
      return '\n'.join(self.data)
    return ''

  def __str__(self):
    message = ('Summary: %s\n'
               'Success: %s\n'
               'Took: %s(s)\n'
               'Data:\n%s\n'
               % (self.summary, self.success, self.time_taken,
                  self.__format_data())
              )
    return message

# Interface to beeswax. Responsible for executing queries, fetching results.
class ImpalaBeeswaxClient(object):
  # Regex applied to all tokens of a query to detect the query type.
  INSERT_REGEX = re.compile("^insert$", re.I)

  def __init__(self, impalad, use_kerberos=False, user=None, password=None,
               use_ssl=False):
    self.connected = False
    self.impalad = impalad
    self.imp_service = None
    self.transport = None
    self.use_kerberos = use_kerberos
    self.use_ssl = use_ssl
    self.user, self.password = user, password
    self.use_ldap = (self.user is not None)
    self.__query_options = {}
    self.query_states = QueryState._NAMES_TO_VALUES

  def __options_to_string_list(self):
    return ["%s=%s" % (k,v) for (k,v) in self.__query_options.iteritems()]

  def get_query_options(self):
    return self.__query_options

  def set_query_option(self, name, value):
    self.__query_options[name.upper()] = value

  def set_query_options(self, query_option_dict):
    if query_option_dict is None:
      raise ValueError, 'Cannot pass None value for query options'
    self.clear_query_options()
    for name, value in query_option_dict.iteritems():
      self.set_query_option(name, value)

  def get_query_option(self, name):
    return self.__query_options.get(name.upper())

  def clear_query_options(self):
    self.__query_options.clear()

  def connect(self):
    """Connect to impalad specified in intializing this object

    Raises an exception if the connection is unsuccesful.
    """
    try:
      self.impalad = self.impalad.split(':')
      self.transport = self.__get_transport()
      self.transport.open()
      protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
      self.imp_service = ImpalaService.Client(protocol)
      self.connected = True
    except Exception, e:
      raise ImpalaBeeswaxException(self.__build_error_message(e), e)

  def close_connection(self):
    """Close the transport if it's still open"""
    if self.transport:
      self.transport.close()
    self.connected = False

  def __get_transport(self):
    """Creates the proper transport type based environment (secure vs unsecure)"""
    trans_type = 'buffered'
    if self.use_kerberos:
      trans_type = 'kerberos'
    elif self.use_ldap:
      trans_type = 'plain_sasl'
    return create_transport(host=self.impalad[0], port=int(self.impalad[1]),
                            service='impala', transport_type=trans_type, user=self.user,
                            password=self.password, use_ssl=self.use_ssl)

  def execute(self, query_string, user=None):
    """Re-directs the query to its appropriate handler, returns ImpalaBeeswaxResult"""
    # Take care of leading/trailing whitespaces.
    query_string = query_string.strip()
    start = time.time()
    start_time = datetime.now()
    handle = self.__execute_query(query_string.strip(), user=user)
    if self.__get_query_type(query_string) == 'insert':
      # DML queries are finished by this point.
      time_taken = time.time() - start

      # fetch_results() will close the query after which there is no guarantee that
      # profile and log will be available so fetch them first.
      runtime_profile = self.get_runtime_profile(handle)
      exec_summary = self.get_exec_summary_and_parse(handle)
      log = self.get_log(handle.log_context)

      result = self.fetch_results(query_string, handle)
      result.time_taken, result.start_time, result.runtime_profile, result.log = \
          time_taken, start_time, runtime_profile, log
      result.exec_summary = exec_summary
    else:
      # For SELECT queries, execution might still be ongoing. fetch_results() will block
      # until the query is completed.
      result = self.fetch_results(query_string, handle)
      result.time_taken = time.time() - start
      result.start_time = start_time
      result.exec_summary = self.get_exec_summary_and_parse(handle)
      result.log = self.get_log(handle.log_context)
      result.runtime_profile = self.get_runtime_profile(handle)
      self.close_query(handle)
    return result

  def get_exec_summary(self, handle):
    return self.__do_rpc(lambda: self.imp_service.GetExecSummary(handle))

  def get_exec_summary_and_parse(self, handle):
    """Calls GetExecSummary() for the last query handle, parses it and returns a summary
    table. Returns None in case of an error or an empty result"""
    try:
      summary = self.get_exec_summary(handle)
    except ImpalaBeeswaxException:
      summary = None

    if summary is None or summary.nodes is None:
      return None
      # If exec summary is not implemented in Impala, this function returns, so we do not
      # get the function __build_summary_table which requires TExecStats to be imported.

    output = []
    self.__build_summary_table(summary, 0, False, 0, False, output)
    return output

  def __build_summary_table(self, summary, idx, is_fragment_root, indent_level,
      new_indent_level, output):
    """NOTE: This was taken from impala_shell.py. Changes made here must be made there as
    well. TODO: This method will be a placed in a library that is shared between
    impala_shell and this file. (IMPALA-5792)

    Direct translation of Coordinator::PrintExecSummary() to recursively build a list
    of rows of summary statistics, one per exec node

    summary: the TExecSummary object that contains all the summary data

    idx: the index of the node to print

    is_fragment_root: true if the node to print is the root of a fragment (and therefore
    feeds into an exchange)

    indent_level: the number of spaces to print before writing the node's label, to give
    the appearance of a tree. The 0th child of a node has the same indent_level as its
    parent. All other children have an indent_level of one greater than their parent.

    new_indent_level: If true, this indent level is different from the previous row's.

    output: the list of rows into which to append the rows produced for this node and its
    children.

    Returns the index of the next exec node in summary.exec_nodes that should be
    processed, used internally to this method only.
    """
    attrs = ["latency_ns", "cpu_time_ns", "cardinality", "memory_used"]

    # Initialise aggregate and maximum stats
    agg_stats, max_stats = TExecStats(), TExecStats()
    for attr in attrs:
      setattr(agg_stats, attr, 0)
      setattr(max_stats, attr, 0)

    row = {}
    node = summary.nodes[idx]
    # exec_stats may not be set even if the query is FINISHED if there are fragments that
    # are still executing or that were cancelled before sending a status report.
    if node.exec_stats is not None:
      for stats in node.exec_stats:
        for attr in attrs:
          val = getattr(stats, attr)
          if val is not None:
            setattr(agg_stats, attr, getattr(agg_stats, attr) + val)
            setattr(max_stats, attr, max(getattr(max_stats, attr), val))

      if len(node.exec_stats) > 0:
        avg_time = agg_stats.latency_ns / len(node.exec_stats)
      else:
        avg_time = 0

      row["num_hosts"] = len(node.exec_stats)
      row["avg_time"] = avg_time

    is_sink = node.node_id == -1
    # If the node is a broadcast-receiving exchange node, the cardinality of rows produced
    # is the max over all instances (which should all have received the same number of
    # rows). Otherwise, the cardinality is the sum over all instances which process
    # disjoint partitions.
    if is_sink:
      cardinality = -1
    elif node.is_broadcast:
      cardinality = max_stats.cardinality
    else:
      cardinality = agg_stats.cardinality

    est_stats = node.estimated_stats

    label_prefix = ""
    if indent_level > 0:
      label_prefix = "|"
      label_prefix += "  |" * (indent_level - 1)
      if new_indent_level:
        label_prefix += "--"
      else:
        label_prefix += "  "

    row["prefix"] = label_prefix
    row["operator"] = node.label
    row["max_time"] = max_stats.latency_ns
    row["num_rows"] = cardinality
    row["est_num_rows"] = est_stats.cardinality
    row["peak_mem"] = max_stats.memory_used
    row["est_peak_mem"] = est_stats.memory_used
    row["detail"] = node.label_detail
    output.append(row)

    if summary.exch_to_sender_map is not None and idx in summary.exch_to_sender_map:
      sender_idx = summary.exch_to_sender_map[idx]
      # This is an exchange node, so the sender is a fragment root, and should be printed
      # next.
      self.__build_summary_table(summary, sender_idx, True, indent_level, False, output)

    idx += 1
    if node.num_children > 0:
      first_child_output = []
      idx = \
        self.__build_summary_table(
            summary, idx, False, indent_level, False, first_child_output)
      for child_idx in xrange(1, node.num_children):
        # All other children are indented (we only have 0, 1 or 2 children for every exec
        # node at the moment)
        idx = self.__build_summary_table(
            summary, idx, False, indent_level + 1, True, output)
      output += first_child_output
    return idx

  def get_runtime_profile(self, handle):
    return self.__do_rpc(lambda: self.imp_service.GetRuntimeProfile(handle))

  def execute_query_async(self, query_string, user=None):
    """
    Executes a query asynchronously

    Issues a query and returns the query handle to the caller for processing.
    """
    query = BeeswaxService.Query()
    query.query = query_string
    query.hadoop_user = user if user is not None else getpass.getuser()
    query.configuration = self.__options_to_string_list()
    handle = self.__do_rpc(lambda: self.imp_service.query(query,))
    LOG.info("Started query {0}".format(handle.id))
    return handle

  def __execute_query(self, query_string, user=None):
    """Executes a query and waits for completion"""
    handle = self.execute_query_async(query_string, user=user)
    # Wait for the query to finish execution.
    self.wait_for_finished(handle)
    return handle

  def cancel_query(self, query_id):
    return self.__do_rpc(lambda: self.imp_service.Cancel(query_id))

  def close_query(self, handle):
    self.__do_rpc(lambda: self.imp_service.close(handle))

  def wait_for_finished(self, query_handle):
    """Given a query handle, polls the coordinator waiting for the query to transition to
       'FINISHED' state"""
    while True:
      query_state = self.get_state(query_handle)
      # if the rpc succeeded, the output is the query state
      if query_state == self.query_states["FINISHED"]:
        break
      elif query_state == self.query_states["EXCEPTION"]:
        try:
          error_log = self.__do_rpc(
            lambda: self.imp_service.get_log(query_handle.log_context))
          raise ImpalaBeeswaxException("Query aborted:" + error_log, None)
        finally:
          self.close_query(query_handle)
      time.sleep(0.05)

  def wait_for_finished_timeout(self, query_handle, timeout=10):
    """Given a query handle and a timeout, polls the coordinator waiting for the query to
       transition to 'FINISHED' state till 'timeout' seconds"""
    start_time = time.time()
    while (time.time() - start_time < timeout):
      query_state = self.get_state(query_handle)
      # if the rpc succeeded, the output is the query state
      if query_state == self.query_states["FINISHED"]:
        return True
      elif query_state == self.query_states["EXCEPTION"]:
        try:
          error_log = self.__do_rpc(
            lambda: self.imp_service.get_log(query_handle.log_context))
          raise ImpalaBeeswaxException("Query aborted:" + error_log, None)
        finally:
          self.close_query(query_handle)
      time.sleep(0.05)
    return False

  def wait_for_admission_control(self, query_handle):
    """Given a query handle, polls the coordinator waiting for it to complete
      admission control processing of the query"""
    while True:
      query_state = self.get_state(query_handle)
      if query_state > self.query_states["COMPILED"]:
        break
      time.sleep(0.05)

  def get_admission_result(self, query_handle):
    """Given a query handle, returns the admission result from the query profile"""
    query_state = self.get_state(query_handle)
    if query_state > self.query_states["COMPILED"]:
      query_profile = self.get_runtime_profile(query_handle)
      admit_result = re.search(r"Admission result: (.*)", query_profile)
      if admit_result:
        return admit_result.group(1)
    return ""

  def get_default_configuration(self):
    return self.__do_rpc(lambda: self.imp_service.get_default_configuration(False))

  def get_state(self, query_handle):
    return self.__do_rpc(lambda: self.imp_service.get_state(query_handle))

  def get_log(self, query_handle):
    return self.__do_rpc(lambda: self.imp_service.get_log(query_handle))

  def fetch_results(self, query_string, query_handle, max_rows = -1):
    """Fetches query results given a handle and query type (insert, use, other)"""
    query_type = self.__get_query_type(query_string)
    if query_type == 'use':
      # TODO: "use <database>" does not currently throw an error. Need to update this
      # to handle the error case once that behavior has been changed.
      return ImpalaBeeswaxResult(query=query_string, query_id=query_handle.id,
                                 success=True, data=[])

    # Result fetching for insert is different from other queries.
    exec_result = None
    if query_type == 'insert':
      exec_result = self.__fetch_insert_results(query_handle)
    else:
      exec_result = self.__fetch_results(query_handle, max_rows)
    exec_result.query = query_string
    return exec_result

  def __fetch_results(self, handle, max_rows = -1):
    """Handles query results, returns a ImpalaBeeswaxResult object"""
    schema = self.__do_rpc(lambda: self.imp_service.get_results_metadata(handle)).schema
    # The query has finished, we can fetch the results
    result_rows = []
    while len(result_rows) < max_rows or max_rows < 0:
      fetch_rows = -1 if max_rows < 0 else max_rows - len(result_rows)
      results = self.__do_rpc(lambda: self.imp_service.fetch(handle, False, fetch_rows))
      result_rows.extend(results.data)
      if not results.has_more:
        break

    # The query executed successfully and all the data was fetched.
    exec_result = ImpalaBeeswaxResult(query_id=handle.id, success=True, data=result_rows,
                                      schema=schema)
    exec_result.summary = 'Returned %d rows' % (len(result_rows))
    return exec_result

  def close_dml(self, handle):
    return self.__do_rpc(lambda: self.imp_service.CloseInsert(handle))

  def __fetch_insert_results(self, handle):
    """Executes an insert query"""
    result = self.close_dml(handle)
    # The insert was successful
    num_rows = sum(map(int, result.rows_modified.values()))
    data = ["%s: %s" % row for row in result.rows_modified.iteritems()]
    exec_result = ImpalaBeeswaxResult(query_id=handle.id, success=True, data=data)
    exec_result.summary = "Inserted %d rows" % (num_rows,)
    return exec_result

  def __get_query_type(self, query_string):
    # Set posix=True and add "'" to escaped quotes
    # to deal with escaped quotes in string literals
    lexer = shlex.shlex(query_string.lstrip(), posix=True)
    lexer.escapedquotes += "'"
    tokens = list(lexer)
    # Do not classify explain queries as 'insert'
    if (tokens[0].lower() == "explain"):
      return tokens[0].lower()
    # Because the WITH clause may precede INSERT or SELECT queries,
    # just checking the first token is insufficient.
    if filter(self.INSERT_REGEX.match, tokens):
      return "insert"
    return tokens[0].lower()

  def __build_error_message(self, exception):
    """Construct a meaningful exception string"""
    message = str(exception)
    if isinstance(exception, BeeswaxService.BeeswaxException):
      message = exception.message
    return 'INNER EXCEPTION: %s\n MESSAGE: %s' % (exception.__class__, message)

  def __do_rpc(self, rpc):
    """Executes the RPC lambda provided with some error checking.

    Catches all the relevant exceptions and re throws them wrapped
    in a custom exception [ImpalaBeeswaxException].
    """
    if not self.connected:
      raise ImpalaBeeswaxException("Not connected", None)
    try:
      return rpc()
    except BeeswaxService.BeeswaxException, b:
      raise ImpalaBeeswaxException(self.__build_error_message(b), b)
    except TTransportException, e:
      self.connected = False
      raise ImpalaBeeswaxException(self.__build_error_message(e), e)
    except TApplicationException, t:
      raise ImpalaBeeswaxException(self.__build_error_message(t), t)
    except Exception, u:
      raise ImpalaBeeswaxException(self.__build_error_message(u), u)


text:
class BtWorld;
class btRigidBody;
class btCompoundShape;
class BtCollision;

class BtBody : public PhysicsBody
{
protected:

   /// The physics world we are in.
   BtWorld *mWorld;

   /// The physics actor.
   btRigidBody *mActor;

   /// The collision representation.
   StrongRefPtr<BtCollision> mColShape;

   /// Our local compound if we had to adjust
   /// the mass center on a dynamic.
   btCompoundShape *mCompound;

   ///
   F32 mMass;

   ///
   bool mIsDynamic;

   /// Is the body participating in the physics simulation.
   bool mIsEnabled;

   /// The center of mass offset used if the graphical
   /// transform is not at the mass center.
   MatrixF *mCenterOfMass;

   /// The inverse center of mass offset.
   MatrixF *mInvCenterOfMass;

   ///
   void _releaseActor();

public:

   BtBody();
   virtual ~BtBody();

   // PhysicsObject
   virtual PhysicsWorld* getWorld();
   virtual void setTransform( const MatrixF &xfm );
   virtual MatrixF& getTransform( MatrixF *outMatrix );
   virtual Box3F getWorldBounds();
   virtual void setSimulationEnabled( bool enabled );
   virtual bool isSimulationEnabled() { return mIsEnabled; }

   // PhysicsBody
   virtual bool init(   PhysicsCollision *shape,
                        F32 mass,
                        U32 bodyFlags,
                        SceneObject *obj,
                        PhysicsWorld *world );
   virtual bool isDynamic() const { return mIsDynamic; }
   virtual PhysicsCollision* getColShape();
   virtual void setSleepThreshold( F32 linear, F32 angular );
   virtual void setDamping( F32 linear, F32 angular );
   virtual void getState( PhysicsState *outState );
   virtual F32 getMass() const { return mMass; }
   virtual Point3F getCMassPosition() const;
   virtual void setLinVelocity( const Point3F &vel );
   virtual void setAngVelocity( const Point3F &vel );
   virtual Point3F getLinVelocity() const;
   virtual Point3F getAngVelocity() const;
   virtual void setSleeping( bool sleeping );
   virtual void setMaterial(  F32 restitution,
                              F32 friction,
                              F32 staticFriction );
   virtual void applyCorrection( const MatrixF &xfm );
   virtual void applyImpulse( const Point3F &origin, const Point3F &force );
};

#endif // _T3D_PHYSICS_BTBODY_H_


text:
using System;
using System.Buffers.Binary;
using System.Globalization;
using System.IO;
using System.Text;

namespace Orleans.Runtime
{
    [Serializable, Immutable]
    [GenerateSerializer]
    [SuppressReferenceTracking]
    public sealed class UniqueKey : IComparable<UniqueKey>, IEquatable<UniqueKey>
    {
        /// <summary>
        /// Type id values encoded into UniqueKeys
        /// </summary>
        public enum Category : byte
        {
            None = 0,
            SystemTarget = 1,
            SystemGrain = 2,
            Grain = 3,
            Client = 4,
            KeyExtGrain = 6,
            // 7 was GeoClient
            KeyExtSystemTarget = 8,
        }

        [Id(1)]
        public UInt64 N0 { get; private set; }
        [Id(2)]
        public UInt64 N1 { get; private set; }
        [Id(3)]
        public UInt64 TypeCodeData { get; private set; }
        [Id(4)]
        public string KeyExt { get; private set; }

        [NonSerialized]
        private uint uniformHashCache;

        public int BaseTypeCode => (int)TypeCodeData;

        public Category IdCategory => GetCategory(TypeCodeData);

        public bool IsLongKey => N0 == 0;

        public bool IsSystemTargetKey
            => IsSystemTarget(IdCategory);

        private static bool IsSystemTarget(Category category)
            => category == Category.SystemTarget || category == Category.KeyExtSystemTarget;

        public bool HasKeyExt => IsKeyExt(IdCategory);

        private static bool IsKeyExt(Category category)
            => category == Category.KeyExtGrain || category == Category.KeyExtSystemTarget;

        internal static readonly UniqueKey Empty = new UniqueKey();

        internal static UniqueKey Parse(ReadOnlySpan<char> input)
        {
            const int minimumValidKeyLength = 48;
            input = input.Trim();
            if (input.Length >= minimumValidKeyLength)
            {
                var n0 = ulong.Parse(input.Slice(0, 16).ToString(), NumberStyles.AllowHexSpecifier);
                var n1 = ulong.Parse(input.Slice(16, 16).ToString(), NumberStyles.AllowHexSpecifier);
                var typeCodeData = ulong.Parse(input.Slice(32, 16).ToString(), NumberStyles.AllowHexSpecifier);
                string keyExt = null;
                if (input.Length > minimumValidKeyLength)
                {
                    if (input[48] != '+') throw new InvalidDataException("UniqueKey hex string missing + separator.");
                    keyExt = input.Slice(49).ToString();
                }

                return NewKey(n0, n1, typeCodeData, keyExt);
            }

            // last, for convenience we attempt to parse the string using GUID syntax. this is needed by unit
            // tests but i don't know if it's needed for production.
            return NewKey(Guid.Parse(input.ToString()));
        }

        internal static UniqueKey NewKey(ulong n0, ulong n1, Category category, long typeData, string keyExt)
            => NewKey(n0, n1, GetTypeCodeData(category, typeData), keyExt);

        internal static UniqueKey NewKey(long longKey, Category category = Category.None, long typeData = 0, string keyExt = null)
        {
            ThrowIfIsSystemTargetKey(category);

            var key = NewKey(GetTypeCodeData(category, typeData), keyExt);
            key.N1 = (ulong)longKey;
            return key;
        }

        public static UniqueKey NewKey() => new UniqueKey { Guid = Guid.NewGuid() };

        internal static UniqueKey NewKey(Guid guid) => new UniqueKey { Guid = guid };

        internal static UniqueKey NewKey(Guid guid, Category category = Category.None, long typeData = 0, string keyExt = null)
        {
            ThrowIfIsSystemTargetKey(category);

            var key = NewKey(GetTypeCodeData(category, typeData), keyExt);
            key.Guid = guid;
            return key;
        }

        internal static UniqueKey NewEmptySystemTargetKey(long typeData)
            => new UniqueKey { TypeCodeData = GetTypeCodeData(Category.SystemTarget, typeData) };

        public static UniqueKey NewSystemTargetKey(Guid guid, long typeData)
            => new UniqueKey { Guid = guid, TypeCodeData = GetTypeCodeData(Category.SystemTarget, typeData) };

        public static UniqueKey NewSystemTargetKey(short systemId)
            => new UniqueKey { N1 = (ulong)systemId, TypeCodeData = GetTypeCodeData(Category.SystemTarget) };

        public static UniqueKey NewGrainServiceKey(short key, long typeData)
            => new UniqueKey { N1 = (ulong)key, TypeCodeData = GetTypeCodeData(Category.SystemTarget, typeData) };

        public static UniqueKey NewGrainServiceKey(string key, long typeData)
            => NewKey(GetTypeCodeData(Category.KeyExtSystemTarget, typeData), key);

        internal static UniqueKey NewKey(ulong n0, ulong n1, ulong typeCodeData, string keyExt)
        {
            var key = NewKey(typeCodeData, keyExt);
            key.N0 = n0;
            key.N1 = n1;
            return key;
        }

        private static UniqueKey NewKey(ulong typeCodeData, string keyExt)
        {
            if (IsKeyExt(GetCategory(typeCodeData)))
            {
                if (string.IsNullOrWhiteSpace(keyExt))
                    throw keyExt is null ? new ArgumentNullException("keyExt") : throw new ArgumentException("Extended key is empty or white space.", "keyExt");
            }
            else if (keyExt != null) throw new ArgumentException("Only key extended grains can specify a non-null key extension.");
            return new UniqueKey { TypeCodeData = typeCodeData, KeyExt = keyExt };
        }

        private void ThrowIfIsNotLong()
        {
            if (!IsLongKey)
                throw new InvalidOperationException("this key cannot be interpreted as a long value");
        }

        private static void ThrowIfIsSystemTargetKey(Category category)
        {
            if (IsSystemTarget(category))
                throw new ArgumentException(
                    "This overload of NewKey cannot be used to construct an instance of UniqueKey containing a SystemTarget id.");
        }

        private void ThrowIfHasKeyExt(string methodName)
        {
            if (KeyExt != null)
                throw new InvalidOperationException(
                    string.Format(
                        "This overload of {0} cannot be used if the grain uses the primary key extension feature.",
                        methodName));
        }

        public long PrimaryKeyToLong(out string extendedKey)
        {
            ThrowIfIsNotLong();

            extendedKey = this.KeyExt;
            return unchecked((long)N1);
        }

        public long PrimaryKeyToLong()
        {
            ThrowIfIsNotLong();
            ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToLong");
            return (long)N1;
        }

        public Guid PrimaryKeyToGuid(out string extendedKey)
        {
            extendedKey = this.KeyExt;
            return Guid;
        }

        public Guid PrimaryKeyToGuid()
        {
            ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToGuid");
            return Guid;
        }

        public override bool Equals(object o) => o is UniqueKey key && Equals(key);

        // We really want Equals to be as fast as possible, as a minimum cost, as close to native as possible.
        // No function calls, no boxing, inline.
        public bool Equals(UniqueKey other)
        {
            return N0 == other.N0
                   && N1 == other.N1
                   && TypeCodeData == other.TypeCodeData
                   && (KeyExt is null || KeyExt == other.KeyExt);
        }

        // We really want CompareTo to be as fast as possible, as a minimum cost, as close to native as possible.
        // No function calls, no boxing, inline.
        public int CompareTo(UniqueKey other)
        {
            return TypeCodeData < other.TypeCodeData ? -1
               : TypeCodeData > other.TypeCodeData ? 1
               : N0 < other.N0 ? -1
               : N0 > other.N0 ? 1
               : N1 < other.N1 ? -1
               : N1 > other.N1 ? 1
               : KeyExt == null ? 0
               : string.CompareOrdinal(KeyExt, other.KeyExt);
        }

        public override int GetHashCode()
        {
            return unchecked((int)GetUniformHashCode());
        }

        internal uint GetUniformHashCode()
        {
            // Disabling this ReSharper warning; hashCache is a logically read-only variable, so accessing them in GetHashCode is safe.
            // ReSharper disable NonReadonlyFieldInGetHashCode
            if (uniformHashCache == 0)
            {
                uint n;
                if (KeyExt != null)
                {
                    n = JenkinsHash.ComputeHash(this.ToByteArray());
                }
                else
                {
                    n = JenkinsHash.ComputeHash(TypeCodeData, N0, N1);
                }
                // Unchecked is required because the Jenkins hash is an unsigned 32-bit integer,
                // which we need to convert to a signed 32-bit integer.
                uniformHashCache = n;
            }
            return uniformHashCache;
            // ReSharper restore NonReadonlyFieldInGetHashCode
        }

        /// <summary>
        /// If KeyExt not exists, returns following structure
        /// |8 bytes|8 bytes|8 bytes|4 bytes| - total 28 bytes.
        /// If KeyExt exists, adds additional KeyExt bytes length
        /// </summary>
        /// <returns></returns>
        internal ReadOnlySpan<byte> ToByteArray()
        {
            var extBytes = this.KeyExt != null ? Encoding.UTF8.GetBytes(KeyExt) : null;
            var extBytesLength = extBytes?.Length ?? 0;
            var sizeWithoutExtBytes = sizeof(ulong) * 3 + sizeof(int);

            var spanBytes = new byte[sizeWithoutExtBytes + extBytesLength].AsSpan();

            BinaryPrimitives.WriteUInt64LittleEndian(spanBytes, N0);
            BinaryPrimitives.WriteUInt64LittleEndian(spanBytes.Slice(8, 8), N1);
            BinaryPrimitives.WriteUInt64LittleEndian(spanBytes.Slice(16, 8), TypeCodeData);

            const int offset = sizeof(ulong) * 3;
            // Copy KeyExt
            if (extBytes != null)
            {
                BinaryPrimitives.WriteInt32LittleEndian(spanBytes.Slice(offset, sizeof(int)), extBytesLength);
                extBytes.CopyTo(spanBytes.Slice(offset + sizeof(int)));
            }
            else
            {
                BinaryPrimitives.WriteInt32LittleEndian(spanBytes.Slice(offset, sizeof(int)), -1);
            }

            return spanBytes;
        }

        private unsafe Guid Guid
        {
            get
            {
                if (BitConverter.IsLittleEndian && sizeof(Guid) == 2 * sizeof(ulong))
                {
                    Guid value;
                    ((ulong*)&value)[0] = N0;
                    ((ulong*)&value)[1] = N1;
                    return value;
                }
                return new Guid((uint)N0, (ushort)(N0 >> 32), (ushort)(N0 >> 48), (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56));
            }
            set
            {
                if (BitConverter.IsLittleEndian && sizeof(Guid) == 2 * sizeof(ulong))
                {
                    N0 = ((ulong*)&value)[0];
                    N1 = ((ulong*)&value)[1];
                }
                else
                {
                    var guid = value.ToByteArray().AsSpan();
                    N0 = BinaryPrimitives.ReadUInt64LittleEndian(guid);
                    N1 = BinaryPrimitives.ReadUInt64LittleEndian(guid.Slice(8));
                }
            }
        }

        public override string ToString()
        {
            return ToHexString();
        }

        internal string ToHexString()
        {
            const string format = "{0:x16}{1:x16}{2:x16}";
            return KeyExt is null ? string.Format(format, N0, N1, TypeCodeData)
                : string.Format(format + "+{3}", N0, N1, TypeCodeData, KeyExt);
        }

        internal string ToGrainKeyString()
        {
            string keyString;
            if (HasKeyExt)
            {
                string extension;
                keyString = IsLongKey ? PrimaryKeyToLong(out extension).ToString() : PrimaryKeyToGuid(out extension).ToString();
                keyString = $"{keyString}+{extension}";
            }
            else
            {
                keyString = this.IsLongKey ? PrimaryKeyToLong().ToString() : this.PrimaryKeyToGuid().ToString();
            }
            return keyString;
        }

        internal static Category GetCategory(UInt64 typeCodeData)
        {
            return (Category)((typeCodeData >> 56) & 0xFF);
        }

        private static ulong GetTypeCodeData(Category category, long typeData = 0) => ((ulong)category << 56) + ((ulong)typeData & 0x00FFFFFFFFFFFFFF);
    }
}


text:
import Assert from "assertsharp";

Assert.AreEqual(0, 0, "Pass");
Assert.AreNotEqual(0, 1, "Pass");
Assert.AreNotSame(new Date(), new Date(), "Pass");
Assert.AreSequenceEqual([0], [0], (x, y) => x === y, "Pass");
Assert.Fail("Should fail");
Assert.IsFalse(false, "Pass");
Assert.IsInstanceOfType(new Date(), Date, "Pass");
Assert.IsNotInstanceOfType(true, Date, "Pass");
Assert.IsNotNull(new Date(), "Pass");
Assert.IsNull(null, "Pass");
Assert.IsTrue(true, "Pass");
Assert.Throws(() => { throw ""; }, "Pass");


text:
extern "C" {
#endif

typedef struct TDWHCIRegister
{
	boolean	m_bValid;
	u32	m_nAddress;
	u32	m_nBuffer;
}
TDWHCIRegister;

void DWHCIRegister (TDWHCIRegister *pThis, u32 nAddress);
void DWHCIRegister2 (TDWHCIRegister *pThis, u32 nAddress, u32 nValue);
void _DWHCIRegister (TDWHCIRegister *pThis);

u32 DWHCIRegisterRead (TDWHCIRegister *pThis);
void DWHCIRegisterWrite (TDWHCIRegister *pThis);

u32 DWHCIRegisterGet (TDWHCIRegister *pThis);
void DWHCIRegisterSet (TDWHCIRegister *pThis, u32 nValue);

boolean DWHCIRegisterIsSet (TDWHCIRegister *pThis, u32 nMask);

void DWHCIRegisterAnd (TDWHCIRegister *pThis, u32 nMask);
void DWHCIRegisterOr (TDWHCIRegister *pThis, u32 nMask);

void DWHCIRegisterClearBit (TDWHCIRegister *pThis, unsigned nBit);
void DWHCIRegisterSetBit (TDWHCIRegister *pThis, unsigned nBit);
void DWHCIRegisterClearAll (TDWHCIRegister *pThis);
void DWHCIRegisterSetAll (TDWHCIRegister *pThis);

#ifndef NDEBUG

void DWHCIRegisterDump (TDWHCIRegister *pThis);

#endif

#ifdef __cplusplus
}
#endif

#endif