text:
#include "qhull_a.h"

/*============= functions in alphabetic order after qhull() =======*/

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

  qh_qhull()
    compute DIM3 convex hull of qh.num_points starting at qh.first_point
    qh contains all global options and variables

  returns:
    returns polyhedron
      qh.facet_list, qh.num_facets, qh.vertex_list, qh.num_vertices,

    returns global variables
      qh.hulltime, qh.max_outside, qh.interior_point, qh.max_vertex, qh.min_vertex

    returns precision constants
      qh.ANGLEround, centrum_radius, cos_max, DISTround, MAXabs_coord, ONEmerge

  notes:
    unless needed for output
      qh.max_vertex and qh.min_vertex are max/min due to merges

  see:
    to add individual points to either qh.num_points
      use qh_addpoint()

    if qh.GETarea
      qh_produceoutput() returns qh.totarea and qh.totvol via qh_getarea()

  design:
    record starting time
    initialize hull and partition points
    build convex hull
    unless early termination
      update facet->maxoutside for vertices, coplanar, and near-inside points
    error if temporary sets exist
    record end time
*/

void qh_qhull(void) {
  int numoutside;

  qh hulltime= qh_CPUclock;
  if (qh RERUN || qh JOGGLEmax < REALmax/2)
    qh_build_withrestart();
  else {
    qh_initbuild();
    qh_buildhull();
  }
  if (!qh STOPpoint && !qh STOPcone) {
    if (qh ZEROall_ok && !qh TESTvneighbors && qh MERGEexact)
      qh_checkzero( qh_ALL);
    if (qh ZEROall_ok && !qh TESTvneighbors && !qh WAScoplanar) {
      trace2((qh ferr, 2055, "qh_qhull: all facets are clearly convex and no coplanar points.  Post-merging and check of maxout not needed.\n"));
      qh DOcheckmax= False;
    }else {
      if (qh MERGEexact || (qh hull_dim > qh_DIMreduceBuild && qh PREmerge))
        qh_postmerge("First post-merge", qh premerge_centrum, qh premerge_cos,
             (qh POSTmerge ? False : qh TESTvneighbors));
      else if (!qh POSTmerge && qh TESTvneighbors)
        qh_postmerge("For testing vertex neighbors", qh premerge_centrum,
             qh premerge_cos, True);
      if (qh POSTmerge)
        qh_postmerge("For post-merging", qh postmerge_centrum,
             qh postmerge_cos, qh TESTvneighbors);
      if (qh visible_list == qh facet_list) { /* i.e., merging done */
        qh findbestnew= True;
        qh_partitionvisible(/*qh.visible_list*/ !qh_ALL, &numoutside);
        qh findbestnew= False;
        qh_deletevisible(/*qh.visible_list*/);
        qh_resetlists(False, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
      }
    }
    if (qh DOcheckmax){
      if (qh REPORTfreq) {
        qh_buildtracing(NULL, NULL);
        qh_fprintf(qh ferr, 8115, "\nTesting all coplanar points.\n");
      }
      qh_check_maxout();
    }
    if (qh KEEPnearinside && !qh maxoutdone)
      qh_nearcoplanar();
  }
  if (qh_setsize(qhmem.tempstack) != 0) {
    qh_fprintf(qh ferr, 6164, "qhull internal error (qh_qhull): temporary sets not empty(%d)\n",
             qh_setsize(qhmem.tempstack));
    qh_errexit(qh_ERRqhull, NULL, NULL);
  }
  qh hulltime= qh_CPUclock - qh hulltime;
  qh QHULLfinished= True;
  trace1((qh ferr, 1036, "Qhull: algorithm completed\n"));
} /* qhull */

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

  qh_addpoint( furthest, facet, checkdist )
    add point (usually furthest point) above facet to hull
    if checkdist,
      check that point is above facet.
      if point is not outside of the hull, uses qh_partitioncoplanar()
      assumes that facet is defined by qh_findbestfacet()
    else if facet specified,
      assumes that point is above facet (major damage if below)
    for Delaunay triangulations,
      Use qh_setdelaunay() to lift point to paraboloid and scale by 'Qbb' if needed
      Do not use options 'Qbk', 'QBk', or 'QbB' since they scale the coordinates.

  returns:
    returns False if user requested an early termination
     qh.visible_list, newfacet_list, delvertex_list, NEWfacets may be defined
    updates qh.facet_list, qh.num_facets, qh.vertex_list, qh.num_vertices
    clear qh.maxoutdone (will need to call qh_check_maxout() for facet->maxoutside)
    if unknown point, adds a pointer to qh.other_points
      do not deallocate the point's coordinates

  notes:
    assumes point is near its best facet and not at a local minimum of a lens
      distributions.  Use qh_findbestfacet to avoid this case.
    uses qh.visible_list, qh.newfacet_list, qh.delvertex_list, qh.NEWfacets

  see also:
    qh_triangulate() -- triangulate non-simplicial facets

  design:
    add point to other_points if needed
    if checkdist
      if point not above facet
        partition coplanar point
        exit
    exit if pre STOPpoint requested
    find horizon and visible facets for point
    make new facets for point to horizon
    make hyperplanes for point
    compute balance statistics
    match neighboring new facets
    update vertex neighbors and delete interior vertices
    exit if STOPcone requested
    merge non-convex new facets
    if merge found, many merges, or 'Qf'
       use qh_findbestnew() instead of qh_findbest()
    partition outside points from visible facets
    delete visible facets
    check polyhedron if requested
    exit if post STOPpoint requested
    reset working lists of facets and vertices
*/
boolT qh_addpoint(pointT *furthest, facetT *facet, boolT checkdist) {
  int goodvisible, goodhorizon;
  vertexT *vertex;
  facetT *newfacet;
  realT dist, newbalance, pbalance;
  boolT isoutside= False;
  int numpart, numpoints, numnew, firstnew;

  qh maxoutdone= False;
  if (qh_pointid(furthest) == qh_IDunknown)
    qh_setappend(&qh other_points, furthest);
  if (!facet) {
    qh_fprintf(qh ferr, 6213, "qhull internal error (qh_addpoint): NULL facet.  Need to call qh_findbestfacet first\n");
    qh_errexit(qh_ERRqhull, NULL, NULL);
  }
  if (checkdist) {
    facet= qh_findbest(furthest, facet, !qh_ALL, !qh_ISnewfacets, !qh_NOupper,
                        &dist, &isoutside, &numpart);
    zzadd_(Zpartition, numpart);
    if (!isoutside) {
      zinc_(Znotmax);  /* last point of outsideset is no longer furthest. */
      facet->notfurthest= True;
      qh_partitioncoplanar(furthest, facet, &dist);
      return True;
    }
  }
  qh_buildtracing(furthest, facet);
  if (qh STOPpoint < 0 && qh furthest_id == -qh STOPpoint-1) {
    facet->notfurthest= True;
    return False;
  }
  qh_findhorizon(furthest, facet, &goodvisible, &goodhorizon);
  if (qh ONLYgood && !(goodvisible+goodhorizon) && !qh GOODclosest) {
    zinc_(Znotgood);
    facet->notfurthest= True;
    /* last point of outsideset is no longer furthest.  This is ok
       since all points of the outside are likely to be bad */
    qh_resetlists(False, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
    return True;
  }
  zzinc_(Zprocessed);
  firstnew= qh facet_id;
  vertex= qh_makenewfacets(furthest /*visible_list, attaches if !ONLYgood */);
  qh_makenewplanes(/* newfacet_list */);
  numnew= qh facet_id - firstnew;
  newbalance= numnew - (realT) (qh num_facets-qh num_visible)
                         * qh hull_dim/qh num_vertices;
  wadd_(Wnewbalance, newbalance);
  wadd_(Wnewbalance2, newbalance * newbalance);
  if (qh ONLYgood
  && !qh_findgood(qh newfacet_list, goodhorizon) && !qh GOODclosest) {
    FORALLnew_facets
      qh_delfacet(newfacet);
    qh_delvertex(vertex);
    qh_resetlists(True, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
    zinc_(Znotgoodnew);
    facet->notfurthest= True;
    return True;
  }
  if (qh ONLYgood)
    qh_attachnewfacets(/*visible_list*/);
  qh_matchnewfacets();
  qh_updatevertices();
  if (qh STOPcone && qh furthest_id == qh STOPcone-1) {
    facet->notfurthest= True;
    return False;  /* visible_list etc. still defined */
  }
  qh findbestnew= False;
  if (qh PREmerge || qh MERGEexact) {
    qh_premerge(vertex, qh premerge_centrum, qh premerge_cos);
    if (qh_USEfindbestnew)
      qh findbestnew= True;
    else {
      FORALLnew_facets {
        if (!newfacet->simplicial) {
          qh findbestnew= True;  /* use qh_findbestnew instead of qh_findbest*/
          break;
        }
      }
    }
  }else if (qh BESToutside)
    qh findbestnew= True;
  qh_partitionvisible(/*qh.visible_list*/ !qh_ALL, &numpoints);
  qh findbestnew= False;
  qh findbest_notsharp= False;
  zinc_(Zpbalance);
  pbalance= numpoints - (realT) qh hull_dim /* assumes all points extreme */
                * (qh num_points - qh num_vertices)/qh num_vertices;
  wadd_(Wpbalance, pbalance);
  wadd_(Wpbalance2, pbalance * pbalance);
  qh_deletevisible(/*qh.visible_list*/);
  zmax_(Zmaxvertex, qh num_vertices);
  qh NEWfacets= False;
  if (qh IStracing >= 4) {
    if (qh num_facets < 2000)
      qh_printlists();
    qh_printfacetlist(qh newfacet_list, NULL, True);
    qh_checkpolygon(qh facet_list);
  }else if (qh CHECKfrequently) {
    if (qh num_facets < 50)
      qh_checkpolygon(qh facet_list);
    else
      qh_checkpolygon(qh newfacet_list);
  }
  if (qh STOPpoint > 0 && qh furthest_id == qh STOPpoint-1)
    return False;
  qh_resetlists(True, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
  /* qh_triangulate(); to test qh.TRInormals */
  trace2((qh ferr, 2056, "qh_addpoint: added p%d new facets %d new balance %2.2g point balance %2.2g\n",
    qh_pointid(furthest), numnew, newbalance, pbalance));
  return True;
} /* addpoint */

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

  qh_build_withrestart()
    allow restarts due to qh.JOGGLEmax while calling qh_buildhull()
       qh_errexit always undoes qh_build_withrestart()
    qh.FIRSTpoint/qh.NUMpoints is point array
        it may be moved by qh_joggleinput()
*/
void qh_build_withrestart(void) {
  int restart;

  qh ALLOWrestart= True;
  while (True) {
    restart= setjmp(qh restartexit); /* simple statement for CRAY J916 */
    if (restart) {       /* only from qh_precision() */
      zzinc_(Zretry);
      wmax_(Wretrymax, qh JOGGLEmax);
      /* QH7078 warns about using 'TCn' with 'QJn' */
      qh STOPcone= qh_IDunknown; /* if break from joggle, prevents normal output */
    }
    if (!qh RERUN && qh JOGGLEmax < REALmax/2) {
      if (qh build_cnt > qh_JOGGLEmaxretry) {
        qh_fprintf(qh ferr, 6229, "qhull precision error: %d attempts to construct a convex hull\n\
        with joggled input.  Increase joggle above 'QJ%2.2g'\n\
        or modify qh_JOGGLE... parameters in user.h\n",
           qh build_cnt, qh JOGGLEmax);
        qh_errexit(qh_ERRqhull, NULL, NULL);
      }
      if (qh build_cnt && !restart)
        break;
    }else if (qh build_cnt && qh build_cnt >= qh RERUN)
      break;
    qh STOPcone= 0;
    qh_freebuild(True);  /* first call is a nop */
    qh build_cnt++;
    if (!qh qhull_optionsiz)
      qh qhull_optionsiz= (int)strlen(qh qhull_options);   /* WARN64 */
    else {
      qh qhull_options [qh qhull_optionsiz]= '\0';
      qh qhull_optionlen= qh_OPTIONline;  /* starts a new line */
    }
    qh_option("_run", &qh build_cnt, NULL);
    if (qh build_cnt == qh RERUN) {
      qh IStracing= qh TRACElastrun;  /* duplicated from qh_initqhull_globals */
      if (qh TRACEpoint != qh_IDunknown || qh TRACEdist < REALmax/2 || qh TRACEmerge) {
        qh TRACElevel= (qh IStracing? qh IStracing : 3);
        qh IStracing= 0;
      }
      qhmem.IStracing= qh IStracing;
    }
    if (qh JOGGLEmax < REALmax/2)
      qh_joggleinput();
    qh_initbuild();
    qh_buildhull();
    if (qh JOGGLEmax < REALmax/2 && !qh MERGING)
      qh_checkconvex(qh facet_list, qh_ALGORITHMfault);
  }
  qh ALLOWrestart= False;
} /* qh_build_withrestart */

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

  qh_buildhull()
    construct a convex hull by adding outside points one at a time

  returns:

  notes:
    may be called multiple times
    checks facet and vertex lists for incorrect flags
    to recover from STOPcone, call qh_deletevisible and qh_resetlists

  design:
    check visible facet and newfacet flags
    check newlist vertex flags and qh.STOPcone/STOPpoint
    for each facet with a furthest outside point
      add point to facet
      exit if qh.STOPcone or qh.STOPpoint requested
    if qh.NARROWhull for initial simplex
      partition remaining outside points to coplanar sets
*/
void qh_buildhull(void) {
  facetT *facet;
  pointT *furthest;
  vertexT *vertex;
  int id;

  trace1((qh ferr, 1037, "qh_buildhull: start build hull\n"));
  FORALLfacets {
    if (facet->visible || facet->newfacet) {
      qh_fprintf(qh ferr, 6165, "qhull internal error (qh_buildhull): visible or new facet f%d in facet list\n",
                   facet->id);
      qh_errexit(qh_ERRqhull, facet, NULL);
    }
  }
  FORALLvertices {
    if (vertex->newlist) {
      qh_fprintf(qh ferr, 6166, "qhull internal error (qh_buildhull): new vertex f%d in vertex list\n",
                   vertex->id);
      qh_errprint("ERRONEOUS", NULL, NULL, NULL, vertex);
      qh_errexit(qh_ERRqhull, NULL, NULL);
    }
    id= qh_pointid(vertex->point);
    if ((qh STOPpoint>0 && id == qh STOPpoint-1) ||
        (qh STOPpoint<0 && id == -qh STOPpoint-1) ||
        (qh STOPcone>0 && id == qh STOPcone-1)) {
      trace1((qh ferr, 1038,"qh_buildhull: stop point or cone P%d in initial hull\n", id));
      return;
    }
  }
  qh facet_next= qh facet_list;      /* advance facet when processed */
  while ((furthest= qh_nextfurthest(&facet))) {
    qh num_outside--;  /* if ONLYmax, furthest may not be outside */
    if (!qh_addpoint(furthest, facet, qh ONLYmax))
      break;
  }
  if (qh NARROWhull) /* move points from outsideset to coplanarset */
    qh_outcoplanar( /* facet_list */ );
  if (qh num_outside && !furthest) {
    qh_fprintf(qh ferr, 6167, "qhull internal error (qh_buildhull): %d outside points were never processed.\n", qh num_outside);
    qh_errexit(qh_ERRqhull, NULL, NULL);
  }
  trace1((qh ferr, 1039, "qh_buildhull: completed the hull construction\n"));
} /* buildhull */

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

  qh_buildtracing( furthest, facet )
    trace an iteration of qh_buildhull() for furthest point and facet
    if !furthest, prints progress message

  returns:
    tracks progress with qh.lastreport
    updates qh.furthest_id (-3 if furthest is NULL)
    also resets visit_id, vertext_visit on wrap around

  see:
    qh_tracemerging()

  design:
    if !furthest
      print progress message
      exit
    if 'TFn' iteration
      print progress message
    else if tracing
      trace furthest point and facet
    reset qh.visit_id and qh.vertex_visit if overflow may occur
    set qh.furthest_id for tracing
*/
void qh_buildtracing(pointT *furthest, facetT *facet) {
  realT dist= 0;
  float cpu;
  int total, furthestid;
  time_t timedata;
  struct tm *tp;
  vertexT *vertex;

  qh old_randomdist= qh RANDOMdist;
  qh RANDOMdist= False;
  if (!furthest) {
    time(&timedata);
    tp= localtime(&timedata);
    cpu= (float)qh_CPUclock - (float)qh hulltime;
    cpu /= (float)qh_SECticks;
    total= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
    qh_fprintf(qh ferr, 8118, "\n\
At %02d:%02d:%02d & %2.5g CPU secs, qhull has created %d facets and merged %d.\n\
 The current hull contains %d facets and %d vertices.  Last point was p%d\n",
      tp->tm_hour, tp->tm_min, tp->tm_sec, cpu, qh facet_id -1,
      total, qh num_facets, qh num_vertices, qh furthest_id);
    return;
  }
  furthestid= qh_pointid(furthest);
  if (qh TRACEpoint == furthestid) {
    qh IStracing= qh TRACElevel;
    qhmem.IStracing= qh TRACElevel;
  }else if (qh TRACEpoint != qh_IDunknown && qh TRACEdist < REALmax/2) {
    qh IStracing= 0;
    qhmem.IStracing= 0;
  }
  if (qh REPORTfreq && (qh facet_id-1 > qh lastreport+qh REPORTfreq)) {
    qh lastreport= qh facet_id-1;
    time(&timedata);
    tp= localtime(&timedata);
    cpu= (float)qh_CPUclock - (float)qh hulltime;
    cpu /= (float)qh_SECticks;
    total= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
    zinc_(Zdistio);
    qh_distplane(furthest, facet, &dist);
    qh_fprintf(qh ferr, 8119, "\n\
At %02d:%02d:%02d & %2.5g CPU secs, qhull has created %d facets and merged %d.\n\
 The current hull contains %d facets and %d vertices.  There are %d\n\
 outside points.  Next is point p%d(v%d), %2.2g above f%d.\n",
      tp->tm_hour, tp->tm_min, tp->tm_sec, cpu, qh facet_id -1,
      total, qh num_facets, qh num_vertices, qh num_outside+1,
      furthestid, qh vertex_id, dist, getid_(facet));
  }else if (qh IStracing >=1) {
    cpu= (float)qh_CPUclock - (float)qh hulltime;
    cpu /= (float)qh_SECticks;
    qh_distplane(furthest, facet, &dist);
    qh_fprintf(qh ferr, 8120, "qh_addpoint: add p%d(v%d) to hull of %d facets(%2.2g above f%d) and %d outside at %4.4g CPU secs.  Previous was p%d.\n",
      furthestid, qh vertex_id, qh num_facets, dist,
      getid_(facet), qh num_outside+1, cpu, qh furthest_id);
  }
  zmax_(Zvisit2max, (int)qh visit_id/2);
  if (qh visit_id > (unsigned) INT_MAX) { /* 31 bits */
    zinc_(Zvisit);
    qh visit_id= 0;
    FORALLfacets
      facet->visitid= 0;
  }
  zmax_(Zvvisit2max, (int)qh vertex_visit/2);
  if (qh vertex_visit > (unsigned) INT_MAX) { /* 31 bits */
    zinc_(Zvvisit);
    qh vertex_visit= 0;
    FORALLvertices
      vertex->visitid= 0;
  }
  qh furthest_id= furthestid;
  qh RANDOMdist= qh old_randomdist;
} /* buildtracing */

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

  qh_errexit2( exitcode, facet, otherfacet )
    return exitcode to system after an error
    report two facets

  returns:
    assumes exitcode non-zero

  see:
    normally use qh_errexit() in user.c(reports a facet and a ridge)
*/
void qh_errexit2(int exitcode, facetT *facet, facetT *otherfacet) {

  qh_errprint("ERRONEOUS", facet, otherfacet, NULL, NULL);
  qh_errexit(exitcode, NULL, NULL);
} /* errexit2 */

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

  qh_findhorizon( point, facet, goodvisible, goodhorizon )
    given a visible facet, find the point's horizon and visible facets
    for all facets, !facet-visible

  returns:
    returns qh.visible_list/num_visible with all visible facets
      marks visible facets with ->visible
    updates count of good visible and good horizon facets
    updates qh.max_outside, qh.max_vertex, facet->maxoutside

  see:
    similar to qh_delpoint()

  design:
    move facet to qh.visible_list at end of qh.facet_list
    for all visible facets
     for each unvisited neighbor of a visible facet
       compute distance of point to neighbor
       if point above neighbor
         move neighbor to end of qh.visible_list
       else if point is coplanar with neighbor
         update qh.max_outside, qh.max_vertex, neighbor->maxoutside
         mark neighbor coplanar (will create a samecycle later)
         update horizon statistics
*/
void qh_findhorizon(pointT *point, facetT *facet, int *goodvisible, int *goodhorizon) {
  facetT *neighbor, **neighborp, *visible;
  int numhorizon= 0, coplanar= 0;
  realT dist;

  trace1((qh ferr, 1040,"qh_findhorizon: find horizon for point p%d facet f%d\n",qh_pointid(point),facet->id));
  *goodvisible= *goodhorizon= 0;
  zinc_(Ztotvisible);
  qh_removefacet(facet);  /* visible_list at end of qh facet_list */
  qh_appendfacet(facet);
  qh num_visible= 1;
  if (facet->good)
    (*goodvisible)++;
  qh visible_list= facet;
  facet->visible= True;
  facet->f.replace= NULL;
  if (qh IStracing >=4)
    qh_errprint("visible", facet, NULL, NULL, NULL);
  qh visit_id++;
  FORALLvisible_facets {
    if (visible->tricoplanar && !qh TRInormals) {
      qh_fprintf(qh ferr, 6230, "Qhull internal error (qh_findhorizon): does not work for tricoplanar facets.  Use option 'Q11'\n");
      qh_errexit(qh_ERRqhull, visible, NULL);
    }
    visible->visitid= qh visit_id;
    FOREACHneighbor_(visible) {
      if (neighbor->visitid == qh visit_id)
        continue;
      neighbor->visitid= qh visit_id;
      zzinc_(Znumvisibility);
      qh_distplane(point, neighbor, &dist);
      if (dist > qh MINvisible) {
        zinc_(Ztotvisible);
        qh_removefacet(neighbor);  /* append to end of qh visible_list */
        qh_appendfacet(neighbor);
        neighbor->visible= True;
        neighbor->f.replace= NULL;
        qh num_visible++;
        if (neighbor->good)
          (*goodvisible)++;
        if (qh IStracing >=4)
          qh_errprint("visible", neighbor, NULL, NULL, NULL);
      }else {
        if (dist > - qh MAXcoplanar) {
          neighbor->coplanar= True;
          zzinc_(Zcoplanarhorizon);
          qh_precision("coplanar horizon");
          coplanar++;
          if (qh MERGING) {
            if (dist > 0) {
              maximize_(qh max_outside, dist);
              maximize_(qh max_vertex, dist);
#if qh_MAXoutside
              maximize_(neighbor->maxoutside, dist);
#endif
            }else
              minimize_(qh min_vertex, dist);  /* due to merge later */
          }
          trace2((qh ferr, 2057, "qh_findhorizon: point p%d is coplanar to horizon f%d, dist=%2.7g < qh MINvisible(%2.7g)\n",
              qh_pointid(point), neighbor->id, dist, qh MINvisible));
        }else
          neighbor->coplanar= False;
        zinc_(Ztothorizon);
        numhorizon++;
        if (neighbor->good)
          (*goodhorizon)++;
        if (qh IStracing >=4)
          qh_errprint("horizon", neighbor, NULL, NULL, NULL);
      }
    }
  }
  if (!numhorizon) {
    qh_precision("empty horizon");
    qh_fprintf(qh ferr, 6168, "qhull precision error (qh_findhorizon): empty horizon\n\
QhullPoint p%d was above all facets.\n", qh_pointid(point));
    qh_printfacetlist(qh facet_list, NULL, True);
    qh_errexit(qh_ERRprec, NULL, NULL);
  }
  trace1((qh ferr, 1041, "qh_findhorizon: %d horizon facets(good %d), %d visible(good %d), %d coplanar\n",
       numhorizon, *goodhorizon, qh num_visible, *goodvisible, coplanar));
  if (qh IStracing >= 4 && qh num_facets < 50)
    qh_printlists();
} /* findhorizon */

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

  qh_nextfurthest( visible )
    returns next furthest point and visible facet for qh_addpoint()
    starts search at qh.facet_next

  returns:
    removes furthest point from outside set
    NULL if none available
    advances qh.facet_next over facets with empty outside sets

  design:
    for each facet from qh.facet_next
      if empty outside set
        advance qh.facet_next
      else if qh.NARROWhull
        determine furthest outside point
        if furthest point is not outside
          advance qh.facet_next(point will be coplanar)
    remove furthest point from outside set
*/
pointT *qh_nextfurthest(facetT **visible) {
  facetT *facet;
  int size, idx;
  realT randr, dist;
  pointT *furthest;

  while ((facet= qh facet_next) != qh facet_tail) {
    if (!facet->outsideset) {
      qh facet_next= facet->next;
      continue;
    }
    SETreturnsize_(facet->outsideset, size);
    if (!size) {
      qh_setfree(&facet->outsideset);
      qh facet_next= facet->next;
      continue;
    }
    if (qh NARROWhull) {
      if (facet->notfurthest)
        qh_furthestout(facet);
      furthest= (pointT*)qh_setlast(facet->outsideset);
#if qh_COMPUTEfurthest
      qh_distplane(furthest, facet, &dist);
      zinc_(Zcomputefurthest);
#else
      dist= facet->furthestdist;
#endif
      if (dist < qh MINoutside) { /* remainder of outside set is coplanar for qh_outcoplanar */
        qh facet_next= facet->next;
        continue;
      }
    }
    if (!qh RANDOMoutside && !qh VIRTUALmemory) {
      if (qh PICKfurthest) {
        qh_furthestnext(/* qh.facet_list */);
        facet= qh facet_next;
      }
      *visible= facet;
      return((pointT*)qh_setdellast(facet->outsideset));
    }
    if (qh RANDOMoutside) {
      int outcoplanar = 0;
      if (qh NARROWhull) {
        FORALLfacets {
          if (facet == qh facet_next)
            break;
          if (facet->outsideset)
            outcoplanar += qh_setsize( facet->outsideset);
        }
      }
      randr= qh_RANDOMint;
      randr= randr/(qh_RANDOMmax+1);
      idx= (int)floor((qh num_outside - outcoplanar) * randr);
      FORALLfacet_(qh facet_next) {
        if (facet->outsideset) {
          SETreturnsize_(facet->outsideset, size);
          if (!size)
            qh_setfree(&facet->outsideset);
          else if (size > idx) {
            *visible= facet;
            return((pointT*)qh_setdelnth(facet->outsideset, idx));
          }else
            idx -= size;
        }
      }
      qh_fprintf(qh ferr, 6169, "qhull internal error (qh_nextfurthest): num_outside %d is too low\nby at least %d, or a random real %g >= 1.0\n",
              qh num_outside, idx+1, randr);
      qh_errexit(qh_ERRqhull, NULL, NULL);
    }else { /* VIRTUALmemory */
      facet= qh facet_tail->previous;
      if (!(furthest= (pointT*)qh_setdellast(facet->outsideset))) {
        if (facet->outsideset)
          qh_setfree(&facet->outsideset);
        qh_removefacet(facet);
        qh_prependfacet(facet, &qh facet_list);
        continue;
      }
      *visible= facet;
      return furthest;
    }
  }
  return NULL;
} /* nextfurthest */

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

  qh_partitionall( vertices, points, numpoints )
    partitions all points in points/numpoints to the outsidesets of facets
    vertices= vertices in qh.facet_list(!partitioned)

  returns:
    builds facet->outsideset
    does not partition qh.GOODpoint
    if qh.ONLYgood && !qh.MERGING,
      does not partition qh.GOODvertex

  notes:
    faster if qh.facet_list sorted by anticipated size of outside set

  design:
    initialize pointset with all points
    remove vertices from pointset
    remove qh.GOODpointp from pointset (unless it's qh.STOPcone or qh.STOPpoint)
    for all facets
      for all remaining points in pointset
        compute distance from point to facet
        if point is outside facet
          remove point from pointset (by not reappending)
          update bestpoint
          append point or old bestpoint to facet's outside set
      append bestpoint to facet's outside set (furthest)
    for all points remaining in pointset
      partition point into facets' outside sets and coplanar sets
*/
void qh_partitionall(setT *vertices, pointT *points, int numpoints){
  setT *pointset;
  vertexT *vertex, **vertexp;
  pointT *point, **pointp, *bestpoint;
  int size, point_i, point_n, point_end, remaining, i, id;
  facetT *facet;
  realT bestdist= -REALmax, dist, distoutside;

  trace1((qh ferr, 1042, "qh_partitionall: partition all points into outside sets\n"));
  pointset= qh_settemp(numpoints);
  qh num_outside= 0;
  pointp= SETaddr_(pointset, pointT);
  for (i=numpoints, point= points; i--; point += qh hull_dim)
    *(pointp++)= point;
  qh_settruncate(pointset, numpoints);
  FOREACHvertex_(vertices) {
    if ((id= qh_pointid(vertex->point)) >= 0)
      SETelem_(pointset, id)= NULL;
  }
  id= qh_pointid(qh GOODpointp);
  if (id >=0 && qh STOPcone-1 != id && -qh STOPpoint-1 != id)
    SETelem_(pointset, id)= NULL;
  if (qh GOODvertexp && qh ONLYgood && !qh MERGING) { /* matches qhull()*/
    if ((id= qh_pointid(qh GOODvertexp)) >= 0)
      SETelem_(pointset, id)= NULL;
  }
  if (!qh BESToutside) {  /* matches conditional for qh_partitionpoint below */
    distoutside= qh_DISToutside; /* multiple of qh.MINoutside & qh.max_outside, see user.h */
    zval_(Ztotpartition)= qh num_points - qh hull_dim - 1; /*misses GOOD... */
    remaining= qh num_facets;
    point_end= numpoints;
    FORALLfacets {
      size= point_end/(remaining--) + 100;
      facet->outsideset= qh_setnew(size);
      bestpoint= NULL;
      point_end= 0;
      FOREACHpoint_i_(pointset) {
        if (point) {
          zzinc_(Zpartitionall);
          qh_distplane(point, facet, &dist);
          if (dist < distoutside)
            SETelem_(pointset, point_end++)= point;
          else {
            qh num_outside++;
            if (!bestpoint) {
              bestpoint= point;
              bestdist= dist;
            }else if (dist > bestdist) {
              qh_setappend(&facet->outsideset, bestpoint);
              bestpoint= point;
              bestdist= dist;
            }else
              qh_setappend(&facet->outsideset, point);
          }
        }
      }
      if (bestpoint) {
        qh_setappend(&facet->outsideset, bestpoint);
#if !qh_COMPUTEfurthest
        facet->furthestdist= bestdist;
#endif
      }else
        qh_setfree(&facet->outsideset);
      qh_settruncate(pointset, point_end);
    }
  }
  /* if !qh BESToutside, pointset contains points not assigned to outsideset */
  if (qh BESToutside || qh MERGING || qh KEEPcoplanar || qh KEEPinside) {
    qh findbestnew= True;
    FOREACHpoint_i_(pointset) {
      if (point)
        qh_partitionpoint(point, qh facet_list);
    }
    qh findbestnew= False;
  }
  zzadd_(Zpartitionall, zzval_(Zpartition));
  zzval_(Zpartition)= 0;
  qh_settempfree(&pointset);
  if (qh IStracing >= 4)
    qh_printfacetlist(qh facet_list, NULL, True);
} /* partitionall */

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

  qh_partitioncoplanar( point, facet, dist )
    partition coplanar point to a facet
    dist is distance from point to facet
    if dist NULL,
      searches for bestfacet and does nothing if inside
    if qh.findbestnew set,
      searches new facets instead of using qh_findbest()

  returns:
    qh.max_ouside updated
    if qh.KEEPcoplanar or qh.KEEPinside
      point assigned to best coplanarset

  notes:
    facet->maxoutside is updated at end by qh_check_maxout

  design:
    if dist undefined
      find best facet for point
      if point sufficiently below facet (depends on qh.NEARinside and qh.KEEPinside)
        exit
    if keeping coplanar/nearinside/inside points
      if point is above furthest coplanar point
        append point to coplanar set (it is the new furthest)
        update qh.max_outside
      else
        append point one before end of coplanar set
    else if point is clearly outside of qh.max_outside and bestfacet->coplanarset
    and bestfacet is more than perpendicular to facet
      repartition the point using qh_findbest() -- it may be put on an outsideset
    else
      update qh.max_outside
*/
void qh_partitioncoplanar(pointT *point, facetT *facet, realT *dist) {
  facetT *bestfacet;
  pointT *oldfurthest;
  realT bestdist, dist2= 0, angle;
  int numpart= 0, oldfindbest;
  boolT isoutside;

  qh WAScoplanar= True;
  if (!dist) {
    if (qh findbestnew)
      bestfacet= qh_findbestnew(point, facet, &bestdist, qh_ALL, &isoutside, &numpart);
    else
      bestfacet= qh_findbest(point, facet, qh_ALL, !qh_ISnewfacets, qh DELAUNAY,
                          &bestdist, &isoutside, &numpart);
    zinc_(Ztotpartcoplanar);
    zzadd_(Zpartcoplanar, numpart);
    if (!qh DELAUNAY && !qh KEEPinside) { /*  for 'd', bestdist skips upperDelaunay facets */
      if (qh KEEPnearinside) {
        if (bestdist < -qh NEARinside) {
          zinc_(Zcoplanarinside);
          trace4((qh ferr, 4062, "qh_partitioncoplanar: point p%d is more than near-inside facet f%d dist %2.2g findbestnew %d\n",
                  qh_pointid(point), bestfacet->id, bestdist, qh findbestnew));
          return;
        }
      }else if (bestdist < -qh MAXcoplanar) {
          trace4((qh ferr, 4063, "qh_partitioncoplanar: point p%d is inside facet f%d dist %2.2g findbestnew %d\n",
                  qh_pointid(point), bestfacet->id, bestdist, qh findbestnew));
        zinc_(Zcoplanarinside);
        return;
      }
    }
  }else {
    bestfacet= facet;
    bestdist= *dist;
  }
  if (bestdist > qh max_outside) {
    if (!dist && facet != bestfacet) {
      zinc_(Zpartangle);
      angle= qh_getangle(facet->normal, bestfacet->normal);
      if (angle < 0) {
        /* typically due to deleted vertex and coplanar facets, e.g.,
             RBOX 1000 s Z1 G1e-13 t1001185205 | QHULL Tv */
        zinc_(Zpartflip);
        trace2((qh ferr, 2058, "qh_partitioncoplanar: repartition point p%d from f%d.  It is above flipped facet f%d dist %2.2g\n",
                qh_pointid(point), facet->id, bestfacet->id, bestdist));
        oldfindbest= qh findbestnew;
        qh findbestnew= False;
        qh_partitionpoint(point, bestfacet);
        qh findbestnew= oldfindbest;
        return;
      }
    }
    qh max_outside= bestdist;
    if (bestdist > qh TRACEdist) {
      qh_fprintf(qh ferr, 8122, "qh_partitioncoplanar: ====== p%d from f%d increases max_outside to %2.2g of f%d last p%d\n",
                     qh_pointid(point), facet->id, bestdist, bestfacet->id, qh furthest_id);
      qh_errprint("DISTANT", facet, bestfacet, NULL, NULL);
    }
  }
  if (qh KEEPcoplanar + qh KEEPinside + qh KEEPnearinside) {
    oldfurthest= (pointT*)qh_setlast(bestfacet->coplanarset);
    if (oldfurthest) {
      zinc_(Zcomputefurthest);
      qh_distplane(oldfurthest, bestfacet, &dist2);
    }
    if (!oldfurthest || dist2 < bestdist)
      qh_setappend(&bestfacet->coplanarset, point);
    else
      qh_setappend2ndlast(&bestfacet->coplanarset, point);
  }
  trace4((qh ferr, 4064, "qh_partitioncoplanar: point p%d is coplanar with facet f%d(or inside) dist %2.2g\n",
          qh_pointid(point), bestfacet->id, bestdist));
} /* partitioncoplanar */

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

  qh_partitionpoint( point, facet )
    assigns point to an outside set, coplanar set, or inside set (i.e., dropt)
    if qh.findbestnew
      uses qh_findbestnew() to search all new facets
    else
      uses qh_findbest()

  notes:
    after qh_distplane(), this and qh_findbest() are most expensive in 3-d

  design:
    find best facet for point
      (either exhaustive search of new facets or directed search from facet)
    if qh.NARROWhull
      retain coplanar and nearinside points as outside points
    if point is outside bestfacet
      if point above furthest point for bestfacet
        append point to outside set (it becomes the new furthest)
        if outside set was empty
          move bestfacet to end of qh.facet_list (i.e., after qh.facet_next)
        update bestfacet->furthestdist
      else
        append point one before end of outside set
    else if point is coplanar to bestfacet
      if keeping coplanar points or need to update qh.max_outside
        partition coplanar point into bestfacet
    else if near-inside point
      partition as coplanar point into bestfacet
    else is an inside point
      if keeping inside points
        partition as coplanar point into bestfacet
*/
void qh_partitionpoint(pointT *point, facetT *facet) {
  realT bestdist;
  boolT isoutside;
  facetT *bestfacet;
  int numpart;
#if qh_COMPUTEfurthest
  realT dist;
#endif

  if (qh findbestnew)
    bestfacet= qh_findbestnew(point, facet, &bestdist, qh BESToutside, &isoutside, &numpart);
  else
    bestfacet= qh_findbest(point, facet, qh BESToutside, qh_ISnewfacets, !qh_NOupper,
                          &bestdist, &isoutside, &numpart);
  zinc_(Ztotpartition);
  zzadd_(Zpartition, numpart);
  if (qh NARROWhull) {
    if (qh DELAUNAY && !isoutside && bestdist >= -qh MAXcoplanar)
      qh_precision("nearly incident point(narrow hull)");
    if (qh KEEPnearinside) {
      if (bestdist >= -qh NEARinside)
        isoutside= True;
    }else if (bestdist >= -qh MAXcoplanar)
      isoutside= True;
  }

  if (isoutside) {
    if (!bestfacet->outsideset
    || !qh_setlast(bestfacet->outsideset)) {
      qh_setappend(&(bestfacet->outsideset), point);
      if (!bestfacet->newfacet) {
        qh_removefacet(bestfacet);  /* make sure it's after qh facet_next */
        qh_appendfacet(bestfacet);
      }
#if !qh_COMPUTEfurthest
      bestfacet->furthestdist= bestdist;
#endif
    }else {
#if qh_COMPUTEfurthest
      zinc_(Zcomputefurthest);
      qh_distplane(oldfurthest, bestfacet, &dist);
      if (dist < bestdist)
        qh_setappend(&(bestfacet->outsideset), point);
      else
        qh_setappend2ndlast(&(bestfacet->outsideset), point);
#else
      if (bestfacet->furthestdist < bestdist) {
        qh_setappend(&(bestfacet->outsideset), point);
        bestfacet->furthestdist= bestdist;
      }else
        qh_setappend2ndlast(&(bestfacet->outsideset), point);
#endif
    }
    qh num_outside++;
    trace4((qh ferr, 4065, "qh_partitionpoint: point p%d is outside facet f%d new? %d (or narrowhull)\n",
          qh_pointid(point), bestfacet->id, bestfacet->newfacet));
  }else if (qh DELAUNAY || bestdist >= -qh MAXcoplanar) { /* for 'd', bestdist skips upperDelaunay facets */
    zzinc_(Zcoplanarpart);
    if (qh DELAUNAY)
      qh_precision("nearly incident point");
    if ((qh KEEPcoplanar + qh KEEPnearinside) || bestdist > qh max_outside)
      qh_partitioncoplanar(point, bestfacet, &bestdist);
    else {
      trace4((qh ferr, 4066, "qh_partitionpoint: point p%d is coplanar to facet f%d (dropped)\n",
          qh_pointid(point), bestfacet->id));
    }
  }else if (qh KEEPnearinside && bestdist > -qh NEARinside) {
    zinc_(Zpartnear);
    qh_partitioncoplanar(point, bestfacet, &bestdist);
  }else {
    zinc_(Zpartinside);
    trace4((qh ferr, 4067, "qh_partitionpoint: point p%d is inside all facets, closest to f%d dist %2.2g\n",
          qh_pointid(point), bestfacet->id, bestdist));
    if (qh KEEPinside)
      qh_partitioncoplanar(point, bestfacet, &bestdist);
  }
} /* partitionpoint */

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

  qh_partitionvisible( allpoints, numoutside )
    partitions points in visible facets to qh.newfacet_list
    qh.visible_list= visible facets
    for visible facets
      1st neighbor (if any) points to a horizon facet or a new facet
    if allpoints(!used),
      repartitions coplanar points

  returns:
    updates outside sets and coplanar sets of qh.newfacet_list
    updates qh.num_outside (count of outside points)

  notes:
    qh.findbest_notsharp should be clear (extra work if set)

  design:
    for all visible facets with outside set or coplanar set
      select a newfacet for visible facet
      if outside set
        partition outside set into new facets
      if coplanar set and keeping coplanar/near-inside/inside points
        if allpoints
          partition coplanar set into new facets, may be assigned outside
        else
          partition coplanar set into coplanar sets of new facets
    for each deleted vertex
      if allpoints
        partition vertex into new facets, may be assigned outside
      else
        partition vertex into coplanar sets of new facets
*/
void qh_partitionvisible(/*qh.visible_list*/ boolT allpoints, int *numoutside) {
  facetT *visible, *newfacet;
  pointT *point, **pointp;
  int coplanar=0, size;
  unsigned count;
  vertexT *vertex, **vertexp;

  if (qh ONLYmax)
    maximize_(qh MINoutside, qh max_vertex);
  *numoutside= 0;
  FORALLvisible_facets {
    if (!visible->outsideset && !visible->coplanarset)
      continue;
    newfacet= visible->f.replace;
    count= 0;
    while (newfacet && newfacet->visible) {
      newfacet= newfacet->f.replace;
      if (count++ > qh facet_id)
        qh_infiniteloop(visible);
    }
    if (!newfacet)
      newfacet= qh newfacet_list;
    if (newfacet == qh facet_tail) {
      qh_fprintf(qh ferr, 6170, "qhull precision error (qh_partitionvisible): all new facets deleted as\n        degenerate facets. Can not continue.\n");
      qh_errexit(qh_ERRprec, NULL, NULL);
    }
    if (visible->outsideset) {
      size= qh_setsize(visible->outsideset);
      *numoutside += size;
      qh num_outside -= size;
      FOREACHpoint_(visible->outsideset)
        qh_partitionpoint(point, newfacet);
    }
    if (visible->coplanarset && (qh KEEPcoplanar + qh KEEPinside + qh KEEPnearinside)) {
      size= qh_setsize(visible->coplanarset);
      coplanar += size;
      FOREACHpoint_(visible->coplanarset) {
        if (allpoints) /* not used */
          qh_partitionpoint(point, newfacet);
        else
          qh_partitioncoplanar(point, newfacet, NULL);
      }
    }
  }
  FOREACHvertex_(qh del_vertices) {
    if (vertex->point) {
      if (allpoints) /* not used */
        qh_partitionpoint(vertex->point, qh newfacet_list);
      else
        qh_partitioncoplanar(vertex->point, qh newfacet_list, NULL);
    }
  }
  trace1((qh ferr, 1043,"qh_partitionvisible: partitioned %d points from outsidesets and %d points from coplanarsets\n", *numoutside, coplanar));
} /* partitionvisible */

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

  qh_precision( reason )
    restart on precision errors if not merging and if 'QJn'
*/
void qh_precision(const char *reason) {

  if (qh ALLOWrestart && !qh PREmerge && !qh MERGEexact) {
    if (qh JOGGLEmax < REALmax/2) {
      trace0((qh ferr, 26, "qh_precision: qhull restart because of %s\n", reason));
      /* May be called repeatedly if qh->ALLOWrestart */
      longjmp(qh restartexit, qh_ERRprec);
    }
  }
} /* qh_precision */

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

  qh_printsummary( fp )
    prints summary to fp

  notes:
    not in io.c so that user_eg.c can prevent io.c from loading
    qh_printsummary and qh_countfacets must match counts

  design:
    determine number of points, vertices, and coplanar points
    print summary
*/
void qh_printsummary(FILE *fp) {
  realT ratio, outerplane, innerplane;
  float cpu;
  int size, id, nummerged, numvertices, numcoplanars= 0, nonsimplicial=0;
  int goodused;
  facetT *facet;
  const char *s;
  int numdel= zzval_(Zdelvertextot);
  int numtricoplanars= 0;

  size= qh num_points + qh_setsize(qh other_points);
  numvertices= qh num_vertices - qh_setsize(qh del_vertices);
  id= qh_pointid(qh GOODpointp);
  FORALLfacets {
    if (facet->coplanarset)
      numcoplanars += qh_setsize( facet->coplanarset);
    if (facet->good) {
      if (facet->simplicial) {
        if (facet->keepcentrum && facet->tricoplanar)
          numtricoplanars++;
      }else if (qh_setsize(facet->vertices) != qh hull_dim)
        nonsimplicial++;
    }
  }
  if (id >=0 && qh STOPcone-1 != id && -qh STOPpoint-1 != id)
    size--;
  if (qh STOPcone || qh STOPpoint)
      qh_fprintf(fp, 9288, "\nAt a premature exit due to 'TVn', 'TCn', 'TRn', or precision error with 'QJn'.");
  if (qh UPPERdelaunay)
    goodused= qh GOODvertex + qh GOODpoint + qh SPLITthresholds;
  else if (qh DELAUNAY)
    goodused= qh GOODvertex + qh GOODpoint + qh GOODthreshold;
  else
    goodused= qh num_good;
  nummerged= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
  if (qh VORONOI) {
    if (qh UPPERdelaunay)
      qh_fprintf(fp, 9289, "\n\
Furthest-site Voronoi vertices by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    else
      qh_fprintf(fp, 9290, "\n\
Voronoi diagram by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    qh_fprintf(fp, 9291, "  Number of Voronoi regions%s: %d\n",
              qh ATinfinity ? " and at-infinity" : "", numvertices);
    if (numdel)
      qh_fprintf(fp, 9292, "  Total number of deleted points due to merging: %d\n", numdel);
    if (numcoplanars - numdel > 0)
      qh_fprintf(fp, 9293, "  Number of nearly incident points: %d\n", numcoplanars - numdel);
    else if (size - numvertices - numdel > 0)
      qh_fprintf(fp, 9294, "  Total number of nearly incident points: %d\n", size - numvertices - numdel);
    qh_fprintf(fp, 9295, "  Number of%s Voronoi vertices: %d\n",
              goodused ? " 'good'" : "", qh num_good);
    if (nonsimplicial)
      qh_fprintf(fp, 9296, "  Number of%s non-simplicial Voronoi vertices: %d\n",
              goodused ? " 'good'" : "", nonsimplicial);
  }else if (qh DELAUNAY) {
    if (qh UPPERdelaunay)
      qh_fprintf(fp, 9297, "\n\
Furthest-site Delaunay triangulation by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    else
      qh_fprintf(fp, 9298, "\n\
Delaunay triangulation by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    qh_fprintf(fp, 9299, "  Number of input sites%s: %d\n",
              qh ATinfinity ? " and at-infinity" : "", numvertices);
    if (numdel)
      qh_fprintf(fp, 9300, "  Total number of deleted points due to merging: %d\n", numdel);
    if (numcoplanars - numdel > 0)
      qh_fprintf(fp, 9301, "  Number of nearly incident points: %d\n", numcoplanars - numdel);
    else if (size - numvertices - numdel > 0)
      qh_fprintf(fp, 9302, "  Total number of nearly incident points: %d\n", size - numvertices - numdel);
    qh_fprintf(fp, 9303, "  Number of%s Delaunay regions: %d\n",
              goodused ? " 'good'" : "", qh num_good);
    if (nonsimplicial)
      qh_fprintf(fp, 9304, "  Number of%s non-simplicial Delaunay regions: %d\n",
              goodused ? " 'good'" : "", nonsimplicial);
  }else if (qh HALFspace) {
    qh_fprintf(fp, 9305, "\n\
Halfspace intersection by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    qh_fprintf(fp, 9306, "  Number of halfspaces: %d\n", size);
    qh_fprintf(fp, 9307, "  Number of non-redundant halfspaces: %d\n", numvertices);
    if (numcoplanars) {
      if (qh KEEPinside && qh KEEPcoplanar)
        s= "similar and redundant";
      else if (qh KEEPinside)
        s= "redundant";
      else
        s= "similar";
      qh_fprintf(fp, 9308, "  Number of %s halfspaces: %d\n", s, numcoplanars);
    }
    qh_fprintf(fp, 9309, "  Number of intersection points: %d\n", qh num_facets - qh num_visible);
    if (goodused)
      qh_fprintf(fp, 9310, "  Number of 'good' intersection points: %d\n", qh num_good);
    if (nonsimplicial)
      qh_fprintf(fp, 9311, "  Number of%s non-simplicial intersection points: %d\n",
              goodused ? " 'good'" : "", nonsimplicial);
  }else {
    qh_fprintf(fp, 9312, "\n\
Convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
    qh_fprintf(fp, 9313, "  Number of vertices: %d\n", numvertices);
    if (numcoplanars) {
      if (qh KEEPinside && qh KEEPcoplanar)
        s= "coplanar and interior";
      else if (qh KEEPinside)
        s= "interior";
      else
        s= "coplanar";
      qh_fprintf(fp, 9314, "  Number of %s points: %d\n", s, numcoplanars);
    }
    qh_fprintf(fp, 9315, "  Number of facets: %d\n", qh num_facets - qh num_visible);
    if (goodused)
      qh_fprintf(fp, 9316, "  Number of 'good' facets: %d\n", qh num_good);
    if (nonsimplicial)
      qh_fprintf(fp, 9317, "  Number of%s non-simplicial facets: %d\n",
              goodused ? " 'good'" : "", nonsimplicial);
  }
  if (numtricoplanars)
      qh_fprintf(fp, 9318, "  Number of triangulated facets: %d\n", numtricoplanars);
  qh_fprintf(fp, 9319, "\nStatistics for: %s | %s",
                      qh rbox_command, qh qhull_command);
  if (qh ROTATErandom != INT_MIN)
    qh_fprintf(fp, 9320, " QR%d\n\n", qh ROTATErandom);
  else
    qh_fprintf(fp, 9321, "\n\n");
  qh_fprintf(fp, 9322, "  Number of points processed: %d\n", zzval_(Zprocessed));
  qh_fprintf(fp, 9323, "  Number of hyperplanes created: %d\n", zzval_(Zsetplane));
  if (qh DELAUNAY)
    qh_fprintf(fp, 9324, "  Number of facets in hull: %d\n", qh num_facets - qh num_visible);
  qh_fprintf(fp, 9325, "  Number of distance tests for qhull: %d\n", zzval_(Zpartition)+
      zzval_(Zpartitionall)+zzval_(Znumvisibility)+zzval_(Zpartcoplanar));
#if 0  /* NOTE: must print before printstatistics() */
  {realT stddev, ave;
  qh_fprintf(fp, 9326, "  average new facet balance: %2.2g\n",
          wval_(Wnewbalance)/zval_(Zprocessed));
  stddev= qh_stddev(zval_(Zprocessed), wval_(Wnewbalance),
                                 wval_(Wnewbalance2), &ave);
  qh_fprintf(fp, 9327, "  new facet standard deviation: %2.2g\n", stddev);
  qh_fprintf(fp, 9328, "  average partition balance: %2.2g\n",
          wval_(Wpbalance)/zval_(Zpbalance));
  stddev= qh_stddev(zval_(Zpbalance), wval_(Wpbalance),
                                 wval_(Wpbalance2), &ave);
  qh_fprintf(fp, 9329, "  partition standard deviation: %2.2g\n", stddev);
  }
#endif
  if (nummerged) {
    qh_fprintf(fp, 9330,"  Number of distance tests for merging: %d\n",zzval_(Zbestdist)+
          zzval_(Zcentrumtests)+zzval_(Zdistconvex)+zzval_(Zdistcheck)+
          zzval_(Zdistzero));
    qh_fprintf(fp, 9331,"  Number of distance tests for checking: %d\n",zzval_(Zcheckpart));
    qh_fprintf(fp, 9332,"  Number of merged facets: %d\n", nummerged);
  }
  if (!qh RANDOMoutside && qh QHULLfinished) {
    cpu= (float)qh hulltime;
    cpu /= (float)qh_SECticks;
    wval_(Wcpu)= cpu;
    qh_fprintf(fp, 9333, "  CPU seconds to compute hull (after input): %2.4g\n", cpu);
  }
  if (qh RERUN) {
    if (!qh PREmerge && !qh MERGEexact)
      qh_fprintf(fp, 9334, "  Percentage of runs with precision errors: %4.1f\n",
           zzval_(Zretry)*100.0/qh build_cnt);  /* careful of order */
  }else if (qh JOGGLEmax < REALmax/2) {
    if (zzval_(Zretry))
      qh_fprintf(fp, 9335, "  After %d retries, input joggled by: %2.2g\n",
         zzval_(Zretry), qh JOGGLEmax);
    else
      qh_fprintf(fp, 9336, "  Input joggled by: %2.2g\n", qh JOGGLEmax);
  }
  if (qh totarea != 0.0)
    qh_fprintf(fp, 9337, "  %s facet area:   %2.8g\n",
            zzval_(Ztotmerge) ? "Approximate" : "Total", qh totarea);
  if (qh totvol != 0.0)
    qh_fprintf(fp, 9338, "  %s volume:       %2.8g\n",
            zzval_(Ztotmerge) ? "Approximate" : "Total", qh totvol);
  if (qh MERGING) {
    qh_outerinner(NULL, &outerplane, &innerplane);
    if (outerplane > 2 * qh DISTround) {
      qh_fprintf(fp, 9339, "  Maximum distance of %spoint above facet: %2.2g",
            (qh QHULLfinished ? "" : "merged "), outerplane);
      ratio= outerplane/(qh ONEmerge + qh DISTround);
      /* don't report ratio if MINoutside is large */
      if (ratio > 0.05 && 2* qh ONEmerge > qh MINoutside && qh JOGGLEmax > REALmax/2)
        qh_fprintf(fp, 9340, " (%.1fx)\n", ratio);
      else
        qh_fprintf(fp, 9341, "\n");
    }
    if (innerplane < -2 * qh DISTround) {
      qh_fprintf(fp, 9342, "  Maximum distance of %svertex below facet: %2.2g",
            (qh QHULLfinished ? "" : "merged "), innerplane);
      ratio= -innerplane/(qh ONEmerge+qh DISTround);
      if (ratio > 0.05 && qh JOGGLEmax > REALmax/2)
        qh_fprintf(fp, 9343, " (%.1fx)\n", ratio);
      else
        qh_fprintf(fp, 9344, "\n");
    }
  }
  qh_fprintf(fp, 9345, "\n");
} /* printsummary */


text:
import { select } from 'd3-selection';
import { line } from 'd3-shape';
import { dataJoin as _dataJoin, isTransition } from '@d3fc/d3fc-data-join';
import { ticksArrayForAxis, tickFormatterForAxis } from './axisTickUtils';

const identity = d => d;

export const axisBase = (orient, scale, custom = {}) => {

    let tickArguments = [10];
    let tickValues = null;
    let decorate = () => {};
    let tickFormat = null;
    let tickSizeOuter = 6;
    let tickSizeInner = 6;
    let tickPadding = 3;

    const svgDomainLine = line();

    const dataJoin = _dataJoin('g', 'tick')
        .key(identity);

    const domainPathDataJoin = _dataJoin('path', 'domain');

    const defaultLabelOffset = () => ({ offset: [0, tickSizeInner + tickPadding] });
    const defaultTickPath = () => ({ path: [[0, 0], [0, tickSizeInner]] });

    const labelOffset = custom.labelOffset || defaultLabelOffset;
    const tickPath = custom.tickPath || defaultTickPath;

    // returns a function that creates a translation based on
    // the bound data
    const containerTranslate = (scale, trans) => {
        let offset = 0;
        if (scale.bandwidth) {
            offset = scale.bandwidth() / 2;
            if (scale.round()) {
                offset = Math.round(offset);
            }
        }
        return d => trans(scale(d) + offset, 0);
    };

    const translate = (x, y) =>
        isVertical()
            ? `translate(${y}, ${x})`
            : `translate(${x}, ${y})`;

    const pathTranspose = (arr) =>
        isVertical()
           ? arr.map(d => [d[1], d[0]])
           : arr;

    const isVertical = () =>
        orient === 'left' || orient === 'right';

    const axis = (selection) => {

        if (isTransition(selection)) {
            dataJoin.transition(selection);
            domainPathDataJoin.transition(selection);
        }

        selection.each((data, index, group) => {

            const element = group[index];

            const container = select(element);
            if (!element.__scale__) {
                container
                    .attr('fill', 'none')
                    .attr('font-size', 10)
                    .attr('font-family', 'sans-serif')
                    .attr('text-anchor', orient === 'right' ? 'start' : orient === 'left' ? 'end' : 'middle');
            }

            // Stash a snapshot of the new scale, and retrieve the old snapshot.
            const scaleOld = element.__scale__ || scale;
            element.__scale__ = scale.copy();

            const ticksArray = ticksArrayForAxis(axis);
            const tickFormatter = tickFormatterForAxis(axis);
            const sign = orient === 'bottom' || orient === 'right' ? 1 : -1;
            const withSign = ([x, y]) => ([x, sign * y]);

            // add the domain line
            const range = scale.range();
            const domainPathData = pathTranspose([
                [range[0], sign * tickSizeOuter],
                [range[0], 0],
                [range[1], 0],
                [range[1], sign * tickSizeOuter]
            ]);

            const domainLine = domainPathDataJoin(container, [data]);

            domainLine.enter()
                .attr('stroke', '#000');

            domainLine.attr('d', svgDomainLine(domainPathData));

            const g = dataJoin(container, ticksArray);

            const labelOffsets = ticksArray.map((d, i) => labelOffset(d, i, ticksArray));
            const tickPaths = ticksArray.map((d, i) => tickPath(d, i, ticksArray));

            // enter
            g.enter()
                .attr('transform', containerTranslate(scaleOld, translate))
                .append('path')
                .attr('stroke', '#000');

            g.enter()
                .append('text')
                .attr('transform', (d, i) => translate(...withSign(labelOffsets[i].offset)))
                .attr('fill', '#000');

            // exit
            g.exit()
                .attr('transform', containerTranslate(scale, translate));

            // update
            g.select('path')
                .attr('visibility', (d, i) => tickPaths[i].hidden && 'hidden')
                .attr('d',
                    (d, i) => svgDomainLine(pathTranspose(tickPaths[i].path.map(withSign)))
                );

            g.select('text')
                .attr('visibility', (d, i) => labelOffsets[i].hidden && 'hidden')
                .attr('transform', (d, i) => translate(...withSign(labelOffsets[i].offset)))
                .attr('dy', () => {
                    let offset = '0em';
                    if (isVertical()) {
                        offset = '0.32em';
                    } else if (orient === 'bottom') {
                        offset = '0.71em';
                    }
                    return offset;
                })
               .text(tickFormatter);

            g.attr('transform', containerTranslate(scale, translate));

            decorate(g, data, index);
        });
    };

    axis.tickFormat = (...args) => {
        if (!args.length) {
            return tickFormat;
        }
        tickFormat = args[0];
        return axis;
    };

    axis.tickSize = (...args) => {
        if (!args.length) {
            return tickSizeInner;
        }
        tickSizeInner = tickSizeOuter = Number(args[0]);
        return axis;
    };

    axis.tickSizeInner = (...args) => {
        if (!args.length) {
            return tickSizeInner;
        }
        tickSizeInner = Number(args[0]);
        return axis;
    };

    axis.tickSizeOuter = (...args) => {
        if (!args.length) {
            return tickSizeOuter;
        }
        tickSizeOuter = Number(args[0]);
        return axis;
    };

    axis.tickPadding = (...args) => {
        if (!args.length) {
            return tickPadding;
        }
        tickPadding = args[0];
        return axis;
    };

    axis.decorate = (...args) => {
        if (!args.length) {
            return decorate;
        }
        decorate = args[0];
        return axis;
    };

    axis.scale = (...args) => {
        if (!args.length) {
            return scale;
        }
        scale = args[0];
        return axis;
    };

    axis.ticks = (...args) => {
        tickArguments = [...args];
        return axis;
    };

    axis.tickArguments = (...args) => {
        if (!args.length) {
            return tickArguments !== null ? tickArguments.slice() : null;
        }
        tickArguments = args[0] == null ? [] : [...args[0]];
        return axis;
    };

    axis.tickValues = (...args) => {
        if (!args.length) {
            return tickValues !== null ? tickValues.slice() : null;
        }
        tickValues = args[0] == null ? [] : [...args[0]];
        return axis;
    };

    axis.orient = () => orient;

    return axis;
};

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hc.client5.http.impl.cache;

import org.apache.hc.core5.http.HttpResponse;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;

public class ResponseEquivalent<T extends HttpResponse> implements ArgumentMatcher<T> {

    private final T expected;

    public ResponseEquivalent(final T expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(final T argument) {
        if (argument == null) {
            return false;
        }
        return HttpTestUtils.equivalent(expected, argument);
    }

    public static <T extends HttpResponse> T eq(final T response) {
        return ArgumentMatchers.argThat(new ResponseEquivalent<>(response));
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.orc;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.trino.orc.metadata.ColumnMetadata;
import io.trino.orc.metadata.OrcColumnId;
import io.trino.orc.metadata.statistics.BloomFilter;
import io.trino.orc.metadata.statistics.BooleanStatistics;
import io.trino.orc.metadata.statistics.ColumnStatistics;
import io.trino.orc.metadata.statistics.RangeStatistics;
import io.trino.spi.predicate.Domain;
import io.trino.spi.predicate.Range;
import io.trino.spi.predicate.ValueSet;
import io.trino.spi.type.CharType;
import io.trino.spi.type.DateType;
import io.trino.spi.type.DecimalType;
import io.trino.spi.type.LongTimestamp;
import io.trino.spi.type.LongTimestampWithTimeZone;
import io.trino.spi.type.TimeType;
import io.trino.spi.type.Timestamps;
import io.trino.spi.type.Type;
import io.trino.spi.type.VarbinaryType;
import io.trino.spi.type.VarcharType;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

import static com.google.common.base.MoreObjects.toStringHelper;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.Chars.truncateToLengthAndTrimSpaces;
import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static io.trino.spi.type.DateTimeEncoding.unpackMillisUtc;
import static io.trino.spi.type.DateType.DATE;
import static io.trino.spi.type.Decimals.encodeUnscaledValue;
import static io.trino.spi.type.Decimals.isLongDecimal;
import static io.trino.spi.type.Decimals.isShortDecimal;
import static io.trino.spi.type.Decimals.rescale;
import static io.trino.spi.type.DoubleType.DOUBLE;
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.RealType.REAL;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TimeZoneKey.UTC_KEY;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MICROS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MILLIS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_NANOS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MICROS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_NANOS;
import static io.trino.spi.type.Timestamps.MICROSECONDS_PER_MILLISECOND;
import static io.trino.spi.type.TinyintType.TINYINT;
import static java.lang.Float.floatToRawIntBits;
import static java.lang.Float.intBitsToFloat;
import static java.lang.Math.floorDiv;
import static java.util.Objects.requireNonNull;

public class TupleDomainOrcPredicate
        implements OrcPredicate
{
    private final List<ColumnDomain> columnDomains;
    private final boolean orcBloomFiltersEnabled;

    public static TupleDomainOrcPredicateBuilder builder()
    {
        return new TupleDomainOrcPredicateBuilder();
    }

    private TupleDomainOrcPredicate(List<ColumnDomain> columnDomains, boolean orcBloomFiltersEnabled)
    {
        this.columnDomains = ImmutableList.copyOf(requireNonNull(columnDomains, "columnDomains is null"));
        this.orcBloomFiltersEnabled = orcBloomFiltersEnabled;
    }

    @Override
    public boolean matches(long numberOfRows, ColumnMetadata<ColumnStatistics> allColumnStatistics)
    {
        for (ColumnDomain column : columnDomains) {
            ColumnStatistics columnStatistics = allColumnStatistics.get(column.getColumnId());
            if (columnStatistics == null) {
                // no statistics for this column, so we can't exclude this section
                continue;
            }

            if (!columnOverlaps(column.getDomain(), numberOfRows, columnStatistics)) {
                return false;
            }
        }

        // this section was not excluded
        return true;
    }

    private boolean columnOverlaps(Domain predicateDomain, long numberOfRows, ColumnStatistics columnStatistics)
    {
        Domain stripeDomain = getDomain(predicateDomain.getType(), numberOfRows, columnStatistics);
        if (!stripeDomain.overlaps(predicateDomain)) {
            // there is no overlap between the predicate and this column
            return false;
        }

        // if bloom filters are not enabled, we cannot restrict the range overlap
        if (!orcBloomFiltersEnabled) {
            return true;
        }

        // if there an overlap in null values, the bloom filter cannot eliminate the overlap
        if (predicateDomain.isNullAllowed() && stripeDomain.isNullAllowed()) {
            return true;
        }

        // extract the discrete values from the predicate
        Optional<Collection<Object>> discreteValues = extractDiscreteValues(predicateDomain.getValues());
        if (discreteValues.isEmpty()) {
            // values are not discrete, so we can't exclude this section
            return true;
        }

        BloomFilter bloomFilter = columnStatistics.getBloomFilter();
        if (bloomFilter == null) {
            // no bloom filter so we can't exclude this section
            return true;
        }

        // if none of the discrete predicate values are found in the bloom filter, there is no overlap and the section should be skipped
        return discreteValues.get().stream().anyMatch(value -> checkInBloomFilter(bloomFilter, value, stripeDomain.getType()));
    }

    private static Optional<Collection<Object>> extractDiscreteValues(ValueSet valueSet)
    {
        if (!valueSet.isDiscreteSet()) {
            return Optional.empty();
        }

        return Optional.of(valueSet.getDiscreteSet());
    }

    // checks whether a value part of the effective predicate is likely to be part of this bloom filter
    @VisibleForTesting
    public static boolean checkInBloomFilter(BloomFilter bloomFilter, Object predicateValue, Type sqlType)
    {
        if (sqlType == TINYINT || sqlType == SMALLINT || sqlType == INTEGER || sqlType == BIGINT || sqlType == DATE) {
            return bloomFilter.testLong(((Number) predicateValue).longValue());
        }

        if (sqlType == DOUBLE) {
            return bloomFilter.testDouble((Double) predicateValue);
        }

        if (sqlType == REAL) {
            return bloomFilter.testFloat(intBitsToFloat(((Number) predicateValue).intValue()));
        }

        if (sqlType instanceof VarcharType || sqlType instanceof VarbinaryType) {
            return bloomFilter.testSlice(((Slice) predicateValue));
        }

        // Bloom filters for timestamps are truncated to millis
        if (sqlType.equals(TIMESTAMP_MILLIS)) {
            return bloomFilter.testLong(((Number) predicateValue).longValue());
        }
        if (sqlType.equals(TIMESTAMP_MICROS)) {
            return bloomFilter.testLong(floorDiv(((Number) predicateValue).longValue(), MICROSECONDS_PER_MILLISECOND));
        }
        if (sqlType.equals(TIMESTAMP_NANOS)) {
            return bloomFilter.testLong(floorDiv(((LongTimestamp) predicateValue).getEpochMicros(), MICROSECONDS_PER_MILLISECOND));
        }
        if (sqlType.equals(TIMESTAMP_TZ_MILLIS)) {
            return bloomFilter.testLong(unpackMillisUtc(((Number) predicateValue).longValue()));
        }
        if (sqlType.equals(TIMESTAMP_TZ_MICROS) || sqlType.equals(TIMESTAMP_TZ_NANOS)) {
            return bloomFilter.testLong(((LongTimestampWithTimeZone) predicateValue).getEpochMillis());
        }

        // todo support DECIMAL, and CHAR
        return true;
    }

    @VisibleForTesting
    public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics)
    {
        if (rowCount == 0) {
            return Domain.none(type);
        }

        if (columnStatistics == null) {
            return Domain.all(type);
        }

        if (columnStatistics.hasNumberOfValues() && columnStatistics.getNumberOfValues() == 0) {
            return Domain.onlyNull(type);
        }

        boolean hasNullValue = columnStatistics.getNumberOfValues() != rowCount;

        if (type instanceof TimeType && columnStatistics.getIntegerStatistics() != null) {
            // This is the representation of TIME used by Iceberg
            return createDomain(type, hasNullValue, columnStatistics.getIntegerStatistics(), value -> ((long) value) * Timestamps.PICOSECONDS_PER_MICROSECOND);
        }
        if (type.getJavaType() == boolean.class && columnStatistics.getBooleanStatistics() != null) {
            BooleanStatistics booleanStatistics = columnStatistics.getBooleanStatistics();

            boolean hasTrueValues = (booleanStatistics.getTrueValueCount() != 0);
            boolean hasFalseValues = (columnStatistics.getNumberOfValues() != booleanStatistics.getTrueValueCount());
            if (hasTrueValues && hasFalseValues) {
                return Domain.all(BOOLEAN);
            }
            if (hasTrueValues) {
                return Domain.create(ValueSet.of(BOOLEAN, true), hasNullValue);
            }
            if (hasFalseValues) {
                return Domain.create(ValueSet.of(BOOLEAN, false), hasNullValue);
            }
        }
        else if (isShortDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> rescale(value, (DecimalType) type).unscaledValue().longValue());
        }
        else if (isLongDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> encodeUnscaledValue(rescale(value, (DecimalType) type).unscaledValue()));
        }
        else if (type instanceof CharType && columnStatistics.getStringStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getStringStatistics(), value -> truncateToLengthAndTrimSpaces(value, type));
        }
        else if (type instanceof VarcharType && columnStatistics.getStringStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getStringStatistics());
        }
        else if (type instanceof DateType && columnStatistics.getDateStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getDateStatistics(), value -> (long) value);
        }
        else if ((type.equals(TIMESTAMP_MILLIS) || type.equals(TIMESTAMP_MICROS)) && columnStatistics.getTimestampStatistics() != null) {
            // ORC timestamp statistics are truncated to millisecond precision, regardless of the precision of the actual data column.
            // Since that can cause some column values to fall outside the stats range, here we are creating a tuple domain predicate
            // that ensures inclusion of all values.  Note that we are adding a full millisecond to account for the fact that Trino rounds
            // timestamps. For example, the stats for timestamp 2020-09-22 12:34:56.678910 are truncated to 2020-09-22 12:34:56.678.
            // If Trino is using millisecond precision, the timestamp gets rounded to the next millisecond (2020-09-22 12:34:56.679), so the
            // upper bound of the domain we create must be adjusted accordingly, to includes the rounded timestamp.
            return createDomain(
                    type,
                    hasNullValue,
                    columnStatistics.getTimestampStatistics(),
                    min -> min * MICROSECONDS_PER_MILLISECOND,
                    max -> (max + 1) * MICROSECONDS_PER_MILLISECOND);
        }
        else if (type.equals(TIMESTAMP_NANOS) && columnStatistics.getTimestampStatistics() != null) {
            return createDomain(
                    type,
                    hasNullValue,
                    columnStatistics.getTimestampStatistics(),
                    min -> new LongTimestamp(min * MICROSECONDS_PER_MILLISECOND, 0),
                    max -> new LongTimestamp((max + 1) * MICROSECONDS_PER_MILLISECOND, 0));
        }
        else if (type.equals(TIMESTAMP_TZ_MILLIS) && columnStatistics.getTimestampStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getTimestampStatistics(), value -> packDateTimeWithZone(value, UTC_KEY));
        }
        else if (type.equals(TIMESTAMP_TZ_MICROS) && (columnStatistics.getTimestampStatistics() != null)) {
            return createDomain(
                    type,
                    hasNullValue,
                    columnStatistics.getTimestampStatistics(),
                    min -> LongTimestampWithTimeZone.fromEpochMillisAndFraction(min, 0, UTC_KEY),
                    max -> LongTimestampWithTimeZone.fromEpochMillisAndFraction(max, 999_000_000, UTC_KEY));
        }
        else if (type.equals(TIMESTAMP_TZ_NANOS) && columnStatistics.getTimestampStatistics() != null) {
            return createDomain(
                    type,
                    hasNullValue,
                    columnStatistics.getTimestampStatistics(),
                    min -> LongTimestampWithTimeZone.fromEpochMillisAndFraction(min, 0, UTC_KEY),
                    max -> LongTimestampWithTimeZone.fromEpochMillisAndFraction(max, 999_999_000, UTC_KEY));
        }
        else if (type.getJavaType() == long.class && columnStatistics.getIntegerStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getIntegerStatistics());
        }
        else if (type.getJavaType() == double.class && columnStatistics.getDoubleStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics());
        }
        else if (REAL.equals(type) && columnStatistics.getDoubleStatistics() != null) {
            return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics(), value -> (long) floatToRawIntBits(value.floatValue()));
        }
        return Domain.create(ValueSet.all(type), hasNullValue);
    }

    private static <T extends Comparable<T>> Domain createDomain(Type type, boolean hasNullValue, RangeStatistics<T> rangeStatistics)
    {
        return createDomain(type, hasNullValue, rangeStatistics, value -> value);
    }

    private static <F, T extends Comparable<T>> Domain createDomain(Type type, boolean hasNullValue, RangeStatistics<F> rangeStatistics, Function<F, T> function)
    {
        return createDomain(type, hasNullValue, rangeStatistics, function, function);
    }

    private static <F, T extends Comparable<T>> Domain createDomain(Type type, boolean hasNullValue, RangeStatistics<F> rangeStatistics, Function<F, T> minFunction, Function<F, T> maxFunction)
    {
        F min = rangeStatistics.getMin();
        F max = rangeStatistics.getMax();

        if (min != null && max != null) {
            return Domain.create(ValueSet.ofRanges(Range.range(type, minFunction.apply(min), true, maxFunction.apply(max), true)), hasNullValue);
        }
        if (max != null) {
            return Domain.create(ValueSet.ofRanges(Range.lessThanOrEqual(type, maxFunction.apply(max))), hasNullValue);
        }
        if (min != null) {
            return Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(type, minFunction.apply(min))), hasNullValue);
        }
        return Domain.create(ValueSet.all(type), hasNullValue);
    }

    public static class TupleDomainOrcPredicateBuilder
    {
        private final List<ColumnDomain> columns = new ArrayList<>();
        private boolean bloomFiltersEnabled;

        public TupleDomainOrcPredicateBuilder addColumn(OrcColumnId columnId, Domain domain)
        {
            requireNonNull(domain, "domain is null");
            columns.add(new ColumnDomain(columnId, domain));
            return this;
        }

        public TupleDomainOrcPredicateBuilder setBloomFiltersEnabled(boolean bloomFiltersEnabled)
        {
            this.bloomFiltersEnabled = bloomFiltersEnabled;
            return this;
        }

        public TupleDomainOrcPredicate build()
        {
            return new TupleDomainOrcPredicate(columns, bloomFiltersEnabled);
        }
    }

    private static class ColumnDomain
    {
        private final OrcColumnId columnId;
        private final Domain domain;

        public ColumnDomain(OrcColumnId columnId, Domain domain)
        {
            this.columnId = requireNonNull(columnId, "columnId is null");
            this.domain = requireNonNull(domain, "domain is null");
        }

        public OrcColumnId getColumnId()
        {
            return columnId;
        }

        public Domain getDomain()
        {
            return domain;
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("columnId", columnId)
                    .add("domain", domain)
                    .toString();
        }
    }
}


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2017 Treasure Data Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef FLB_OUT_LIB
#define FLB_OUT_LIB

