text:
If you need help to setup everything you can read the [Javascript Setup section of the ANTLR Mega Tutorial](https://tomassetti.me/antlr-mega-tutorial/#javascript-setup)

The commands you need to know:
```
// to install dependencies and devDependencies
npm install
// to generate parser and lexer
antlr4 -Dlanguage=JavaScript Chat.g4
// to launch node. The[js] suffix is usually added only in debian-derived distributions
// then point your browser to the proper location, usually http://localhost:1337/
node[js] antlr.js
// to run the tests
./node_modules/nodeunit/bin/nodeunit nodeunit.js
```


text:
package com.github.ryanholdren.typesafesql.parameters;

public class UUIDParameter extends Parameter {

	public UUIDParameter(String argumentName) {
		super(argumentName);
	}

	@Override
	public <T,E extends Exception> T accept(ParameterVisitor<T,E> visitor) throws E {
		return visitor.visit(this);
	}

	@Override
	public String getArgumentType() {
		return "UUID";
	}

	@Override
	public String getCast() {
		return "UUID";
	}

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

}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;

namespace Alexa.NET.Management.SlotType
{
    public class CreateSlotResponseType
    {
        [JsonProperty("id")]
        public string Id { get; set; }
    }
}


text:
<?php declare(strict_types=1);

namespace Composer\Test\Mock;

use React\Promise\PromiseInterface;
use Composer\Installer\InstallationManager;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\IO\IOInterface;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation;
use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation;

class InstallationManagerMock extends InstallationManager
{
    /**
     * @var PackageInterface[]
     */
    private $installed = array();
    /**
     * @var PackageInterface[][]
     */
    private $updated = array();
    /**
     * @var PackageInterface[]
     */
    private $uninstalled = array();
    /**
     * @var string[]
     */
    private $trace = array();

    public function __construct()
    {
    }

    public function execute(InstalledRepositoryInterface $repo, array $operations, $devMode = true, $runScripts = true): void
    {
        foreach ($operations as $operation) {
            $method = $operation->getOperationType();
            // skipping download() step here for tests
            $this->$method($repo, $operation);
        }
    }

    public function getInstallPath(PackageInterface $package): string
    {
        return '';
    }

    public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool
    {
        return $repo->hasPackage($package);
    }

    /**
     * @inheritDoc
     */
    public function install(InstalledRepositoryInterface $repo, InstallOperation $operation): ?PromiseInterface
    {
        $this->installed[] = $operation->getPackage();
        $this->trace[] = strip_tags((string) $operation);
        $repo->addPackage(clone $operation->getPackage());

        return null;
    }

    /**
     * @inheritDoc
     */
    public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface
    {
        $this->updated[] = array($operation->getInitialPackage(), $operation->getTargetPackage());
        $this->trace[] = strip_tags((string) $operation);
        $repo->removePackage($operation->getInitialPackage());
        if (!$repo->hasPackage($operation->getTargetPackage())) {
            $repo->addPackage(clone $operation->getTargetPackage());
        }

        return null;
    }

    /**
     * @inheritDoc
     */
    public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation): ?PromiseInterface
    {
        $this->uninstalled[] = $operation->getPackage();
        $this->trace[] = strip_tags((string) $operation);
        $repo->removePackage($operation->getPackage());

        return null;
    }

    public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void
    {
        $package = $operation->getPackage();

        $this->installed[] = $package;
        $this->trace[] = strip_tags((string) $operation);

        parent::markAliasInstalled($repo, $operation);
    }

    public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void
    {
        $this->uninstalled[] = $operation->getPackage();
        $this->trace[] = strip_tags((string) $operation);

        parent::markAliasUninstalled($repo, $operation);
    }

    /** @return string[] */
    public function getTrace(): array
    {
        return $this->trace;
    }

    /** @return PackageInterface[] */
    public function getInstalledPackages(): array
    {
        return $this->installed;
    }

    /** @return PackageInterface[][] */
    public function getUpdatedPackages(): array
    {
        return $this->updated;
    }

    /** @return PackageInterface[] */
    public function getUninstalledPackages(): array
    {
        return $this->uninstalled;
    }

    public function notifyInstalls(IOInterface $io): void
    {
        // noop
    }

    /** @return PackageInterface[] */
    public function getInstalledPackagesByType(): array
    {
        return $this->installed;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>boto v2.10.0 — boto v2.33.0</title>

    <link rel="stylesheet" href="../_static/boto.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="boto v2.33.0" href="../index.html" />
    <link rel="next" title="boto v2.11.0" href="v2.11.0.html" />
    <link rel="prev" title="boto v2.1.1" href="v2.1.1.html" />

Navigation

          index

          modules |

          next |

          previous |

boto v2.33.0 »

boto v2.10.0¶

<col class="field-name" />
<col class="field-body" />

date:	2013/08/13

This release adds Mobile Push Notification support to Amazon Simple Notification
Service, better reporting for Amazon Redshift, SigV4 authorization for Amazon
Elastic MapReduce & lots of bugfixes.

Features¶

Added support for Mobile Push Notifications to SNS. This enables you to send
push notifications to mobile devices (such as iOS or Android) using SNS.
(commit ccba574)

Added support for better reporting within Redshift. (commit 9d55dd3)

Switched Elastic MapReduce to use SigV4 for authorization. (commit b80aa48)

Bugfixes¶

Added the <tt class="docutils literal">MinAdjustmentType</tt> parameter to EC2 Autoscaling. (issue 1562,
issue 1619, commit 1760284, commit 2a11fd9, commit 2d14006 &
commit b7f1ae1)

Fixed how DynamoDB tracks changes to data in <tt class="docutils literal">Item</tt> objects, fixing
failures with modified sets not being sent. (issue 1565,
commit b111fcf & commit 812f9a6)

Updated the CA certificates Boto ships with. (issue 1578, commit 4dfadc8)

Fixed how CloudSearch’s <tt class="docutils literal">Layer2</tt> object gets initialized. (issue 1629,
issue 1630, commit 40b3652 & commit f797ff9)

Fixed the <tt class="docutils literal">-w</tt> flag in <tt class="docutils literal">s3put</tt>. (issue 1637, commit 0865004 &
commit 3fe70ca)

Added the <tt class="docutils literal">ap-southeast-2</tt> endpoint for DynamoDB. (issue 1621,
commit 501b637)

Fixed test suite to run faster. (commit 243a67e)

Fixed how non-JSON responses are caught from CloudSearch. (issue 1633,
issue 1645, commit d5a5c01, commit 954a50c, commit 915d8ff &
commit 4407fcb)

Fixed how <tt class="docutils literal">DeviceIndex</tt> is parsed from EC2. (issue 1632, issue 1646,
commit ff15e1f, commit 8337a0b & commit 27c9b04)

Fixed EC2’s <tt class="docutils literal">connect_to_region</tt> to respect the <tt class="docutils literal">region</tt> parameter. (
issue 1616, issue 1654, commit 9c37256, commit 5950d12 & commit b7eebe8)

Added <tt class="docutils literal">modify_network_interface_atribute</tt> to EC2 connections.
(issue 1613, issue 1656, commit e00b601, commit 5b62f27, commit 126f6e9,
commit bbfed1f & commit 0c61293)

Added support for <tt class="docutils literal">param_group</tt> within RDS. (issue 1639, commit c47baf0)

Added support for using <tt class="docutils literal">Item.partial_save</tt> to create new records within
DynamoDBv2. (issue 1660, issue 1521, commit bfa469f & commit 58a13d7)

Several documentation improvements/fixes:

Updated guideline on how core should merge PRs. (commit 80a419c)

Fixed a typo in a CloudFront docstring. (issue 1657, commit 1aa0621)

Table Of Contents

boto v2.10.0

Features

Bugfixes

Previous topic

boto v2.1.1

Next topic

boto v2.11.0

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

PDF Version

Navigation

          index

          modules |

          next |

          previous |

boto v2.33.0 »

        © Copyright 2009,2010, Mitch Garnaat.
      Created using Sphinx 1.2.3.


text:
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "../builders/primrefgen.h"
#include "../builders/heuristic_spatial.h"
#include "../builders/splitter.h"

#include "../../common/algorithms/parallel_for_for.h"
#include "../../common/algorithms/parallel_for_for_prefix_sum.h"

#define DBG_PRESPLIT(x)
#define CHECK_PRESPLIT(x)

#define GRID_SIZE 1024
#define MAX_PRESPLITS_PER_PRIMITIVE_LOG 5
#define MAX_PRESPLITS_PER_PRIMITIVE (1<<MAX_PRESPLITS_PER_PRIMITIVE_LOG)
#define PRIORITY_CUTOFF_THRESHOLD 1.0f
#define PRIORITY_SPLIT_POS_WEIGHT 1.5f

namespace embree
{
  namespace isa
  {

    struct PresplitItem
    {
      union {
        float priority;
        unsigned int data;
      };
      unsigned int index;

      __forceinline operator unsigned() const
      {
	return reinterpret_cast<const unsigned&>(priority);
      }
      __forceinline bool operator < (const PresplitItem& item) const
      {
	return (priority < item.priority);
      }

      template<typename Mesh>
      __forceinline static float compute_priority(const PrimRef &ref, Scene *scene, const Vec2i &mc)
      {
	const unsigned int geomID = ref.geomID();
	const unsigned int primID = ref.primID();
	const float area_aabb  = area(ref.bounds());
	const float area_prim  = ((Mesh*)scene->get(geomID))->projectedPrimitiveArea(primID);
        const unsigned int diff = 31 - lzcnt(mc.x^mc.y);
        assert(area_prim <= area_aabb);
        //const float priority = powf((area_aabb - area_prim) * powf(PRIORITY_SPLIT_POS_WEIGHT,(float)diff),1.0f/4.0f);
        const float priority = sqrtf(sqrtf( (area_aabb - area_prim) * powf(PRIORITY_SPLIT_POS_WEIGHT,(float)diff) ));
        assert(priority >= 0.0f && priority < FLT_LARGE);
	return priority;
      }

    };

    inline std::ostream &operator<<(std::ostream &cout, const PresplitItem& item) {
      return cout << "index " << item.index << " priority " << item.priority;
    };

    template<typename SplitterFactory>
      void splitPrimitive(SplitterFactory &Splitter,
                          const PrimRef &prim,
                          const unsigned int geomID,
                          const unsigned int primID,
                          const unsigned int split_level,
                          const Vec3fa &grid_base,
                          const float grid_scale,
                          const float grid_extend,
                          PrimRef subPrims[MAX_PRESPLITS_PER_PRIMITIVE],
                          unsigned int& numSubPrims)
    {
      assert(split_level <= MAX_PRESPLITS_PER_PRIMITIVE_LOG);
      if (split_level == 0)
      {
        assert(numSubPrims < MAX_PRESPLITS_PER_PRIMITIVE);
        subPrims[numSubPrims++] = prim;
      }
      else
      {
        const Vec3fa lower = prim.lower;
        const Vec3fa upper = prim.upper;
        const Vec3fa glower = (lower-grid_base)*Vec3fa(grid_scale)+Vec3fa(0.2f);
        const Vec3fa gupper = (upper-grid_base)*Vec3fa(grid_scale)-Vec3fa(0.2f);
        Vec3ia ilower(floor(glower));
        Vec3ia iupper(floor(gupper));

        /* this ignores dimensions that are empty */
        iupper = (Vec3ia)(select(vint4(glower) >= vint4(gupper),vint4(ilower),vint4(iupper)));

        /* compute a morton code for the lower and upper grid coordinates. */
        const unsigned int lower_code = bitInterleave(ilower.x,ilower.y,ilower.z);
        const unsigned int upper_code = bitInterleave(iupper.x,iupper.y,iupper.z);

        /* if all bits are equal then we cannot split */
        if(unlikely(lower_code == upper_code))
        {
          assert(numSubPrims < MAX_PRESPLITS_PER_PRIMITIVE);
          subPrims[numSubPrims++] = prim;
          return;
        }

        /* compute octree level and dimension to perform the split in */
        const unsigned int diff = 31 - lzcnt(lower_code^upper_code);
        const unsigned int level = diff / 3;
        const unsigned int dim   = diff % 3;

        /* now we compute the grid position of the split */
        const unsigned int isplit = iupper[dim] & ~((1<<level)-1);

        /* compute world space position of split */
        const float inv_grid_size = 1.0f / GRID_SIZE;
        const float fsplit = grid_base[dim] + isplit * inv_grid_size * grid_extend;

        assert(prim.lower[dim] <= fsplit &&
               prim.upper[dim] >= fsplit);

        /* split primitive */
        const auto splitter = Splitter(prim);
        BBox3fa left,right;
        splitter(prim.bounds(),dim,fsplit,left,right);
        assert(!left.empty());
        assert(!right.empty());

        splitPrimitive(Splitter,PrimRef(left ,geomID,primID),geomID,primID,split_level-1,grid_base,grid_scale,grid_extend,subPrims,numSubPrims);
        splitPrimitive(Splitter,PrimRef(right,geomID,primID),geomID,primID,split_level-1,grid_base,grid_scale,grid_extend,subPrims,numSubPrims);
      }
    }

    template<typename Mesh, typename SplitterFactory>
      PrimInfo createPrimRefArray_presplit(Geometry* geometry, unsigned int geomID, size_t numPrimRefs, mvector<PrimRef>& prims, BuildProgressMonitor& progressMonitor)
    {
      ParallelPrefixSumState<PrimInfo> pstate;

      /* first try */
      progressMonitor(0);
      PrimInfo pinfo = parallel_prefix_sum( pstate, size_t(0), geometry->size(), size_t(1024), PrimInfo(empty), [&](const range<size_t>& r, const PrimInfo& base) -> PrimInfo {
	  return geometry->createPrimRefArray(prims,r,r.begin(),geomID);
	}, [](const PrimInfo& a, const PrimInfo& b) -> PrimInfo { return PrimInfo::merge(a,b); });

      /* if we need to filter out geometry, run again */
      if (pinfo.size() != numPrimRefs)
	{
	  progressMonitor(0);
	  pinfo = parallel_prefix_sum( pstate, size_t(0), geometry->size(), size_t(1024), PrimInfo(empty), [&](const range<size_t>& r, const PrimInfo& base) -> PrimInfo {
	      return geometry->createPrimRefArray(prims,r,base.size(),geomID);
	    }, [](const PrimInfo& a, const PrimInfo& b) -> PrimInfo { return PrimInfo::merge(a,b); });
	}
      return pinfo;
    }

    __forceinline Vec2i computeMC(const Vec3fa &grid_base, const float grid_scale, const PrimRef &ref)
    {
      const Vec3fa lower = ref.lower;
      const Vec3fa upper = ref.upper;
      const Vec3fa glower = (lower-grid_base)*Vec3fa(grid_scale)+Vec3fa(0.2f);
      const Vec3fa gupper = (upper-grid_base)*Vec3fa(grid_scale)-Vec3fa(0.2f);
      Vec3ia ilower(floor(glower));
      Vec3ia iupper(floor(gupper));

      /* this ignores dimensions that are empty */
      iupper = (Vec3ia)select(vint4(glower) >= vint4(gupper),vint4(ilower),vint4(iupper));

      /* compute a morton code for the lower and upper grid coordinates. */
      const unsigned int lower_code = bitInterleave(ilower.x,ilower.y,ilower.z);
      const unsigned int upper_code = bitInterleave(iupper.x,iupper.y,iupper.z);
      return Vec2i(lower_code,upper_code);
    }

    template<typename Mesh, typename SplitterFactory>
      PrimInfo createPrimRefArray_presplit(Scene* scene, Geometry::GTypeMask types, bool mblur, size_t numPrimRefs, mvector<PrimRef>& prims, BuildProgressMonitor& progressMonitor)
    {
      static const size_t MIN_STEP_SIZE = 128;

      ParallelForForPrefixSumState<PrimInfo> pstate;
      Scene::Iterator2 iter(scene,types,mblur);

      /* first try */
      progressMonitor(0);
      pstate.init(iter,size_t(1024));
      PrimInfo pinfo = parallel_for_for_prefix_sum0( pstate, iter, PrimInfo(empty), [&](Geometry* mesh, const range<size_t>& r, size_t k, size_t geomID) -> PrimInfo {
	  return mesh->createPrimRefArray(prims,r,k,(unsigned)geomID);
	}, [](const PrimInfo& a, const PrimInfo& b) -> PrimInfo { return PrimInfo::merge(a,b); });

      /* if we need to filter out geometry, run again */
      if (pinfo.size() != numPrimRefs)
	{
	  progressMonitor(0);
	  pinfo = parallel_for_for_prefix_sum1( pstate, iter, PrimInfo(empty), [&](Geometry* mesh, const range<size_t>& r, size_t k, size_t geomID, const PrimInfo& base) -> PrimInfo {
	      return mesh->createPrimRefArray(prims,r,base.size(),(unsigned)geomID);
	    }, [](const PrimInfo& a, const PrimInfo& b) -> PrimInfo { return PrimInfo::merge(a,b); });
	}

      /* use correct number of primitives */
      size_t numPrimitives = pinfo.size();
      const size_t alloc_numPrimitives = prims.size();
      const size_t numSplitPrimitivesBudget = alloc_numPrimitives - numPrimitives;

      /* set up primitive splitter */
      SplitterFactory Splitter(scene);

      DBG_PRESPLIT(
        const size_t org_numPrimitives = pinfo.size();
        PRINT(numPrimitives);
        PRINT(alloc_numPrimitives);
        PRINT(numSplitPrimitivesBudget);
        );

      /* allocate double buffer presplit items */
      const size_t presplit_allocation_size = sizeof(PresplitItem)*alloc_numPrimitives;
      PresplitItem *presplitItem     = (PresplitItem*)alignedMalloc(presplit_allocation_size,64);
      PresplitItem *tmp_presplitItem = (PresplitItem*)alignedMalloc(presplit_allocation_size,64);

      /* compute grid */
      const Vec3fa grid_base    = pinfo.geomBounds.lower;
      const Vec3fa grid_diag    = pinfo.geomBounds.size();
      const float grid_extend   = max(grid_diag.x,max(grid_diag.y,grid_diag.z));
      const float grid_scale    = grid_extend == 0.0f ? 0.0f : GRID_SIZE / grid_extend;

      /* init presplit items and get total sum */
      const float psum = parallel_reduce( size_t(0), numPrimitives, size_t(MIN_STEP_SIZE), 0.0f, [&](const range<size_t>& r) -> float {
          float sum = 0.0f;
          for (size_t i=r.begin(); i<r.end(); i++)
          {
            presplitItem[i].index = (unsigned int)i;
            const Vec2i mc = computeMC(grid_base,grid_scale,prims[i]);
            /* if all bits are equal then we cannot split */
            presplitItem[i].priority = (mc.x != mc.y) ? PresplitItem::compute_priority<Mesh>(prims[i],scene,mc) : 0.0f;
            /* FIXME: sum undeterministic */
            sum += presplitItem[i].priority;
          }
          return sum;
        },[](const float& a, const float& b) -> float { return a+b; });

      /* compute number of splits per primitive */
      const float inv_psum = 1.0f / psum;
      parallel_for( size_t(0), numPrimitives, size_t(MIN_STEP_SIZE), [&](const range<size_t>& r) -> void {
          for (size_t i=r.begin(); i<r.end(); i++)
          {
            if (presplitItem[i].priority > 0.0f)
            {
              const float rel_p = (float)numSplitPrimitivesBudget * presplitItem[i].priority * inv_psum;
              if (rel_p >= PRIORITY_CUTOFF_THRESHOLD) // need at least a split budget that generates two sub-prims
              {
                presplitItem[i].priority = max(min(ceilf(logf(rel_p)/logf(2.0f)),(float)MAX_PRESPLITS_PER_PRIMITIVE_LOG),1.0f);
                //presplitItem[i].priority = min(floorf(logf(rel_p)/logf(2.0f)),(float)MAX_PRESPLITS_PER_PRIMITIVE_LOG);
                assert(presplitItem[i].priority >= 0.0f && presplitItem[i].priority <= (float)MAX_PRESPLITS_PER_PRIMITIVE_LOG);
              }
              else
                presplitItem[i].priority = 0.0f;
            }
          }
        });

      auto isLeft = [&] (const PresplitItem &ref) { return ref.priority < PRIORITY_CUTOFF_THRESHOLD; };
      size_t center = parallel_partitioning(presplitItem,0,numPrimitives,isLeft,1024);

      /* anything to split ? */
      if (center < numPrimitives)
      {
        size_t numPrimitivesToSplit = numPrimitives - center;
        assert(presplitItem[center].priority >= 1.0f);

        /* sort presplit items in ascending order */
        radix_sort_u32(presplitItem + center,tmp_presplitItem + center,numPrimitivesToSplit,1024);

        CHECK_PRESPLIT(
          parallel_for( size_t(center+1), numPrimitives, size_t(MIN_STEP_SIZE), [&](const range<size_t>& r) -> void {
              for (size_t i=r.begin(); i<r.end(); i++)
                assert(presplitItem[i-1].priority <= presplitItem[i].priority);
            });
          );

        unsigned int* primOffset0 = (unsigned int*)tmp_presplitItem;
        unsigned int* primOffset1 = (unsigned int*)tmp_presplitItem + numPrimitivesToSplit;

        /* compute actual number of sub-primitives generated within the [center;numPrimitives-1] range */
        const size_t totalNumSubPrims = parallel_reduce( size_t(center), numPrimitives, size_t(MIN_STEP_SIZE), size_t(0), [&](const range<size_t>& t) -> size_t {
            size_t sum = 0;
            for (size_t i=t.begin(); i<t.end(); i++)
            {
              PrimRef subPrims[MAX_PRESPLITS_PER_PRIMITIVE];
              assert(presplitItem[i].priority >= 1.0f);
              const unsigned int  primrefID = presplitItem[i].index;
              const float prio              = presplitItem[i].priority;
              const unsigned int   geomID   = prims[primrefID].geomID();
              const unsigned int   primID   = prims[primrefID].primID();
              const unsigned int split_levels = (unsigned int)prio;
              unsigned int numSubPrims = 0;
              splitPrimitive(Splitter,prims[primrefID],geomID,primID,split_levels,grid_base,grid_scale,grid_extend,subPrims,numSubPrims);
              assert(numSubPrims);
              numSubPrims--; // can reuse slot
              sum+=numSubPrims;
              presplitItem[i].data = (numSubPrims << MAX_PRESPLITS_PER_PRIMITIVE_LOG) | split_levels;
              primOffset0[i-center] = numSubPrims;
            }
            return sum;
          },[](const size_t& a, const size_t& b) -> size_t { return a+b; });

        /* if we are over budget, need to shrink the range */
        if (totalNumSubPrims > numSplitPrimitivesBudget)
        {
          size_t new_center = numPrimitives-1;
          size_t sum = 0;
          for (;new_center>=center;new_center--)
          {
            const unsigned int numSubPrims = presplitItem[new_center].data >> MAX_PRESPLITS_PER_PRIMITIVE_LOG;
            if (unlikely(sum + numSubPrims >= numSplitPrimitivesBudget)) break;
            sum += numSubPrims;
          }
          new_center++;

          primOffset0 += new_center - center;
          numPrimitivesToSplit -= new_center - center;
          center = new_center;
          assert(numPrimitivesToSplit == (numPrimitives - center));
        }

        /* parallel prefix sum to compute offsets for storing sub-primitives */
        const unsigned int offset = parallel_prefix_sum(primOffset0,primOffset1,numPrimitivesToSplit,(unsigned int)0,std::plus<unsigned int>());
        assert(numPrimitives+offset <= alloc_numPrimitives);

        /* iterate over range, and split primitives into sub primitives and append them to prims array */
        parallel_for( size_t(center), numPrimitives, size_t(MIN_STEP_SIZE), [&](const range<size_t>& rn) -> void {
            for (size_t j=rn.begin(); j<rn.end(); j++)
            {
              PrimRef subPrims[MAX_PRESPLITS_PER_PRIMITIVE];
              const unsigned int  primrefID = presplitItem[j].index;
              const unsigned int   geomID   = prims[primrefID].geomID();
              const unsigned int   primID   = prims[primrefID].primID();
              const unsigned int split_levels = presplitItem[j].data & ((unsigned int)(1 << MAX_PRESPLITS_PER_PRIMITIVE_LOG)-1);

              assert(split_levels);
              assert(split_levels <= MAX_PRESPLITS_PER_PRIMITIVE_LOG);
              unsigned int numSubPrims = 0;
              splitPrimitive(Splitter,prims[primrefID],geomID,primID,split_levels,grid_base,grid_scale,grid_extend,subPrims,numSubPrims);
              const size_t newID = numPrimitives + primOffset1[j-center];
              assert(newID+numSubPrims-1 <= alloc_numPrimitives);
              prims[primrefID] = subPrims[0];
              for (size_t i=1;i<numSubPrims;i++)
                prims[newID+i-1] = subPrims[i];
            }
          });

        numPrimitives += offset;
        DBG_PRESPLIT(
          PRINT(pinfo.size());
          PRINT(numPrimitives);
          PRINT((float)numPrimitives/org_numPrimitives));
      }

      /* recompute centroid bounding boxes */
      pinfo = parallel_reduce(size_t(0),numPrimitives,size_t(MIN_STEP_SIZE),PrimInfo(empty),[&] (const range<size_t>& r) -> PrimInfo {
          PrimInfo p(empty);
          for (size_t j=r.begin(); j<r.end(); j++)
            p.add_center2(prims[j]);
          return p;
        }, [](const PrimInfo& a, const PrimInfo& b) -> PrimInfo { return PrimInfo::merge(a,b); });

      assert(pinfo.size() == numPrimitives);

      /* free double buffer presplit items */
      alignedFree(tmp_presplitItem);
      alignedFree(presplitItem);
      return pinfo;
    }
  }
}


text:
package org.apache.nifi.attribute.expression.language;

import org.apache.nifi.components.PropertyValue;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.controller.ControllerServiceLookup;
import org.apache.nifi.expression.AttributeValueDecorator;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.parameter.ParameterLookup;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.registry.VariableRegistry;
import org.apache.nifi.util.FormatUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class StandardPropertyValue implements PropertyValue {

    private final String rawValue;
    private final ControllerServiceLookup serviceLookup;
    private final PreparedQuery preparedQuery;
    private final VariableRegistry variableRegistry;
    private final ParameterLookup parameterLookup;

    public StandardPropertyValue(final String rawValue, final ControllerServiceLookup serviceLookup, final ParameterLookup parameterLookup) {
        this(rawValue, serviceLookup, parameterLookup, Query.prepare(rawValue), VariableRegistry.EMPTY_REGISTRY);
    }

    public StandardPropertyValue(final String rawValue, final ControllerServiceLookup serviceLookup, final ParameterLookup parameterLookup, final VariableRegistry variableRegistry) {
        this(rawValue, serviceLookup, parameterLookup, Query.prepare(rawValue), variableRegistry);
    }

    /**
     * Constructs a new StandardPropertyValue with the given value & service
     * lookup and indicates whether or not the rawValue contains any NiFi
     * Expressions. If it is unknown whether or not the value contains any NiFi
     * Expressions, the
     * {@link #StandardPropertyValue(String, ControllerServiceLookup, ParameterLookup, VariableRegistry)}
     * constructor should be used or true should be passed.
     * However, if it is known that the value contains no NiFi Expression, that
     * information should be provided so that calls to
     * {@link #evaluateAttributeExpressions()} are much more efficient
     *
     * @param rawValue value
     * @param serviceLookup lookup
     * @param  parameterLookup the parameter lookup
     * @param preparedQuery query
     * @param variableRegistry variableRegistry
     */
    public StandardPropertyValue(final String rawValue, final ControllerServiceLookup serviceLookup, final ParameterLookup parameterLookup, final PreparedQuery preparedQuery,
            final VariableRegistry variableRegistry) {
        this.rawValue = rawValue;
        this.serviceLookup = serviceLookup;
        this.preparedQuery = preparedQuery;
        this.variableRegistry = variableRegistry;
        this.parameterLookup = parameterLookup == null ? ParameterLookup.EMPTY : parameterLookup;
    }

    @Override
    public String getValue() {
        return rawValue;
    }

    @Override
    public Integer asInteger() {
        return (rawValue == null) ? null : Integer.parseInt(rawValue.trim());
    }

    @Override
    public Long asLong() {
        return (rawValue == null) ? null : Long.parseLong(rawValue.trim());
    }

    @Override
    public Boolean asBoolean() {
        return (rawValue == null) ? null : Boolean.parseBoolean(rawValue.trim());
    }

    @Override
    public Float asFloat() {
        return (rawValue == null) ? null : Float.parseFloat(rawValue.trim());
    }

    @Override
    public Double asDouble() {
        return (rawValue == null) ? null : Double.parseDouble(rawValue.trim());
    }

    @Override
    public Long asTimePeriod(final TimeUnit timeUnit) {
        return (rawValue == null) ? null : FormatUtils.getTimeDuration(rawValue.trim(), timeUnit);
    }

    @Override
    public Double asDataSize(final DataUnit dataUnit) {
        return rawValue == null ? null : DataUnit.parseDataSize(rawValue.trim(), dataUnit);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions() throws ProcessException {
        return evaluateAttributeExpressions(null, null, null);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final Map<String, String> attributes) throws ProcessException {
        return evaluateAttributeExpressions(null, attributes, null);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final Map<String, String> attributes, final AttributeValueDecorator decorator) throws ProcessException {
        return evaluateAttributeExpressions(null, attributes, decorator);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final AttributeValueDecorator decorator) throws ProcessException {
        return evaluateAttributeExpressions(null, null, decorator);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final FlowFile flowFile) throws ProcessException {
        return evaluateAttributeExpressions(flowFile, null, null);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final FlowFile flowFile, final Map<String, String> additionalAttributes) throws ProcessException {
        return evaluateAttributeExpressions(flowFile, additionalAttributes, null);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final FlowFile flowFile, final AttributeValueDecorator decorator) throws ProcessException {
        return evaluateAttributeExpressions(flowFile, null, decorator);
    }

    @Override
    public PropertyValue evaluateAttributeExpressions(final FlowFile flowFile, final Map<String, String> additionalAttributes, final AttributeValueDecorator decorator) throws ProcessException {
        return evaluateAttributeExpressions(flowFile, additionalAttributes, decorator, null);
    }

    @Override
    @SuppressWarnings("unchecked")
    public PropertyValue evaluateAttributeExpressions(FlowFile flowFile, Map<String, String> additionalAttributes, AttributeValueDecorator decorator, Map<String, String> stateValues)
            throws ProcessException {
        if (rawValue == null || preparedQuery == null) {
            return this;
        }

        final ValueLookup lookup = new ValueLookup(variableRegistry, flowFile, additionalAttributes);
        final EvaluationContext evaluationContext = new StandardEvaluationContext(lookup, stateValues, parameterLookup);
        final String evaluated = preparedQuery.evaluateExpressions(evaluationContext, decorator);

        return new StandardPropertyValue(evaluated, serviceLookup, parameterLookup, new EmptyPreparedQuery(evaluated), null);
    }

    @Override
    public String toString() {
        return rawValue;
    }

    @Override
    public ControllerService asControllerService() {
        if (rawValue == null || rawValue.equals("") || serviceLookup == null) {
            return null;
        }

        return serviceLookup.getControllerService(rawValue);
    }

    @Override
    public <T extends ControllerService> T asControllerService(final Class<T> serviceType) throws IllegalArgumentException {
        if (!serviceType.isInterface()) {
            throw new IllegalArgumentException("ControllerServices may be referenced only via their interfaces; " + serviceType + " is not an interface");
        }
        if (rawValue == null || rawValue.equals("") || serviceLookup == null) {
            return null;
        }

        final ControllerService service = serviceLookup.getControllerService(rawValue);
        if (service == null) {
            return null;
        }
        if (serviceType.isAssignableFrom(service.getClass())) {
            return serviceType.cast(service);
        }
        throw new IllegalArgumentException("Controller Service with identifier " + rawValue + " is of type " + service.getClass() + " and cannot be cast to " + serviceType);
    }

    @Override
    public boolean isSet() {
        return rawValue != null;
    }

    @Override
    public boolean isExpressionLanguagePresent() {
        if (preparedQuery == null) {
            return false;
        }
        return preparedQuery.isExpressionLanguagePresent();
    }
}


text:
SPEC_DIR = File.expand_path(File.dirname(__FILE__))
ROOT_DIR = File.expand_path(File.join(SPEC_DIR, '..'))
LIB_DIR = File.expand_path(File.join(ROOT_DIR, 'lib'))
FIXTURES_DIR = File.expand_path(File.join(SPEC_DIR, 'fixtures'))

$LOAD_PATH.unshift(SPEC_DIR)
$LOAD_PATH.unshift(LIB_DIR)
$LOAD_PATH.uniq!

require 'rspec'
require 'minichat'


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace util
      {
        namespace regex
        {
            class CharIndexedString;
        }
      }
    }
  }
}