enum {
    FLB_OUT_LIB_FMT_MSGPACK = 0,
    FLB_OUT_LIB_FMT_JSON,
    FLB_OUT_LIB_FMT_ERROR,
};

#define FLB_FMT_STR_MSGPACK "msgpack"
#define FLB_FMT_STR_JSON    "json"

struct flb_out_lib_config{
    int format;
    int (*user_callback)(void* data, size_t size);
};

#endif


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

namespace Aws
{
namespace EC2
{
namespace Model
{
  enum class VpnEcmpSupportValue
  {
    NOT_SET,
    enable,
    disable
  };

namespace VpnEcmpSupportValueMapper
{
AWS_EC2_API VpnEcmpSupportValue GetVpnEcmpSupportValueForName(const Aws::String& name);

AWS_EC2_API Aws::String GetNameForVpnEcmpSupportValue(VpnEcmpSupportValue value);
} // namespace VpnEcmpSupportValueMapper
} // namespace Model
} // namespace EC2
} // namespace Aws


text:
namespace {

void NotifyEvent(base::WaitableEvent* event) {
  event->Signal();
}

}  // namespace

// TestHandler::CompletionState

TestHandler::CompletionState::CompletionState(int total)
    : total_(total),
      count_(0),
      event_(true, false) {
}

void TestHandler::CompletionState::TestComplete() {
  if (++count_ == total_) {
    count_ = 0;

    // Signal that the test is now complete. Do not access any object members
    // after this call because |this| might be deleted.
    event_.Signal();
  }
}

void TestHandler::CompletionState::WaitForTests() {
  // Wait for the test to complete
  event_.Wait();

  // Reset the event so the same test can be executed again.
  event_.Reset();
}

// TestHandler::Collection

TestHandler::Collection::Collection(CompletionState* completion_state)
    : completion_state_(completion_state) {
  EXPECT_TRUE(completion_state_);
}

void TestHandler::Collection::AddTestHandler(TestHandler* test_handler) {
  EXPECT_EQ(test_handler->completion_state_, completion_state_);
  handler_list_.push_back(test_handler);
}

void TestHandler::Collection::ExecuteTests() {
  EXPECT_GT(handler_list_.size(), 0UL);

  TestHandlerList::const_iterator it;

  it = handler_list_.begin();
  for (; it != handler_list_.end(); ++it)
    (*it)->SetupTest();

  completion_state_->WaitForTests();

  it = handler_list_.begin();
  for (; it != handler_list_.end(); ++it)
    (*it)->RunTest();

  completion_state_->WaitForTests();
}

// TestHandler::UIThreadHelper