class gnu::java::util::regex::CharIndexedString : public ::gnu::java::util::regex::CharIndexedCharSequence
{

public: // actually package-private
  CharIndexedString(::java::lang::String *, jint);
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_java_util_regex_CharIndexedString__


text:
<?php

namespace Ali\DatatableBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Ali\DatatableBundle\Util\Datatable;

class AliDatatableExtension extends \Twig_Extension
{

    /** @var \Symfony\Component\DependencyInjection\ContainerInterface */
    protected $_container;

    /**
     * class constructor
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->_container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('datatable', array($this, 'datatable'), array("is_safe" => array("html")))
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('dta_trans', array($this, 'dtatransFilter'))
        );
    }

    /**
     * Datatable translate filter
     *
     * @param string $id
     *
     * @return string
     */
    public function dtatransFilter($id)
    {
        $translator = $this->_container->get('translator');
        $callback   = function($id) {
            $path = $this->_container->get('kernel')->locateResource('@AliDatatableBundle/Resources/translations/messages.en.yml');
            return \Symfony\Component\Yaml\Yaml::parse(file_get_contents($path))['ali']['common'][explode('.', $id)[2]];
        };
        return $translator->trans($id) === $id ? $callback($id) : $translator->trans($id);
    }

    /**
     * Converts a string to time
     *
     * @param string $string
     * @return int
     */
    public function datatable($options)
    {
        if (!isset($options['id']))
        {
            $options['id'] = 'ali-dta_' . md5(rand(1, 100));
        }
        $dt                       = Datatable::getInstance($options['id']);
        $config                   = $dt->getConfiguration();
        $options['js_conf']       = json_encode($config['js']);
        $options['js']            = json_encode($options['js']);
        $options['action']        = $dt->getHasAction();
        $options['action_twig']   = $dt->getHasRendererAction();
        $options['fields']        = $dt->getFields();
        $options['delete_form']   = $this->createDeleteForm('_id_')->createView();
        $options['search']        = $dt->getSearch();
        $options['search_fields'] = $dt->getSearchFields();
        $options['multiple']      = $dt->getMultiple();
        $options['sort']          = is_null($dt->getOrderField()) ? NULL : array(array_search(
                    $dt->getOrderField(), array_values($dt->getFields())), $dt->getOrderType());
        $main_template            = 'AliDatatableBundle:Main:index.html.twig';
        if (isset($options['main_template']))
        {
            $main_template = $options['main_template'];
        }
        $session                  = $this->_container->get('session');
        $rawjs                    = $this->_container
                ->get('templating')
                ->render('AliDatatableBundle:Internal:script.html.twig', $options);
        $sess_dtb                 = $session->get('datatable', array());
        $sess_dtb[$options['id']] = $rawjs;
        $session->set('datatable', $sess_dtb);

        return $this->_container
                        ->get('templating')
                        ->render($main_template, $options);
    }