TestHandler::UIThreadHelper::UIThreadHelper()
    : weak_ptr_factory_(this) {
}

void TestHandler::UIThreadHelper::PostTask(const base::Closure& task) {
  EXPECT_UI_THREAD();
  CefPostTask(
      TID_UI,
      base::Bind(&UIThreadHelper::TaskHelper,
                 weak_ptr_factory_.GetWeakPtr(), task));
}

void TestHandler::UIThreadHelper::PostDelayedTask(
    const base::Closure& task, int delay_ms) {
  EXPECT_UI_THREAD();
  CefPostDelayedTask(
      TID_UI,
      base::Bind(&UIThreadHelper::TaskHelper,
                 weak_ptr_factory_.GetWeakPtr(), task),
      delay_ms);
}

void TestHandler::UIThreadHelper::TaskHelper(const base::Closure& task) {
  EXPECT_UI_THREAD();
  task.Run();
}

// TestHandler

int TestHandler::browser_count_ = 0;

TestHandler::TestHandler(CompletionState* completion_state)
    : first_browser_id_(0),
      signal_completion_when_all_browsers_close_(true),
      destroy_event_(NULL),
      destroy_test_expected_(true),
      destroy_test_called_(false) {
  if (completion_state) {
    completion_state_ = completion_state;
    completion_state_owned_ = false;
  } else {
    completion_state_ = new CompletionState(1);
    completion_state_owned_ = true;
  }
}

TestHandler::~TestHandler() {
  DCHECK(!ui_thread_helper_.get());
  if (destroy_test_expected_)
    EXPECT_TRUE(destroy_test_called_);
  else
    EXPECT_FALSE(destroy_test_called_);
  EXPECT_TRUE(browser_map_.empty());

  if (completion_state_owned_)
    delete completion_state_;

  if (destroy_event_)
    destroy_event_->Signal();
}

void TestHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
  EXPECT_UI_THREAD();

  browser_count_++;

  if (!browser->IsPopup()) {
    // Keep non-popup browsers.
    const int browser_id = browser->GetIdentifier();
    EXPECT_EQ(browser_map_.find(browser_id), browser_map_.end());
    if (browser_map_.empty()) {
      first_browser_id_ = browser_id;
      first_browser_ = browser;
    }
    browser_map_.insert(std::make_pair(browser_id, browser));
  }
}

void TestHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
  EXPECT_UI_THREAD();

  if (!browser->IsPopup()) {
    // Free the browser pointer so that the browser can be destroyed.
    const int browser_id = browser->GetIdentifier();
    BrowserMap::iterator it = browser_map_.find(browser_id);
    EXPECT_NE(it, browser_map_.end());
    browser_map_.erase(it);

    if (browser_id == first_browser_id_) {
      first_browser_id_ = 0;
      first_browser_ = NULL;
    }

    if (browser_map_.empty() &&
        signal_completion_when_all_browsers_close_) {
      // Signal that the test is now complete.
      TestComplete();
    }
  }

  browser_count_--;
}