    /**
     * create delete form
     *
     * @param type $id
     * @return type
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm();
    }

    /**
     * create form builder
     *
     * @param type $data
     * @param array $options
     * @return type
     */
    public function createFormBuilder($data = null, array $options = array())
    {
        return $this->_container->get('form.factory')->createBuilder('form', $data, $options);
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'DatatableBundle';
    }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/tasks/v2beta3/target.proto

package com.google.cloud.tasks.v2beta3;

/**
 *
 *
 *

 * App Engine HTTP queue.
 * The task will be delivered to the App Engine application hostname
 * specified by its
 * [AppEngineHttpQueue][google.cloud.tasks.v2beta3.AppEngineHttpQueue] and
 * [AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest]. The
 * documentation for
 * [AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest]
 * explains how the task's host URL is constructed.
 * Using [AppEngineHttpQueue][google.cloud.tasks.v2beta3.AppEngineHttpQueue]
 * requires
 * [`appengine.applications.get`](https://cloud.google.com/appengine/docs/admin-api/access-control)
 * Google IAM permission for the project
 * and the following scope:
 * `https://www.googleapis.com/auth/cloud-platform`
 *

 *
 * Protobuf type {@code google.cloud.tasks.v2beta3.AppEngineHttpQueue}
 */
public final class AppEngineHttpQueue extends com.google.protobuf.GeneratedMessageV3
    implements
    // @@protoc_insertion_point(message_implements:google.cloud.tasks.v2beta3.AppEngineHttpQueue)
    AppEngineHttpQueueOrBuilder {
  private static final long serialVersionUID = 0L;
  // Use AppEngineHttpQueue.newBuilder() to construct.
  private AppEngineHttpQueue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }

  private AppEngineHttpQueue() {}

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
    return this.unknownFields;
  }

  private AppEngineHttpQueue(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    int mutable_bitField0_ = 0;
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          case 10:
            {
              com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder subBuilder = null;
              if (appEngineRoutingOverride_ != null) {
                subBuilder = appEngineRoutingOverride_.toBuilder();
              }
              appEngineRoutingOverride_ =
                  input.readMessage(
                      com.google.cloud.tasks.v2beta3.AppEngineRouting.parser(), extensionRegistry);
              if (subBuilder != null) {
                subBuilder.mergeFrom(appEngineRoutingOverride_);
                appEngineRoutingOverride_ = subBuilder.buildPartial();
              }

              break;
            }
          default:
            {
              if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
    } finally {
      this.unknownFields = unknownFields.build();
      makeExtensionsImmutable();
    }
  }

  public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
    return com.google.cloud.tasks.v2beta3.TargetProto
        .internal_static_google_cloud_tasks_v2beta3_AppEngineHttpQueue_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.tasks.v2beta3.TargetProto
        .internal_static_google_cloud_tasks_v2beta3_AppEngineHttpQueue_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.class,
            com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.Builder.class);
  }

  public static final int APP_ENGINE_ROUTING_OVERRIDE_FIELD_NUMBER = 1;
  private com.google.cloud.tasks.v2beta3.AppEngineRouting appEngineRoutingOverride_;
  /**
   *
   *
   *

   * Overrides for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   * If set, `app_engine_routing_override` is used for all tasks in
   * the queue, no matter what the setting is for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   *

   *
   * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
   */
  public boolean hasAppEngineRoutingOverride() {
    return appEngineRoutingOverride_ != null;
  }
  /**
   *
   *
   *

   * Overrides for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   * If set, `app_engine_routing_override` is used for all tasks in
   * the queue, no matter what the setting is for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   *

   *
   * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
   */
  public com.google.cloud.tasks.v2beta3.AppEngineRouting getAppEngineRoutingOverride() {
    return appEngineRoutingOverride_ == null
        ? com.google.cloud.tasks.v2beta3.AppEngineRouting.getDefaultInstance()
        : appEngineRoutingOverride_;
  }
  /**
   *
   *
   *

   * Overrides for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   * If set, `app_engine_routing_override` is used for all tasks in
   * the queue, no matter what the setting is for the
   * [task-level
   * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
   *

   *
   * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
   */
  public com.google.cloud.tasks.v2beta3.AppEngineRoutingOrBuilder
      getAppEngineRoutingOverrideOrBuilder() {
    return getAppEngineRoutingOverride();
  }

  private byte memoizedIsInitialized = -1;

  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
    if (appEngineRoutingOverride_ != null) {
      output.writeMessage(1, getAppEngineRoutingOverride());
    }
    unknownFields.writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (appEngineRoutingOverride_ != null) {
      size +=
          com.google.protobuf.CodedOutputStream.computeMessageSize(
              1, getAppEngineRoutingOverride());
    }
    size += unknownFields.getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof com.google.cloud.tasks.v2beta3.AppEngineHttpQueue)) {
      return super.equals(obj);
    }
    com.google.cloud.tasks.v2beta3.AppEngineHttpQueue other =
        (com.google.cloud.tasks.v2beta3.AppEngineHttpQueue) obj;

    boolean result = true;
    result = result && (hasAppEngineRoutingOverride() == other.hasAppEngineRoutingOverride());
    if (hasAppEngineRoutingOverride()) {
      result = result && getAppEngineRoutingOverride().equals(other.getAppEngineRoutingOverride());
    }
    result = result && unknownFields.equals(other.unknownFields);
    return result;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    if (hasAppEngineRoutingOverride()) {
      hash = (37 * hash) + APP_ENGINE_ROUTING_OVERRIDE_FIELD_NUMBER;
      hash = (53 * hash) + getAppEngineRoutingOverride().hashCode();
    }
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseDelimitedFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseDelimitedFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      com.google.protobuf.CodedInputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() {
    return newBuilder();
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(com.google.cloud.tasks.v2beta3.AppEngineHttpQueue prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *
   *
   *

   * App Engine HTTP queue.
   * The task will be delivered to the App Engine application hostname
   * specified by its
   * [AppEngineHttpQueue][google.cloud.tasks.v2beta3.AppEngineHttpQueue] and
   * [AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest]. The
   * documentation for
   * [AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest]
   * explains how the task's host URL is constructed.
   * Using [AppEngineHttpQueue][google.cloud.tasks.v2beta3.AppEngineHttpQueue]
   * requires
   * [`appengine.applications.get`](https://cloud.google.com/appengine/docs/admin-api/access-control)
   * Google IAM permission for the project
   * and the following scope:
   * `https://www.googleapis.com/auth/cloud-platform`
   *

   *
   * Protobuf type {@code google.cloud.tasks.v2beta3.AppEngineHttpQueue}
   */
  public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
      implements
      // @@protoc_insertion_point(builder_implements:google.cloud.tasks.v2beta3.AppEngineHttpQueue)
      com.google.cloud.tasks.v2beta3.AppEngineHttpQueueOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
      return com.google.cloud.tasks.v2beta3.TargetProto
          .internal_static_google_cloud_tasks_v2beta3_AppEngineHttpQueue_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.cloud.tasks.v2beta3.TargetProto
          .internal_static_google_cloud_tasks_v2beta3_AppEngineHttpQueue_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.class,
              com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.Builder.class);
    }

    // Construct using com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }

    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
    }

    @java.lang.Override
    public Builder clear() {
      super.clear();
      if (appEngineRoutingOverrideBuilder_ == null) {
        appEngineRoutingOverride_ = null;
      } else {
        appEngineRoutingOverride_ = null;
        appEngineRoutingOverrideBuilder_ = null;
      }
      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
      return com.google.cloud.tasks.v2beta3.TargetProto
          .internal_static_google_cloud_tasks_v2beta3_AppEngineHttpQueue_descriptor;
    }

    @java.lang.Override
    public com.google.cloud.tasks.v2beta3.AppEngineHttpQueue getDefaultInstanceForType() {
      return com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.cloud.tasks.v2beta3.AppEngineHttpQueue build() {
      com.google.cloud.tasks.v2beta3.AppEngineHttpQueue result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.cloud.tasks.v2beta3.AppEngineHttpQueue buildPartial() {
      com.google.cloud.tasks.v2beta3.AppEngineHttpQueue result =
          new com.google.cloud.tasks.v2beta3.AppEngineHttpQueue(this);
      if (appEngineRoutingOverrideBuilder_ == null) {
        result.appEngineRoutingOverride_ = appEngineRoutingOverride_;
      } else {
        result.appEngineRoutingOverride_ = appEngineRoutingOverrideBuilder_.build();
      }
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return (Builder) super.clone();
    }

    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return (Builder) super.setField(field, value);
    }

    @java.lang.Override
    public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
      return (Builder) super.clearField(field);
    }

    @java.lang.Override
    public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return (Builder) super.clearOneof(oneof);
    }

    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
      return (Builder) super.setRepeatedField(field, index, value);
    }

    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return (Builder) super.addRepeatedField(field, value);
    }

    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.cloud.tasks.v2beta3.AppEngineHttpQueue) {
        return mergeFrom((com.google.cloud.tasks.v2beta3.AppEngineHttpQueue) other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.cloud.tasks.v2beta3.AppEngineHttpQueue other) {
      if (other == com.google.cloud.tasks.v2beta3.AppEngineHttpQueue.getDefaultInstance())
        return this;
      if (other.hasAppEngineRoutingOverride()) {
        mergeAppEngineRoutingOverride(other.getAppEngineRoutingOverride());
      }
      this.mergeUnknownFields(other.unknownFields);
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.cloud.tasks.v2beta3.AppEngineHttpQueue parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage =
            (com.google.cloud.tasks.v2beta3.AppEngineHttpQueue) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private com.google.cloud.tasks.v2beta3.AppEngineRouting appEngineRoutingOverride_ = null;
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.tasks.v2beta3.AppEngineRouting,
            com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder,
            com.google.cloud.tasks.v2beta3.AppEngineRoutingOrBuilder>
        appEngineRoutingOverrideBuilder_;
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public boolean hasAppEngineRoutingOverride() {
      return appEngineRoutingOverrideBuilder_ != null || appEngineRoutingOverride_ != null;
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public com.google.cloud.tasks.v2beta3.AppEngineRouting getAppEngineRoutingOverride() {
      if (appEngineRoutingOverrideBuilder_ == null) {
        return appEngineRoutingOverride_ == null
            ? com.google.cloud.tasks.v2beta3.AppEngineRouting.getDefaultInstance()
            : appEngineRoutingOverride_;
      } else {
        return appEngineRoutingOverrideBuilder_.getMessage();
      }
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public Builder setAppEngineRoutingOverride(
        com.google.cloud.tasks.v2beta3.AppEngineRouting value) {
      if (appEngineRoutingOverrideBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        appEngineRoutingOverride_ = value;
        onChanged();
      } else {
        appEngineRoutingOverrideBuilder_.setMessage(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public Builder setAppEngineRoutingOverride(
        com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder builderForValue) {
      if (appEngineRoutingOverrideBuilder_ == null) {
        appEngineRoutingOverride_ = builderForValue.build();
        onChanged();
      } else {
        appEngineRoutingOverrideBuilder_.setMessage(builderForValue.build());
      }

      return this;
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public Builder mergeAppEngineRoutingOverride(
        com.google.cloud.tasks.v2beta3.AppEngineRouting value) {
      if (appEngineRoutingOverrideBuilder_ == null) {
        if (appEngineRoutingOverride_ != null) {
          appEngineRoutingOverride_ =
              com.google.cloud.tasks.v2beta3.AppEngineRouting.newBuilder(appEngineRoutingOverride_)
                  .mergeFrom(value)
                  .buildPartial();
        } else {
          appEngineRoutingOverride_ = value;
        }
        onChanged();
      } else {
        appEngineRoutingOverrideBuilder_.mergeFrom(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public Builder clearAppEngineRoutingOverride() {
      if (appEngineRoutingOverrideBuilder_ == null) {
        appEngineRoutingOverride_ = null;
        onChanged();
      } else {
        appEngineRoutingOverride_ = null;
        appEngineRoutingOverrideBuilder_ = null;
      }

      return this;
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder
        getAppEngineRoutingOverrideBuilder() {

      onChanged();
      return getAppEngineRoutingOverrideFieldBuilder().getBuilder();
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    public com.google.cloud.tasks.v2beta3.AppEngineRoutingOrBuilder
        getAppEngineRoutingOverrideOrBuilder() {
      if (appEngineRoutingOverrideBuilder_ != null) {
        return appEngineRoutingOverrideBuilder_.getMessageOrBuilder();
      } else {
        return appEngineRoutingOverride_ == null
            ? com.google.cloud.tasks.v2beta3.AppEngineRouting.getDefaultInstance()
            : appEngineRoutingOverride_;
      }
    }
    /**
     *
     *
     *

     * Overrides for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     * If set, `app_engine_routing_override` is used for all tasks in
     * the queue, no matter what the setting is for the
     * [task-level
     * app_engine_routing][google.cloud.tasks.v2beta3.AppEngineHttpRequest.app_engine_routing].
     *

     *
     * .google.cloud.tasks.v2beta3.AppEngineRouting app_engine_routing_override = 1;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.tasks.v2beta3.AppEngineRouting,
            com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder,
            com.google.cloud.tasks.v2beta3.AppEngineRoutingOrBuilder>
        getAppEngineRoutingOverrideFieldBuilder() {
      if (appEngineRoutingOverrideBuilder_ == null) {
        appEngineRoutingOverrideBuilder_ =
            new com.google.protobuf.SingleFieldBuilderV3<
                com.google.cloud.tasks.v2beta3.AppEngineRouting,
                com.google.cloud.tasks.v2beta3.AppEngineRouting.Builder,
                com.google.cloud.tasks.v2beta3.AppEngineRoutingOrBuilder>(
                getAppEngineRoutingOverride(), getParentForChildren(), isClean());
        appEngineRoutingOverride_ = null;
      }
      return appEngineRoutingOverrideBuilder_;
    }

    @java.lang.Override
    public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFieldsProto3(unknownFields);
    }

    @java.lang.Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.cloud.tasks.v2beta3.AppEngineHttpQueue)
  }

  // @@protoc_insertion_point(class_scope:google.cloud.tasks.v2beta3.AppEngineHttpQueue)
  private static final com.google.cloud.tasks.v2beta3.AppEngineHttpQueue DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new com.google.cloud.tasks.v2beta3.AppEngineHttpQueue();
  }

  public static com.google.cloud.tasks.v2beta3.AppEngineHttpQueue getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<AppEngineHttpQueue> PARSER =
      new com.google.protobuf.AbstractParser<AppEngineHttpQueue>() {
        @java.lang.Override
        public AppEngineHttpQueue parsePartialFrom(
            com.google.protobuf.CodedInputStream input,
            com.google.protobuf.ExtensionRegistryLite extensionRegistry)
            throws com.google.protobuf.InvalidProtocolBufferException {
          return new AppEngineHttpQueue(input, extensionRegistry);
        }
      };

  public static com.google.protobuf.Parser<AppEngineHttpQueue> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<AppEngineHttpQueue> getParserForType() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.cloud.tasks.v2beta3.AppEngineHttpQueue getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }
}


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.generators.ContactDataGenerator;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class ContactDeletionTests extends TestBase {

    @BeforeMethod
    public void ensurePreconditions() {
        app.goTo().homePage();
        if (app.db().contacts().isEmpty()) {
            app.contacts().create(ContactDataGenerator.getDefaultContactData());
        }
    }

    @Test
    public void testContactDeletion() {
        Contacts before = app.db().contacts();
        ContactData deletingContact = before.iterator().next();

        app.contacts().delete(deletingContact);
        assertThat(app.contacts().count(), equalTo(before.size() - 1));

        Contacts after = app.db().contacts();
        assertThat(after, equalTo(before.without(deletingContact)));

        verifyContactListInUI();
    }
}


invalidUrl: URL no válida, por ejemplo: http://www.test.com


text: Just a bunch of Resources used across this Repository


text:
@interface SpdyDnsResolver : NSObject

+(SpdyDnsResult*)lookupURL:(NSURL*)url;
+(SpdyDnsResult*)lookupHost:(NSString*)host;
+(SpdyDnsResult*)lookupHost:(NSString*)host withPort:(NSUInteger)port;

@end


text:
package org.heaven7.core.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * {@link Logger#v(String, String, String)} i like
 *
 * @author heaven7
 */
public class Logger {

	private static final String DEFAULT_LOG_PATH = android.os.Environment
			.getExternalStorageDirectory().getPath() + "/heaven7/log.txt";

	private static int sLOG_LEVEL = 6;// default all

	public static final int VERBOSE = 5; /* the lowest */
	public static final int DEBUG = 4;
	public static final int INFO = 3;
	public static final int WARNING = 2;
	public static final int ERROR = 1;
	/**default true(only called internal)*/
	public static boolean IsDebug = true;

	/** enable or disable debug */
	public static void setDebug(boolean debug) {
		IsDebug = debug;
		if (debug)
			setLevel(VERBOSE);
		else
			setLevel(INFO);
	}

	/**
	 */
	public static void setLevel(int lowestLevel) {
		switch (lowestLevel) {
		case VERBOSE:
			sLOG_LEVEL = 6;
			break;

		case DEBUG:
			sLOG_LEVEL = 5;
			break;

		case INFO:
			sLOG_LEVEL = 4;

			break;

		case WARNING:
		case ERROR:
			sLOG_LEVEL = 3;
			break;

		default:
			throw new IllegalArgumentException("caused by log lowestLevel="
					+ lowestLevel);
		}
	}

	// verbose
	public static void v(String tag, String msg) {
		if (sLOG_LEVEL > VERBOSE) {
			Log.v(tag, msg);
		}
	}

	public static void v(String tag, String methodTag, String msg) {
		if (sLOG_LEVEL > VERBOSE) {
			Log.v(tag, "called [ " + methodTag + "() ]: " + msg);
		}
	}

	// debug
	public static void d(String tag, String msg) {
		if (sLOG_LEVEL > DEBUG) {
			Log.d(tag, msg);
		}
	}

	public static void d(String tag, String methodTag, String msg) {
		if (sLOG_LEVEL > DEBUG) {
			Log.d(tag, "called [ " + methodTag + "() ]: " + msg);
		}
	}

	// info
	public static void i(String tag, String msg) {
		if (sLOG_LEVEL > INFO) {
			Log.i(tag, msg);
		}
	}

	public static void i(String tag, String methodTag, String msg) {
		if (sLOG_LEVEL > INFO) {
			Log.i(tag, "called [ " + methodTag + "() ]: " + msg);
		}
	}

	// warning
	public static void w(String tag, String msg) {
		if (sLOG_LEVEL > WARNING) {
			Log.w(tag, msg);
		}
	}

	public static void w(String tag, String methodTag, String msg) {
		if (sLOG_LEVEL > WARNING) {
			Log.w(tag, "called [ " + methodTag + "() ]: " + msg);
		}
	}

	public static void w(String tag, Throwable throwable) {
		if (sLOG_LEVEL > WARNING) {
			Log.w(tag, throwable);
		}
	}

	// error
	public static void e(String tag, String msg) {
		if (sLOG_LEVEL > ERROR) {
			Log.e(tag, msg);
		}
	}

	public static void e(String tag, String methodTag, String msg) {
		if (sLOG_LEVEL > ERROR) {
			Log.e(tag, "called [ " + methodTag + "() ]: " + msg);
		}
	}

	// =========== write sd =====================//
	public static void write2SD(String tag, String message, String filename,
			boolean append) {
		BufferedWriter bw = null;
		try {
            bw = new BufferedWriter(new FileWriter(
					createFileIfNeed(filename), append));// append
			bw.append("[ Time=" + FORMATER.format(new Date()) + " ] :tag=" + tag + " ,message=" + message + " \r\n");
			bw.newLine();
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null)
				try {
					bw.close();
				} catch (IOException e) {
				}
		}
	}
	public static File createFileIfNeed(String filePath){
		File file=null;
		try {
			file = new File(filePath);
			File p = file.getParentFile();
			if(p!=null && !p.exists()){
				p.mkdirs();
			}
			if(!file.exists()){//need permission : mount_unmount_filesystem
				//permission.MOUNT_UNMOUNT_FILESYSTEMS
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	/** use default append */
	public static void write2SD(String tag, String message, String filename) {
		write2SD(tag, message, filename, true);
	}

	public static void write2SD(String tag, String message, boolean append) {
		write2SD(tag, message, DEFAULT_LOG_PATH, append);
	}

	/** use default file and append */
	public static void write2SD(String tag, String message) {
		write2SD(tag, message, DEFAULT_LOG_PATH, true);
	}

	public static void write2SD(String tag, Throwable t, String filename,
			boolean append) {
		write2SD(tag, toString(t), filename, append);
	}

	public static void write2SD(String tag, Throwable t, boolean append) {
		write2SD(tag, toString(t), DEFAULT_LOG_PATH, append);
	}

	/** use default append */
	public static void write2SD(String tag, Throwable t, String filename) {
		write2SD(tag, toString(t), filename, true);
	}

	/** use default file and append */
	public static void write2SD(String tag, Throwable t) {
		write2SD(tag, toString(t), DEFAULT_LOG_PATH, true);
	}

	public static String toString(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);

		t.printStackTrace(pw);
		Throwable cause = t.getCause();
		while (cause != null) {
			cause.printStackTrace(pw);
			cause = cause.getCause();
		}
		pw.flush();
		String data = sw.toString();
		pw.close();
		return data;
	}

	public static void deleteDefaultLogFile(){
		deleteLogFile(DEFAULT_LOG_PATH);
	}
	public static void deleteLogFile(String path){
		File file = new File(path);
		if(file.exists() && !file.delete()){
			Logger.w(null, "cannot delete log file!");
		}
	}
	public static String getDefaultLogInfo(){
		return getLogInfo(DEFAULT_LOG_PATH);
	}
	public static String getLogInfo(String path){
		File file = new File(path);
		if(file.exists()){
			BufferedReader br =null;
			try {
				StringBuilder sb = new StringBuilder();
				br = new BufferedReader(new FileReader(file));
				String line;
				while((line = br.readLine())!=null){
					sb.append(line);
				}
				return sb.toString();
			} catch (FileNotFoundException e) {
				return null;
			} catch (IOException e) {
				return null;
			}finally{
				if(br!=null)
					try {
						br.close();
					} catch (IOException e) {
					}
			}
		}
		return null;
	}

	public static boolean isDefaultLogExist(){
		return new File(DEFAULT_LOG_PATH).exists();
	}

	public static final SimpleDateFormat FORMATER = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
}


text:
void
test_mongo_sync_cmd_authenticate_cache (void)
{
  mongo_sync_conn_recovery_cache *cache;
  mongo_sync_connection *c;

  begin_network_tests (8);

  cache = mongo_sync_conn_recovery_cache_new ();
  mongo_sync_conn_recovery_cache_seed_add (cache,
                                           config.primary_host,
                                           config.primary_port);

  c = mongo_sync_connect_recovery_cache (cache, TRUE);

  mongo_sync_cmd_user_add (c, config.db, "test", "s3kr1+");

  ok (mongo_sync_cmd_authenticate (c, config.db, "test", "s3kr1+") == TRUE,
      "mongo_sync_cmd_authenticate() works");

  mongo_sync_disconnect (c);

  ok ((cache->auth.db != NULL) && (strcmp (cache->auth.db, config.db) == 0),
      "db is cached");

  ok ((cache->auth.user != NULL) && (strcmp (cache->auth.user, "test") == 0),
      "user is cached");

  ok ((cache->auth.pw != NULL) && (strcmp (cache->auth.pw, "s3kr1+") == 0),
      "pw is cached");

  c = mongo_sync_connect_recovery_cache (cache, TRUE);

  ok (c->auth.db != NULL, "db is loaded from cache");

  ok (c->auth.user != NULL, "username is loaded from cache");

  ok (c->auth.pw != NULL, "password is loaded from cache");

  ok (mongo_sync_cmd_authenticate (c,
                                   c->auth.db,
                                   c->auth.user,
                                   c->auth.pw) == TRUE,
      "mongo_sync_cmd_authenticate() works with cached auth. credentials");

  mongo_sync_disconnect (c);
  mongo_sync_conn_recovery_cache_free (cache);

  end_network_tests ();
}

RUN_TEST (8, mongo_sync_cmd_authenticate_cache);


text:
struct query_lonlat
{
    double lon;
    double lat;
};

struct query_result
{
    std::string layer;
    double distance;
    double x_hit;
    double y_hit;
    mapnik::feature_ptr feature;
    explicit query_result() :
     layer(),
     distance(0),
     x_hit(0),
     y_hit(0) {}
};

struct query_hit
{
    double distance;
    unsigned feature_id;
};

struct queryMany_result
{
    std::map<unsigned,query_result> features;
    std::map<unsigned,std::vector<query_hit> > hits;
};

class VectorTile: public Nan::ObjectWrap
{
public:
    static Nan::Persistent<v8::FunctionTemplate> constructor;
    static void Initialize(v8::Local<v8::Object> target);
    static NAN_METHOD(New);
    static NAN_METHOD(getData);
    static NAN_METHOD(getDataSync);
    static v8::Local<v8::Value> _getDataSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static void get_data(uv_work_t* req);
    static void after_get_data(uv_work_t* req);
    static NAN_METHOD(render);
    static NAN_METHOD(toJSON);
    static NAN_METHOD(query);
    static void EIO_Query(uv_work_t* req);
    static void EIO_AfterQuery(uv_work_t* req);
    static std::vector<query_result> _query(VectorTile* d, double lon, double lat, double tolerance, std::string const& layer_name);
    static bool _querySort(query_result const& a, query_result const& b);
    static v8::Local<v8::Array> _queryResultToV8(std::vector<query_result> const& result);
    static NAN_METHOD(queryMany);
    static void _queryMany(queryMany_result & result, VectorTile* d, std::vector<query_lonlat> const& query, double tolerance, std::string const& layer_name, std::vector<std::string> const& fields);
    static bool _queryManySort(query_hit const& a, query_hit const& b);
    static v8::Local<v8::Object> _queryManyResultToV8(queryMany_result const& result);
    static void EIO_QueryMany(uv_work_t* req);
    static void EIO_AfterQueryMany(uv_work_t* req);
    static NAN_METHOD(extent);
    static NAN_METHOD(bufferedExtent);
    static NAN_METHOD(names);
    static NAN_METHOD(layer);
    static NAN_METHOD(emptyLayers);
    static NAN_METHOD(paintedLayers);
    static v8::Local<v8::Value> _toGeoJSONSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(toGeoJSON);
    static NAN_METHOD(toGeoJSONSync);
    static void to_geojson(uv_work_t* req);
    static void after_to_geojson(uv_work_t* req);
    static NAN_METHOD(addGeoJSON);
    static NAN_METHOD(addImage);
    static void EIO_AddImage(uv_work_t* req);
    static void EIO_AfterAddImage(uv_work_t* req);
    static v8::Local<v8::Value> _addImageSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(addImageSync);
    static NAN_METHOD(addImageBuffer);
    static void EIO_AddImageBuffer(uv_work_t* req);
    static void EIO_AfterAddImageBuffer(uv_work_t* req);
    static v8::Local<v8::Value> _addImageBufferSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(addImageBufferSync);
    static void EIO_RenderTile(uv_work_t* req);
    static void EIO_AfterRenderTile(uv_work_t* req);
    static NAN_METHOD(setData);
    static void EIO_SetData(uv_work_t* req);
    static void EIO_AfterSetData(uv_work_t* req);
    static v8::Local<v8::Value> _setDataSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(setDataSync);
    static NAN_METHOD(addData);
    static void EIO_AddData(uv_work_t* req);
    static void EIO_AfterAddData(uv_work_t* req);
    static v8::Local<v8::Value> _addDataSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(addDataSync);
    static NAN_METHOD(composite);
    static NAN_METHOD(compositeSync);
    static v8::Local<v8::Value> _compositeSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static void EIO_Composite(uv_work_t* req);
    static void EIO_AfterComposite(uv_work_t* req);
    static NAN_METHOD(painted);
    static NAN_METHOD(clearSync);
    static v8::Local<v8::Value> _clearSync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(clear);
    static void EIO_Clear(uv_work_t* req);
    static void EIO_AfterClear(uv_work_t* req);
    static NAN_METHOD(empty);
    static NAN_METHOD(info);
#if BOOST_VERSION >= 105800
    static NAN_METHOD(reportGeometrySimplicity);
    static void EIO_ReportGeometrySimplicity(uv_work_t* req);
    static void EIO_AfterReportGeometrySimplicity(uv_work_t* req);
    static NAN_METHOD(reportGeometrySimplicitySync);
    static v8::Local<v8::Value> _reportGeometrySimplicitySync(Nan::NAN_METHOD_ARGS_TYPE info);
    static NAN_METHOD(reportGeometryValidity);
    static void EIO_ReportGeometryValidity(uv_work_t* req);
    static void EIO_AfterReportGeometryValidity(uv_work_t* req);
    static NAN_METHOD(reportGeometryValiditySync);
    static v8::Local<v8::Value> _reportGeometryValiditySync(Nan::NAN_METHOD_ARGS_TYPE info);
#endif // BOOST_VERSION >= 105800

    static NAN_GETTER(get_tile_x);
    static NAN_SETTER(set_tile_x);
    static NAN_GETTER(get_tile_y);
    static NAN_SETTER(set_tile_y);
    static NAN_GETTER(get_tile_z);
    static NAN_SETTER(set_tile_z);
    static NAN_GETTER(get_tile_size);
    static NAN_SETTER(set_tile_size);
    static NAN_GETTER(get_buffer_size);
    static NAN_SETTER(set_buffer_size);

    VectorTile(std::uint64_t z,
               std::uint64_t x,
               std::uint64_t y,
               std::uint32_t tile_size,
               std::int32_t buffer_size);

    void clear()
    {
        tile_->clear();
    }

    std::uint32_t tile_size() const
    {
        return tile_->tile_size();
    }

    void tile_size(std::uint32_t val)
    {
        tile_->tile_size(val);
    }

    std::int32_t buffer_size() const
    {
        return tile_->buffer_size();
    }

    void buffer_size(std::int32_t val)
    {
        tile_->buffer_size(val);
    }

    mapnik::vector_tile_impl::merc_tile_ptr & get_tile()
    {
        return tile_;
    }

    mapnik::vector_tile_impl::merc_tile_ptr const& get_tile() const
    {
        return tile_;
    }

    using Nan::ObjectWrap::Ref;
    using Nan::ObjectWrap::Unref;

private:
    mapnik::vector_tile_impl::merc_tile_ptr tile_;
    ~VectorTile();
};

#endif // __NODE_MAPNIK_VECTOR_TILE_H__


text:
<?php
/**
 * Represents a group of users in the system
 *
 * @package StartupAPI
 * @subpackage Analytics\CohortAnalysis
 */
class Cohort {
	/**
	 * @var string Cohort identifier to be used in query string parameters and slugs
	 */
	private $id;
	/**
	 * @var string Cohort display name
	 */
	private $title;
	/**
	 * @var int Total number of members in the cohort
	 */
	private $total;

	/**
	 * Creates new cohort
	 *
	 * @param string $id Cohort ID string
	 * @param string $title Cohort display name
	 * @param int $total Total number of members
	 */
	public function __construct($id, $title, $total) {
		$this->id = $id;
		$this->title = $title;
		$this->total = $total;
	}

	/**
	 * Returns cohort ID string
	 *
	 * @return string
	 */
	public function getID() {
		return $this->id;
	}

	/**
	 * Returns cohort display name
	 *
	 * @return string
	 */
	public function getTitle() {
		return $this->title;
	}

	/**
	 * Returns total number of members in the cohort
	 *
	 * @return int
	 */
	public function getTotal() {
		return $this->total;
	}
}

/**
 * Defines a method to break down all users into cohorts
 *
 * Whatever you want to split them by registration date, by gender or by salary
 * range, just subclass this class and add it to UserConfig::$cohort_providers array
 *
 * <code>
 * UserConfig::$cohort_providers[] = new MyOwnCohortProvider();
 * </code>
 *
 * @package StartupAPI
 * @subpackage Analytics\CohortAnalysis
 *
 * @see UserConfig::$cohort_providers
 */
abstract class CohortProvider {
	/**
	 * @var string Cohort provider ID string
	 */
	private $id;
	/**
	 * @var string Cohort provider display name
	 */
	private $title;

	/**
	 * Whatever or not cohorts created by this provider create a sequence
	 * and have previous cohort to compare to.
	 *
	 * Most of cohort lists don't create cohorts that are sequential, no reason to compare them
	 *
	 * @var boolean
	 */
	protected $compare_to_previous_cohort = false;

	/**
	 * Creates a cohort provider object
	 *
	 * Add them to UserConfig::$cohort_providers[] array to be used in admin UI
	 *
	 * @param string $id ID of the provider
	 * @param string $title Display name of the provider
	 *
	 * @see UserConfig::$cohort_providers
	 */
	public function __construct($id, $title) {
		$this->id = $id;
		$this->title = $title;
	}

	/**
	 * Returns provider ID
	 *
	 * @return string Provider ID
	 */
	public function getID() {
		return $this->id;
	}

	/**
	 * Returns provider display name
	 *
	 * @return string Provider display name
	 */
	public function getTitle() {
		return $this->title;
	}

	/**
	 * Returns the cohort comparison flag
	 *
	 * @return boolean Can we compare to previous cohort or not
	 */
	public function canCompareToPreviousCohort() {
		return $this->compare_to_previous_cohort;
	}

	/**
	 * Returns a list of cohorts tracked by specific CohortProvider
	 *
	 * @return array $cohorts an array of Cohort objects
	 */
	public abstract function getCohorts();

	/**
	 * Returns the name of dimension this provider separates users by (e.g. "registration date" or "gender")
	 *
	 * @return string Name of the dimension
	 */
	public abstract function getDimensionTitle();

	/**
	 * Returns a number of users who performed each activity for each period (specified the activity period length)
	 *
	 * If activity ID is provided, returns levels only for specific activity, otherwise for all activities.
	 *
	 * @param int $activityid Activity ID (null for all activities)
	 * @param int $actnum Number of days in activity period
	 *
	 * @return array Two dimensional array of buckets by cohort_id and activity period as keys and number of users in the bucket as values
	 *
	 * @throws DBException
	 */
	public function getActivityRate($activityid, $actnum)
	{
		$db = UserConfig::getDB();

		$siteadminsstring = null;
		if (count(UserConfig::$admins) > 0) {
			$siteadminsstring = implode(", ", UserConfig::$admins);
		}

		$aggregates = array();

		$query = 'SELECT u.cohort_id AS cohort_id,
			FLOOR(DATEDIFF(a.time, u.regtime) / ?) AS actperiod,
			COUNT(DISTINCT u.id) AS total
			FROM `u_activity` AS a
				INNER JOIN ('.$this->getCohortSQL().') AS u
					ON a.user_id = u.id';
		if (!is_null($activityid)) {
			$query .= '	WHERE `activity_id` = ?';
		}

		if (!is_null($siteadminsstring)) {
			$query .= "\nAND u.id NOT IN ($siteadminsstring)";
		}

		$query .= '
			GROUP BY cohort_id, actperiod
			ORDER BY actperiod ASC';

		if ($stmt = $db->prepare($query))
		{
			if (!is_null($activityid)) {
				if (!$stmt->bind_param('ii', $actnum, $activityid))
				{
					throw new DBBindParamException($db, $stmt);
				}
			} else {
				if (!$stmt->bind_param('i', $actnum))
				{
					throw new DBBindParamException($db, $stmt);
				}
			}
			if (!$stmt->execute())
			{
				throw new DBExecuteStmtException($db, $stmt);
			}
			if (!$stmt->bind_result($cohort_id, $actperiod, $activeusers))
			{
				throw new DBBindResultException($db, $stmt);
			}

			while($stmt->fetch() === TRUE)
			{
				$aggregates[$cohort_id][$actperiod] = $activeusers;
			}

			$stmt->close();
		}
		else
		{
			throw new DBPrepareStmtException($db);
		}

		return $aggregates;
	}

	/**
	 * Returns SQL statement used to separate users into cohorts
	 *
	 * Subclasses must override this method and provide an SQL statement returning 3 columns:
	 * - id (ser ID, from users table)
	 * - re_time (user registration datetime, from users table)
	 * - cohort_id (cohort ID specific to your provider
	 *
	 * Where cohort_id is the main information provided by this method
	 * and used to put users into different buckets.
	 */
	abstract function getCohortSQL();

}

/**
 * This class allows dropping users into cohorts by registration date
 *
 * @package StartupAPI
 * @subpackage Analytics\CohortAnalysis
 */
class GenerationCohorts extends CohortProvider {
	/**
	 * @var int DescriptionDefines a period constant: year
	 */
	const YEAR = 0;
	/**
	 * @var int Defines a period constant: month
	 */
	const MONTH = 1;
	/**
	 * @var int Defines a period constant: week
	 */
	const WEEK = 2;

	/**
	 * A period of time between generations
	 *
	 * @var int One of GenerationCohorts::YEAR, GenerationCohorts::MONTH or GenerationCohorts::WEEK
	 */
	private $period;

	/**
	 * Creates a cohort provider to separate users by generation
	 *
	 * Most commonly used for analysis, usually for month-to-month comparison
	 *
	 * @param int $period One of GenerationCohorts::YEAR, GenerationCohorts::MONTH (default) or GenerationCohorts::WEEK
	 *
	 * @throws StartupAPIException
	 */
	public function __construct($period = self::MONTH) {
		$title = 'User genrations by ';
		$id = 'gen';

		switch ($period) {
			case self::MONTH:
				$title .= "month";
				$id .= "month";
				break;
			case self::YEAR:
				$title .= "year";
				$id .= "year";
				break;
			case self::WEEK:
				$title .= "week";
				$id .= "week";
				break;
			default:
				throw new StartupAPIException('Wrong generation period');
		}

		parent::__construct($id, $title);

		// cohorts are chronological so it makes sense to compare to previous
		$this->compare_to_previous_cohort = true;

		$this->period = $period;
	}

	/**
	 * Always returns "Reg. date"
	 *
	 * @return string
	 */
	public function getDimensionTitle() {
		return 'Reg. date';
	}

	/**
	 * Returns a list of generation cohorts for all generations of users registered so far
	 *
	 * @return array $cohorts An array of Cohort objects for each generation
	 *
	 * @throws StartupAPIException
	 * @throws DBException
	 */
	public function getCohorts() {
		$db = UserConfig::getDB();

		// an array of cohorts to return
		$cohorts = array();

		/**
		 * The query must return a unique cohort_id, title and total members
		 */
		switch ($this->period) {
			case self::MONTH:
				$query = "SELECT EXTRACT(YEAR_MONTH FROM regtime) AS cohort_id,
					DATE_FORMAT(regtime, '%b %Y') AS title,
					COUNT(*) AS totals
					FROM u_users";
				break;
			case self::YEAR:
				$query = "SELECT YEAR(regtime) AS cohort_id,
					YEAR(regtime) AS title,
					COUNT(*) AS totals
					FROM u_users";
				break;
			case self::WEEK:
				$query = "SELECT YEARWEEK(regtime) AS cohort_id,
					CONCAT(
						DATE_FORMAT(
							DATE(DATE_SUB(regtime, INTERVAL WEEKDAY(regtime) DAY)),
							'%b %e, %Y'
						), ' - ',
						DATE_FORMAT(
							DATE(DATE_ADD(regtime, INTERVAL 6-WEEKDAY(regtime) DAY)),
							'%b %e, %Y'
						)
					) AS title,
					COUNT(*) AS totals
					FROM u_users";
				break;
			default:
				throw new StartupAPIException('Wrong generation period');
		}

		// Excluding site administrators
		if (count(UserConfig::$admins) > 0) {
			$query .= "\nWHERE id NOT IN (" . implode(", ", UserConfig::$admins) . ")";
		}

		$query .= ' GROUP BY cohort_id ORDER BY regtime DESC';

		if ($stmt = $db->prepare($query))
		{
			if (!$stmt->execute())
			{
				throw new DBExecuteStmtException($db, $stmt);
			}
			if (!$stmt->bind_result($cohort_id, $title, $total))
			{
				throw new DBBindResultException($db, $stmt);
			}

			while($stmt->fetch() === TRUE)
			{
				$cohorts[] = new Cohort($cohort_id, $title, $total);
			}
			$stmt->close();
		}
		else
		{
			throw new DBPrepareStmtException($db);
		}

		return $cohorts;
	}

	/**
	 * SQL statement for separation of users into generations
	 *
	 * @return string SQL statement for generating a resultset with id, regtime and cohort_id
	 *
	 * @throws StartupAPIException
	 */
	public function getCohortSQL() {
		switch ($this->period) {
			case self::MONTH:
				$query = 'SELECT id, regtime, EXTRACT(YEAR_MONTH FROM regtime) AS cohort_id
					FROM u_users';
				break;
			case self::YEAR:
				$query = 'SELECT id, regtime, YEAR(regtime) AS cohort_id
					FROM u_users';
				break;
			case self::WEEK:
				$query = 'SELECT id, regtime, YEARWEEK(regtime) AS cohort_id
					FROM u_users';
				break;
			default:
				throw new StartupAPIException('Wrong generation period');
		}

		return $query;
	}
}

/**
 * This class allows dropping users into cohorts by registration method / module
 *
 * @package StartupAPI
 * @subpackage Analytics\CohortAnalysis
 */
class RegMethodCohorts extends CohortProvider {
	/**
	 * Creates new cohort provider based on user's method of registration (Authentication Module)
	 */
	public function __construct() {
		parent::__construct('byregmethod', 'Users registration method');
	}

	/**
	 * Always returns "Reg. module"
	 *
	 * @return string "Reg. module"
	 */
	public function getDimensionTitle() {
		return 'Reg. module';
	}

	/**
	 * Returns a list of registration module cohorts for all modules users actually regusterd with
	 *
	 * @return array $cohorts An array of Cohort objects
	 *
	 * @throws DBException
	 */
	public function getCohorts() {
		$db = UserConfig::getDB();

		$cohort_titles = array();

		foreach (UserConfig::$authentication_modules as $module) {
			$cohort_titles[$module->getID()] = $module->getTitle();
		}

		/**
		 * The query must return a unique cohort_id, title and total members
		 */
		$query = 'SELECT regmodule AS cohort_id, COUNT(*) AS totals FROM u_users';

		$siteadminsstring = null;
		if (count(UserConfig::$admins) > 0) {
			$siteadminsstring = implode(", ", UserConfig::$admins);
		}

		if (!is_null($siteadminsstring)) {
			$query .= "\nWHERE id NOT IN ($siteadminsstring)";
		}

		$cohorts = array();

		$query .= ' GROUP BY cohort_id ORDER BY regtime DESC';

		if ($stmt = $db->prepare($query))
		{
			if (!$stmt->execute())
			{
				throw new DBExecuteStmtException($db, $stmt);
			}
			if (!$stmt->bind_result($cohort_id, $total))
			{
				throw new DBBindResultException($db, $stmt);
			}

			while($stmt->fetch() === TRUE)
			{
				$cohorts[] = new Cohort($cohort_id, $cohort_titles[$cohort_id], $total);
			}
			$stmt->close();
		}
		else
		{
			throw new DBPrepareStmtException($db);
		}

		return $cohorts;
	}

	/**
	 * SQL statement for separation of users into buckets by registration module
	 *
	 * @return string SQL statement for generating a resultset with id, regtime and cohort_id
	 */
	public function getCohortSQL() {
		return 'SELECT id, regtime, regmodule AS cohort_id FROM u_users';
	}
}