CefRefPtr<CefResourceHandler> TestHandler::GetResourceHandler(
      CefRefPtr<CefBrowser> browser,
      CefRefPtr<CefFrame> frame,
      CefRefPtr<CefRequest> request) {
  EXPECT_IO_THREAD();

  if (resource_map_.size() > 0) {
    CefString url = request->GetURL();

    // Ignore the query component, if any.
    std::string urlStr = url;
    size_t idx = urlStr.find('?');
    if (idx > 0)
       urlStr = urlStr.substr(0, idx);

    ResourceMap::const_iterator it = resource_map_.find(urlStr);
    if (it != resource_map_.end()) {
      // Return the previously mapped resource
      CefRefPtr<CefStreamReader> stream =
          CefStreamReader::CreateForData(
              static_cast<void*>(const_cast<char*>(it->second.first.c_str())),
              it->second.first.length());
      return new CefStreamResourceHandler(it->second.second, stream);
    }
  }

  return NULL;
}

CefRefPtr<CefBrowser> TestHandler::GetBrowser() {
  return first_browser_;
}

int TestHandler::GetBrowserId() {
  return first_browser_id_;
}

void TestHandler::GetAllBrowsers(BrowserMap* map) {
  EXPECT_UI_THREAD();
  EXPECT_TRUE(map);
  *map = browser_map_;
}

void TestHandler::ExecuteTest() {
  EXPECT_EQ(completion_state_->total(), 1);

  // Reset any state from the previous run.
  if (destroy_test_called_)
    destroy_test_called_ = false;

  // Run the test.
  RunTest();

  // Wait for the test to complete.
  completion_state_->WaitForTests();
}

void TestHandler::SetupComplete() {
  // Signal that the test setup is complete.
  completion_state_->TestComplete();
}

void TestHandler::DestroyTest() {
  if (!CefCurrentlyOn(TID_UI)) {
    CefPostTask(TID_UI, base::Bind(&TestHandler::DestroyTest, this));
    return;
  }

  EXPECT_TRUE(destroy_test_expected_);
  if (destroy_test_called_)
    return;
  destroy_test_called_ = true;

  if (!browser_map_.empty()) {
    // Use a copy of the map since the original may be modified while we're
    // iterating.
    BrowserMap browser_map = browser_map_;

    // Tell all non-popup browsers to close.
    BrowserMap::const_iterator it = browser_map.begin();
    for (; it != browser_map.end(); ++it)
      it->second->GetHost()->CloseBrowser(false);
  }

  if (ui_thread_helper_.get())
    ui_thread_helper_.reset(NULL);
}

void TestHandler::OnTestTimeout(int timeout_ms) {
  EXPECT_UI_THREAD();
  EXPECT_TRUE(false) << "Test timed out after " << timeout_ms << "ms";
  DestroyTest();
}

void TestHandler::CreateBrowser(
    const CefString& url,
    CefRefPtr<CefRequestContext> request_context) {
  CefWindowInfo windowInfo;
  CefBrowserSettings settings;
#if defined(OS_WIN)
  windowInfo.SetAsPopup(NULL, "CefUnitTest");
  windowInfo.style |= WS_VISIBLE;
#endif
  PopulateBrowserSettings(&settings);
  CefBrowserHost::CreateBrowser(windowInfo, this, url, settings,
                                request_context);
}

void TestHandler::AddResource(const std::string& url,
                              const std::string& content,
                              const std::string& mimeType) {
  if (!CefCurrentlyOn(TID_IO)) {
    CefPostTask(TID_IO,
        base::Bind(&TestHandler::AddResource, this, url, content, mimeType));
    return;
  }

  // Ignore the query component, if any.
  std::string urlStr = url;
  size_t idx = urlStr.find('?');
  if (idx > 0)
     urlStr = urlStr.substr(0, idx);

  resource_map_.insert(
      std::make_pair(urlStr, std::make_pair(content, mimeType)));
}

void TestHandler::ClearResources() {
  if (!CefCurrentlyOn(TID_IO)) {
    CefPostTask(TID_IO, base::Bind(&TestHandler::ClearResources, this));
    return;
  }

  resource_map_.clear();
}

void TestHandler::SetTestTimeout(int timeout_ms) {
  if (!CefCurrentlyOn(TID_UI)) {
    CefPostTask(TID_UI, base::Bind(&TestHandler::SetTestTimeout, this,
                timeout_ms));
    return;
  }

  if (CefCommandLine::GetGlobalCommandLine()->HasSwitch("disable-test-timeout"))
    return;

  // Use a weak reference to |this| via UIThreadHelper so that the TestHandler
  // can be destroyed before the timeout expires.
  GetUIThreadHelper()->PostDelayedTask(
      base::Bind(&TestHandler::OnTestTimeout, base::Unretained(this),
                 timeout_ms),
      timeout_ms);
}

void TestHandler::TestComplete() {
  if (!CefCurrentlyOn(TID_UI)) {
    CefPostTask(TID_UI, base::Bind(&TestHandler::TestComplete, this));
    return;
  }

  EXPECT_TRUE(browser_map_.empty());
  completion_state_->TestComplete();
}

TestHandler::UIThreadHelper* TestHandler::GetUIThreadHelper() {
  EXPECT_UI_THREAD();
  EXPECT_FALSE(destroy_test_called_);

  if (!ui_thread_helper_.get())
    ui_thread_helper_.reset(new UIThreadHelper());
  return ui_thread_helper_.get();
}

// global functions

void WaitForThread(CefThreadId thread_id) {
  base::WaitableEvent event(true, false);
  CefPostTask(thread_id, base::Bind(&NotifyEvent, &event));
  event.Wait();
}

void WaitForThread(CefRefPtr<CefTaskRunner> task_runner) {
  base::WaitableEvent event(true, false);
  task_runner->PostTask(CefCreateClosureTask(base::Bind(&NotifyEvent, &event)));
  event.Wait();
}

bool TestFailed() {
  CefRefPtr<CefCommandLine> command_line =
      CefCommandLine::GetGlobalCommandLine();
  if (command_line->HasSwitch("single-process")) {
    // Check for a failure on the current test only.
    return ::testing::UnitTest::GetInstance()->current_test_info()->result()->
        Failed();
  } else {
    // Check for any global failure.
    return ::testing::UnitTest::GetInstance()->Failed();
  }
}


text:
package org.rapidpm.jumpstart.vaadin.logic.properties;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

public class FilePropertyService implements PropertyService {

  private final Map<String, String> storage = new HashMap<>();

  @Override
  public String resolve(final String key) {
    return storage.get(key);
  }

  @Override
  public boolean hasKey(final String key) {
    return storage.containsKey(key);
  }

  @PostConstruct
  public void init() {
    storage.put("admin", "admin");
    storage.put("login.name", "Login"); // i18n
    storage.put("login.info", "Please enter your username and password"); // i18n
    storage.put("login.username", "username"); // i18n
    storage.put("login.password", "password"); // i18n
    storage.put("login.failed", "Login failed..."); // i18n
    storage.put("login.failed.description", "Login failed, please use right User / Password combination"); // i18n

    storage.put("login.language.de", "German");
    storage.put("login.language.en", "English");

    storage.put("app.logo", "/images/rapidpm.PNG"); // i18n
    storage.put("app.version", "Jumpstart Version 0.x.y"); // i18n

    storage.put("menue.default.help", "Help"); // i18n
    storage.put("menue.default.help.contact", "Contact"); // i18n
    storage.put("menue.default.help.support", "Support"); // i18n
    storage.put("menue.default.help.impressum", "Impressum"); // i18n
    storage.put("menue.default.help.disclaimer", "Disclaimer"); // i18n

    storage.put("menue.default.main", "Home"); // i18n
    storage.put("menue.default.main.logout", "Logout"); // i18n7

    storage.put("menue.default.chat", "Chat"); // i18n
  }
}


text:
namespace Furrovine { namespace Graphics {

	enum class ShaderVariablePrimitive {
		Void,
		Bool,
		Int,
		Float,
		String,
		Texture,
		Texture1D,
		Texture2D,
		Texture3D,
		TextureCube,
		Sampler,
		Sampler1D,
		Sampler2D,
		Sampler3D,
		SamplerCube,
		PixelShader,
		VertexShader,
		PixelFragment,
		VertexFragment,
		UInt,
		UInt8,
		GeometryShader,
		Rasterizer,
		DepthStencil,
		Blend,
		Buffer,
		CBuffer,
		TBuffer,
		Texture1DArray,
		Texture2DArray,
		RenderTargetView,
		DepthStencilView,
		Texture2DMS,
		Texture2DMSArray,
		TextureCubeArray,
		HullShader,
		DomainShader,
		Interface_Pointer,
		ComputeShader,
		Double,
		RWTexture1D,
		RWTexture1DArray,
		RWTexture2D,
		RWTexture2DArray,
		RWTexture3D,
		RWBuffer,
		ByteAddressBuffer,
		RWByteAddressBuffer,
		StructuredBuffer,
		RWStructuredBuffer,
		AppendStructuredBuffer,
		ConsumemeStructuredBuffer,
		Min8Float,
		Min10Float,
		Min16Float,
		Min12Int,
		Min16Int,
		Min16UInt,
	};

}}


text:
Named Colors: :func:`html2rgb`
==============================

.. testsetup::

    # Prep modules
    import sys, os
    # Full path to the test folder
    docpath = os.path.join(os.getcwd(), "test")
    # Add that path.
    sys.path.append(docpath)
    # Now actually go the current folder.
    os.chdir(docpath)
    os.chdir("html2rgb")
    # Load the module.
    from matlabtest import *

This test checks the blue component of an HTML color called :code:`'Navy'`.

.. doctest::

    >>> matlab("test_Navy")
    '0.5020'


text:
class MomentumCms::Admin::BaseController < ApplicationController
  layout 'momentum_cms/admin/application'
  include MomentumCms::I18nLocale
  include MomentumCms.configuration.admin_authentication.to_s.constantize

  before_action :authenticate,
                :load_sites,
                :load_site,
                :load_fixtures

  protected

  def load_sites
    @momentum_cms_sites = MomentumCms::Site.all
  end

  def load_site
    @current_momentum_cms_site = if params[:site_id]
                                   MomentumCms::Site.where(id: params[:site_id]).first
                                 else
                                   MomentumCms::Site.where(host: request.host_with_port).first
                                 end

    if @current_momentum_cms_site.blank?
      @current_momentum_cms_site = MomentumCms::Site.first
    end

    if @current_momentum_cms_site.blank?
      redirect_to new_cms_admin_site_path and return
    end
  end

  def load_fixtures
    return unless MomentumCms.configuration.site_fixtures_enabled.is_a?(Array)
    MomentumCms.configuration.site_fixtures_enabled.each do |fixture|
      MomentumCms::Fixture::Importer.new({ source: fixture }).import!
    end
    flash.now[:danger] = 'Fixtures enabled, all changes will be discarded.'
  end

end


text:
Extensions used for Windows Release Test Clusters.

Master extension: used to taint master node after provision.

Agent node extension: used to create missing dirs ( c:/temp ) that some tests require
as well as pull all required test images. Pulling of images is necessary as
a way to reduce test flakes due to timeouts (Pods may not spawn in the required 5 minutes).


text:
title       : Clustering techniques
subtitle    :
author      : Ahsan Ijaz
job         :
# logo        : /home/ahsan/Personal/Workshop Machine learning/DataScienceWorkshops/usefulResources-00/ebryx-logo.png
framework   : io2012        # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow   #
# url:
  # lib: ../../libraries
  # assets: /home/ahsan/Personal/Workshop Machine learning/Workshop1
widgets     : [mathjax]            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
embed : TRUE
---

## Clustering Applications

- Structure information together

---

## Clustering Applications

- Structure information together

---

## Clustering

- Unsupervised learning task
- No labels provided
- Uncovering structure by using only input
-  Input : docs as a vector $x_i$
-  Output : cluster labels $z_i$

---

## Characteristics of a cluster

> - Center and shape
> - Assign observation $x_i$ (doc) under cluster k (topic label) if
    - Score under cluster k is higher than others
    - Can think of distance from cluster center as a metric

---

## Ambiguous clusters

---

## K-means clustering

- Partitional clustering approach
- Each cluster is associated with a centroid
- Number of cluster, K are specified.

1. Select K points as initial centroids.
2.  repeat
3. Form K clusters by assigning all points to the closest center
4. Recompute the centroids of each cluster.
5.  Until  the centroids don't change.

---

## Illustrating k-means

---

## K-mean clustering details

- Initial centroids are often chosen randomly.
- Clusters produced vary from one run to another.
- 'Closeness' is measured by a proximity measure e.g., Euclidean distance, cosine similarity, or correlation.
- K-means will converge for common proximity measures mentioned above.
- Most of the convergence happens in the first few iterations.

---

## Importance of choosing initial clusters

K-mean clustering can depend heavily on the initial cluster centroids.

---

## Example of 10 clusters (initial centroid)

---

## Example of 10 clusters

---

## Limitations of K-means (differing sizes)

---

## Limitations of K-means (differing density)

---

## Limitations of K-means (nonglobular shapes)

---

## Other examples of limitations

---

# Density based clustering

Locate regions of high density separated from one another by region of low density.

---

## Notion of density

- Euclidean density
  - Number of points per unit volume
- Probability density

---

## Cell-based Euclidean density

- Divide region into a number of rectangular cells of equal volume and define density as # of points in each cell.

---

## Center-based Euclidean density

- Number of points with a specified radius of the point

---

## DBSCAN

- Density = number of points within a specified radius (Eps)
- A point is a core point if it has more than a specified number of neighbors (MinPts) within Eps.
  - These are points that are at the interior of a cluster.
- A border point has fewer than MinPts within Eps, but is in the neighborhood of a core point.
- A noise point is any point that is not a core point nor a border point.

---

## DBSCAN: Core, border and noise points

---

## DBSCAN Algorithm

- Eliminate noise points
- Perform clustering on the remaining points

1. Label all points as core, border or noise points.
2. Eliminate noise points.
3. Put an edge between all core points that are within Eps of each other.
4. Make each group of connected points into one cluster.
5. Assign each border point to one of the clusters of its associated core points.

---

## When DBSCAN works well
- Resistant to noise
- Can handle different shapes and sizes

---

## When DBSCAN fails

- Varying densities
- High dimensional data

---


text:
require 'mixlib/config'
require 'pedant/command_line'

require 'rspec-rerun/formatters/failures_formatter'

module Pedant
  class Config
    extend Mixlib::Config

    # Configure Pedant based on command-line arguments
    def self.from_argv(argv)
      cli_options = Pedant::CommandLine.new(argv).parse()
      cli_options.config_file ||= self.config_file

      if File.exist?(cli_options.config_file)
        self.from_file(cli_options.config_file)
      else
        raise "Configuration file '#{cli_options.config_file}' not found!"
      end

      # --tag TAG:VALUE  (inclusion filter)
      # --tag ~TAG:VALUE (exclusion filter)
      self[:tags] = cli_options.foci + cli_options.skip.map { |tag| "~#{tag}" }

      # ensure we remove any nil options before merging so we don't clobber
      # values set in the default Pedant::Config class OR user provided config
      # file
      non_nil_cli_options = cli_options.to_hash.delete_if{|key, value| value.nil? }
      merge!(non_nil_cli_options)
    end

    # Return an array of arguments for RSpec.
    def self.rspec_args
      args = []

      # Only apply filtering flags if 'run_all' is not set to override them
      if self[:tags] && !run_all
        args.concat(self[:tags].map { |tag| ['-t', tag.to_s] } )
      end

      if junit_file
        args.concat(%W[-r rspec_junit_formatter -f RspecJunitFormatter -o #{junit_file} -f documentation])
      else
        args.concat(%w[ --color -f documentation ])
      end

      # Always use the failures formatter, in case we want to rerun failures
      args.concat(%W[-f #{::RSpec::Rerun::Formatters::FailuresFormatter}])

      # Load up the failures file if we're re-running
      if rerun
        args.concat(%W[-O #{::RSpec::Rerun::Formatters::FailuresFormatter::FILENAME}])
      else
        # Remove the failures file if we aren't running with --rerun;
        # otherwise, if it exists, we would only ever run those tests,
        # even if they all pass!
        FileUtils.rm(::RSpec::Rerun::Formatters::FailuresFormatter::FILENAME, :force => true)
      end

      # Tell it which tests to run
      args.concat ["spec/bifrost"]

      args.flatten
    end

    # Default Values
    ################################################################################

    # Default to a config file in the current directory
    config_file "pedant_config.rb"

    # HTTP logging is turned off by default
    log_file(false)

    # JUnit output is turned off by default
    junit_file(false)

    # Error message verification is on by default
    verify_error_messages(true)

    # Emits a console bell when run finishes
    bell_on_completion(false)
  end
end


text:
#import <Foundation/Foundation.h>

@interface MCTEnglishMnemonicsDictionary : NSObject

+ (NSArray *)words;

@end


text:
require('time')
require('display-setup')
require('bluetooth-setup')
require('buttons')
require('main-menu')()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aubergine.Tests.Accounts.SoftwareToTest.Services
{
    public class GenericRepository<T> : List<T>
    {
        Func<T,string, bool> _FindbyName;
        public GenericRepository(Func<T,string, bool> findByName)
        {
            _FindbyName = findByName;
        }

        public T Find(string name)
        {
            return this.Where(o=>_FindbyName(o,name)).FirstOrDefault();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/empty_loading"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/q333333"
    android:gravity="center"
    android:orientation="horizontal"
    android:visibility="visible">

    <!--<ImageView-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:src="@drawable/image_detail_placeholder" />-->
    <!--<com.github.ybq.android.spinkit.SpinKitView-->
        <!--xmlns:app="http://schemas.android.com/apk/res-auto"-->
        <!--android:id="@+id/spin_kit"-->
        <!--style="@style/SpinKitView.Large.ThreeBounce"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_gravity="center"-->
        <!--app:SpinKit_Color="@color/colorPrimary" />-->

</LinearLayout>