text:
#ifndef TNT_UTILS_CSTRING_H
#define TNT_UTILS_CSTRING_H

// NOTE: this header should not include STL headers

#include <utils/compiler.h>

#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

namespace utils {

//! \privatesection
struct hashCStrings {
    typedef const char* argument_type;
    typedef size_t result_type;
    result_type operator()(argument_type cstr) const noexcept {
        size_t hash = 5381;
        while (int c = *cstr++) {
            hash = (hash * 33u) ^ size_t(c);
        }
        return hash;
    }
};

template <size_t N>
using StringLiteral = const char[N];

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

class UTILS_PUBLIC CString {
public:
    using value_type      = char;
    using size_type       = uint32_t;
    using difference_type = int32_t;
    using reference       = value_type&;
    using const_reference = const value_type&;
    using pointer         = value_type*;
    using const_pointer   = const value_type*;
    using iterator        = value_type*;
    using const_iterator  = const value_type*;

    CString() noexcept {} // NOLINT(modernize-use-equals-default), Ubuntu compiler bug

    // Allocates memory and appends a null. This constructor can be used to hold arbitrary data
    // inside the string (i.e. it can contain nulls or non-ASCII encodings).
    CString(const char* cstr, size_t length);

    // Allocates memory for a string of size length plus space for the null terminating character.
    // Also initializes the memory to 0. This constructor can be used to hold arbitrary data
    // inside the string.
    explicit CString(size_t length);

    // Allocates memory and copies traditional C string content. Unlike the above constructor, this
    // does not allow embedded nulls. This is explicit because this operation is costly.
    explicit CString(const char* cstr);

    template<size_t N>
    CString(StringLiteral<N> const& other) noexcept // NOLINT(google-explicit-constructor)
            : CString(other, N - 1) {
    }

    CString(const CString& rhs);

    CString(CString&& rhs) noexcept {
        this->swap(rhs);
    }

    CString& operator=(const CString& rhs);

    CString& operator=(CString&& rhs) noexcept {
        this->swap(rhs);
        return *this;
    }

    ~CString() noexcept {
        if (mData) {
            free(mData - 1);
        }
    }

    void swap(CString& other) noexcept {
        // don't use std::swap(), we don't want an STL dependency in this file
        auto *temp = mCStr;
        mCStr = other.mCStr;
        other.mCStr = temp;
    }

    const_pointer c_str() const noexcept { return mCStr; }
    pointer c_str() noexcept { return mCStr; }
    const_pointer c_str_safe() const noexcept { return mData ? c_str() : ""; }
    const_pointer data() const noexcept { return c_str(); }
    pointer data() noexcept { return c_str(); }
    size_type size() const noexcept { return mData ? mData[-1].length : 0; }
    size_type length() const noexcept { return size(); }
    bool empty() const noexcept { return size() == 0; }

    iterator begin() noexcept { return mCStr; }
    iterator end() noexcept { return begin() + length(); }
    const_iterator begin() const noexcept { return data(); }
    const_iterator end() const noexcept { return begin() + length(); }
    const_iterator cbegin() const noexcept { return begin(); }
    const_iterator cend() const noexcept { return end(); }

    CString& replace(size_type pos, size_type len, const CString& str) noexcept;
    CString& insert(size_type pos, const CString& str) noexcept { return replace(pos, 0, str); }

    const_reference operator[](size_type pos) const noexcept {
        assert(pos < size());
        return begin()[pos];
    }

    reference operator[](size_type pos) noexcept {
        assert(pos < size());
        return begin()[pos];
    }

    const_reference at(size_type pos) const noexcept {
        assert(pos < size());
        return begin()[pos];
    }

    reference at(size_type pos) noexcept {
        assert(pos < size());
        return begin()[pos];
    }

    reference front() noexcept {
        assert(size());
        return begin()[0];
    }

    const_reference front() const noexcept {
        assert(size());
        return begin()[0];
    }

    reference back() noexcept {
        assert(size());
        return begin()[size() - 1];
    }

    const_reference back() const noexcept {
        assert(size());
        return begin()[size() - 1];
    }

    // placement new declared as "throw" to avoid the compiler's null-check
    inline void* operator new(size_t, void* ptr) {
        assert(ptr);
        return ptr;
    }

    struct Hasher : private hashCStrings {
        typedef CString argument_type;
        typedef size_t result_type;
        result_type operator()(const argument_type& s) const noexcept {
            return hashCStrings::operator()(s.c_str());
        }
    };

private:
    struct Data {
        size_type length;
    };

    // mCStr points to the C-string or nullptr. if non-null, mCStr is preceded by the string's size
    union {
        value_type *mCStr = nullptr;
        Data* mData; // Data is stored at mData[-1]
    };

    int compare(const CString& rhs) const noexcept {
        size_type lhs_size = size();
        size_type rhs_size = rhs.size();
        if (lhs_size < rhs_size) return -1;
        if (lhs_size > rhs_size) return 1;
        return strncmp(data(), rhs.data(), size());
    }

    friend bool operator==(CString const& lhs, CString const& rhs) noexcept {
        return (lhs.data() == rhs.data()) ||
               ((lhs.size() == rhs.size()) && !strncmp(lhs.data(), rhs.data(), lhs.size()));
    }
    friend bool operator!=(CString const& lhs, CString const& rhs) noexcept {
        return !(lhs == rhs);
    }
    friend bool operator<(CString const& lhs, CString const& rhs) noexcept {
        return lhs.compare(rhs) < 0;
    }
    friend bool operator>(CString const& lhs, CString const& rhs) noexcept {
        return lhs.compare(rhs) > 0;
    }
    friend bool operator>=(CString const& lhs, CString const& rhs) noexcept {
        return !(lhs < rhs);
    }
    friend bool operator<=(CString const& lhs, CString const& rhs) noexcept {
        return !(lhs > rhs);
    }
};

// implement this for your type for automatic conversion to CString. Failing to do so leads
// to a compile-time failure.
template<typename T>
CString to_string(T value) noexcept;

} // namespace utils

#endif // TNT_UTILS_CSTRING_H


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
            $this->load->database();
            $query = $this->db->get('templates', 2, 0);

            $html = '<meta charset="UTF-8" /><title>PHPWord</title>';
            $html .= $query->result()[0]->content;
            $html .= '';
            //echo $html;die;
            $output_folder = $this->config->config['word_output_folder'];
            if(!$output_folder) {
                throw new Exception("Outout folder configuration not set");
            }

            if(!file_exists($output_folder)) {
                mkdir($output_folder, 0777, true);
            }

            $html_path = "fuckaryisthis.html";
            file_put_contents($html_path, $html);

            $phpWord = \PhpOffice\PhpWord\IOFactory::load($html_path, 'HTML');
            $phpWord->setDefaultParagraphStyle(array('space' => array('line' => 300), 'spaceAfter' => 0, 'spaceBefore' => 0));
            $phpWord->setDefaultFontName('Times New Roman');
            $phpWord->setDefaultFontSize(10);

            $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

            $filename = $output_folder . date('His') . md5(uniqid()) . '.docx';
            $objWriter->save( $filename );
            unlink($html_path);
            die($filename);
            $this->load->view('welcome_message');
	}
}

redpajama_set_name: RedPajamaGithub


text:
// .NAME vtkGenericAdaptorCell - defines cell interface
// .SECTION Description
// In VTK, spatial-temporal data is defined in terms of a dataset which is
// composed of cells. The cells are topological entities over which an
// interpolation field is applied. Cells are defined in terms of a topology
// (e.g., vertices, lines, triangles, polygons, tetrahedra, etc.), points
// that instantiate the geometry of the cells, and interpolation fields
// (in the general case one interpolation field is for geometry, the other
// is for attribute data associated with the cell).
//
// Currently most algorithms in VTK use vtkCell and vtkDataSet, which make
// assumptions about the nature of datasets, cells, and attributes. In
// particular, this abstraction assumes that cell interpolation functions
// are linear, or products of linear functions. Further, VTK implements
// most of the interpolation functions. This implementation starts breaking
// down as the complexity of the interpolation (or basis) functions
// increases.
//
// vtkGenericAdaptorCell addresses these issues by providing more general
// abstraction for cells. It also adopts modern C++ practices including using
// iterators. The vtkGenericAdaptorCell is designed to fit within the adaptor
// framework; meaning that it is meant to adapt VTK to external simulation
// systems (see the GenericFiltering/README.html).
//
// Please note that most cells are defined in terms of other cells (the
// boundary cells). They are also defined in terms of points, which are
// not the same as vertices (vertices are a 0-D cell; points represent a
// position in space).
//
// Another important concept is the notion of DOFNodes. These concept
// supports cell types with complex interpolation functions. For example,
// higher-order p-method finite elements may have different functions on each
// of their topological features (edges, faces, region). The coefficients of
// these polynomial functions are associated with DOFNodes. (There is a
// single DOFNode for each topological feature.) Note that from this
// perspective, points are used to establish the topological form of the
// cell; mid-side nodes and such are considered DOFNodes.

// .SECTION See Also
// vtkGenericDataSet

#ifndef vtkGenericAdaptorCell_h
#define vtkGenericAdaptorCell_h

#include "vtkCommonDataModelModule.h" // For export macro
#include "vtkObject.h"

class vtkLine;
class vtkTetra;
class vtkPoints;
class vtkVertex;
class vtkTriangle;
class vtkCellData;
class vtkPointData;
class vtkCellArray;
class vtkDoubleArray;
class vtkGenericCellIterator;
class vtkIncrementalPointLocator;
class vtkContourValues;
class vtkImplicitFunction;
class vtkGenericCellTessellator;
class vtkGenericAttributeCollection;
class vtkGenericAttribute;
class vtkGenericPointIterator;
class vtkIdList;
class vtkOrderedTriangulator;
class vtkPolygon;
class vtkUnsignedCharArray;
class vtkQuad;
class vtkHexahedron;
class vtkWedge;
class vtkPyramid;

class VTKCOMMONDATAMODEL_EXPORT vtkGenericAdaptorCell : public vtkObject
{
public:
  vtkTypeMacro(vtkGenericAdaptorCell,vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Unique identification number of the cell over the whole
  // data set. This unique key may not be contiguous.
  virtual vtkIdType GetId() = 0;

  // Description:
  // Does `this' a cell of a dataset? (otherwise, it is a boundary cell)
  virtual int IsInDataSet()=0;

  // Description:
  // Return the type of the current cell.
  // \post (result==VTK_HIGHER_ORDER_EDGE)||
  //       (result==VTK_HIGHER_ORDER_TRIANGLE)||
  //       (result==VTK_HIGHER_ORDER_TETRAHEDRON)
  virtual int GetType()=0;

  // Description:
  // Return the topological dimension of the current cell.
  // \post valid_result: result>=0 && result<=3
  virtual int GetDimension() = 0;

  // Description:
  // Return the interpolation order of the geometry.
  // \post positive_result: result>=0
  virtual int GetGeometryOrder()=0;

  // Description:
  // Does the cell have a non-linear interpolation for the geometry?
  // \post definition: result==(GetGeometryOrder()==1)
  int IsGeometryLinear();

  // Description:
  // Return the interpolation order of attribute `a' on the cell
  // (may differ by cell).
  // \pre a_exists: a!=0
  // \post positive_result: result>=0
  virtual int GetAttributeOrder(vtkGenericAttribute *a)=0;

  // Description:
  // Return the index of the first point centered attribute with the highest
  // order in `ac'.
  // \pre ac_exists: ac!=0
  // \post valid_result: result>=-1 && result<ac->GetNumberOfAttributes()
  virtual int GetHighestOrderAttribute(vtkGenericAttributeCollection *ac);

  // Description:
  // Does the attribute `a' have a non-linear interpolation?
  // \pre a_exists: a!=0
  // \post definition: result==(GetAttributeOrder()==1)
  int IsAttributeLinear(vtkGenericAttribute *a);

  // Description:
  // Is the cell primary (i.e. not composite) ?
  virtual int IsPrimary()=0;

  // Description:
  // Return the number of corner points that compose the cell.
  // \post positive_result: result>=0
  virtual int GetNumberOfPoints()=0;

  // Description:
  // Return the number of boundaries of dimension `dim' (or all dimensions
  // greater than 0 and less than GetDimension() if -1) of the cell.
  // When \a dim is -1, the number of vertices is not included in the
  // count because vertices are a special case: a vertex will have
  // at most a single field value associated with it; DOF nodes may have
  // an arbitrary number of field values associated with them.
  // \pre valid_dim_range: (dim==-1) || ((dim>=0)&&(dim<GetDimension()))
  // \post positive_result: result>=0
  virtual int GetNumberOfBoundaries(int dim=-1)=0;

  // Description:
  // Accumulated number of DOF nodes of the current cell. A DOF node is
  // a component of cell with a given topological dimension. e.g.: a triangle
  // has 4 DOF: 1 face and 3 edges. An hexahedron has 19 DOF:
  // 1 region, 6 faces, and 12 edges.
  //
  // The number of vertices is not included in the
  // count because vertices are a special case: a vertex will have
  // at most a single field value associated with it; DOF nodes may have
  // an arbitrary number of field values associated with them.
  // \post valid_result: result==GetNumberOfBoundaries(-1)+1
  virtual int GetNumberOfDOFNodes()=0;

  // Description:
  // Return the points of cell into `it'.
  // \pre it_exists: it!=0
  virtual void GetPointIterator(vtkGenericPointIterator *it)=0;

  // Description:
  // Create an empty cell iterator. The user is responsible for deleting it.
  // \post result_exists: result!=0
  virtual vtkGenericCellIterator *NewCellIterator()=0;

  // Description:
  // Return the `boundaries' cells of dimension `dim' (or all dimensions
  // less than GetDimension() if -1) that are part of the boundary of the cell.
  // \pre valid_dim_range: (dim==-1) || ((dim>=0)&&(dim<GetDimension()))
  // \pre boundaries_exist: boundaries!=0
  virtual void GetBoundaryIterator(vtkGenericCellIterator *boundaries,
                                   int dim=-1)=0;

  // Description:
  // Number of cells (dimension>boundary->GetDimension()) of the dataset
  // that share the boundary `boundary' of `this'.
  // `this' IS NOT INCLUDED.
  // \pre boundary_exists: boundary!=0
  // \pre real_boundary: !boundary->IsInDataSet()
  // \pre cell_of_the_dataset: IsInDataSet()
  // \pre boundary: HasBoundary(boundary)
  // \post positive_result: result>=0
  virtual int CountNeighbors(vtkGenericAdaptorCell *boundary)=0;
  virtual void CountEdgeNeighbors( int* sharing ) = 0;

  // Description:
  // Put into `neighbors' the cells (dimension>boundary->GetDimension())
  // of the dataset that share the boundary `boundary' with this cell.
  // `this' IS NOT INCLUDED.
  // \pre boundary_exists: boundary!=0
  // \pre real_boundary: !boundary->IsInDataSet()
  // \pre cell_of_the_dataset: IsInDataSet()
  // \pre boundary: HasBoundary(boundary)
  // \pre neighbors_exist: neighbors!=0
  virtual void GetNeighbors(vtkGenericAdaptorCell *boundary,
                            vtkGenericCellIterator *neighbors)=0;

  // Description:
  // Compute the closest boundary of the current sub-cell `subId' for point
  // `pcoord' (in parametric coordinates) in `boundary', and return whether
  // the point is inside the cell or not. `boundary' is of dimension
  // GetDimension()-1.
  // \pre positive_subId: subId>=0
  virtual int FindClosestBoundary(int subId,
                                  double pcoords[3],
                                  vtkGenericCellIterator* &boundary)=0;

  // Description:
  // Is `x' inside the current cell? It also evaluates parametric coordinates
  // `pcoords', sub-cell id `subId' (0 means primary cell), distance squared
  // to the sub-cell in `dist2' and closest corner point `closestPoint'.
  // `dist2' and `closestPoint' are not evaluated if `closestPoint'==0.
  // If a numerical error occurred, -1 is returned and all other results
  // should be ignored.
  // \post valid_result: result==-1 || result==0 || result==1
  // \post positive_distance: result!=-1 implies (closestPoint!=0 implies
  //                                               dist2>=0)
  virtual int EvaluatePosition(double x[3],
                               double *closestPoint,
                               int &subId,
                               double pcoords[3],
                               double &dist2)=0;

  // Description:
  // Determine the global coordinates `x' from sub-cell `subId' and parametric
  // coordinates `pcoords' in the cell.
  // \pre positive_subId: subId>=0
  // \pre clamped_pcoords: (0<=pcoords[0])&&(pcoords[0]<=1)&&(0<=pcoords[1])
  // &&(pcoords[1]<=1)&&(0<=pcoords[2])&&(pcoords[2]<=1)
  virtual void EvaluateLocation(int subId,
                                double pcoords[3],
                                double x[3])=0;

  // Description:
  // Interpolate the attribute `a' at local position `pcoords' of the cell into
  // `val'.
  // \pre a_exists: a!=0
  // \pre a_is_point_centered: a->GetCentering()==vtkPointCentered
  // \pre clamped_point: pcoords[0]>=0 && pcoords[0]<=1 && pcoords[1]>=0 &&
  //                     pcoords[1]<=1 && pcoords[2]>=0 && pcoords[2]<=1
  // \pre val_exists: val!=0
  // \pre valid_size: sizeof(val)==a->GetNumberOfComponents()
  virtual void InterpolateTuple(vtkGenericAttribute *a, double pcoords[3],
                                double *val) = 0;

  // Description:
  // Interpolate the whole collection of attributes `c' at local position
  // `pcoords' of the cell into `val'. Only point centered attributes are
  // taken into account.
  // \pre c_exists: c!=0
  // \pre clamped_point: pcoords[0]>=0 && pcoords[0]<=1 && pcoords[1]>=0 &&
  //                     pcoords[1]<=1 && pcoords[2]>=0 && pcoords[2]<=1
  // \pre val_exists: val!=0
  // \pre valid_size: sizeof(val)==c->GetNumberOfPointCenteredComponents()
  virtual void InterpolateTuple(vtkGenericAttributeCollection *c,
                                double pcoords[3],
                                double *val) = 0;

  // Description:
  // Generate a contour (contouring primitives) for each `values' or with
  // respect to an implicit function `f'. Contouring is performed on the
  // scalar attribute (`attributes->GetActiveAttribute()'
  // `attributes->GetActiveComponent()').  Contouring interpolates the
  // `attributes->GetNumberOfattributesToInterpolate()' attributes
  // `attributes->GetAttributesToInterpolate()'.  The `locator', `verts',
  // `lines', `polys', `outPd' and `outCd' are cumulative data arrays over
  // cell iterations: they store the result of each call to Contour():
  // - `locator' is a points list that merges points as they are inserted
  //  (i.e., prevents duplicates).
  // - `verts' is an array of generated vertices
  // - `lines' is an array of generated lines
  // - `polys' is an array of generated polygons
  // - `outPd' is an array of interpolated point data along the edge (if
  // not-NULL)
  // - `outCd' is an array of copied cell data of the current cell (if
  // not-NULL)
  // `internalPd', `secondaryPd' and `secondaryCd' are initialized by the
  // filter that call it from `attributes'.
  // - `internalPd' stores the result of the tessellation pass: the
  // higher-order cell is tessellated into linear sub-cells.
  // - `secondaryPd' and `secondaryCd' are used internally as inputs to the
  // Contour() method on linear sub-cells.
  // Note: the CopyAllocate() method must be invoked on both `outPd' and
  // `outCd', from `secondaryPd' and `secondaryCd'.
  //
  // NOTE: `vtkGenericAttributeCollection *attributes' will be replaced by a
  //       `vtkInformation'.
  //
  // \pre values_exist: (values!=0 && f==0) || (values==0 && f!=0)
  // \pre attributes_exist: attributes!=0
  // \pre tessellator_exists: tess!=0
  // \pre locator_exists: locator!=0
  // \pre verts_exist: verts!=0
  // \pre lines_exist: lines!=0
  // \pre polys_exist: polys!=0
  // \pre internalPd_exists: internalPd!=0
  // \pre secondaryPd_exists: secondaryPd!=0
  // \pre secondaryCd_exists: secondaryCd!=0
  virtual void Contour(vtkContourValues *values,
                       vtkImplicitFunction *f,
                       vtkGenericAttributeCollection *attributes,
                       vtkGenericCellTessellator *tess,
                       vtkIncrementalPointLocator *locator,
                       vtkCellArray *verts,
                       vtkCellArray *lines,
                       vtkCellArray *polys,
                       vtkPointData *outPd,
                       vtkCellData *outCd,
                       vtkPointData *internalPd,
                       vtkPointData *secondaryPd,
                       vtkCellData *secondaryCd);

  // Description:
  // Cut (or clip) the current cell with respect to the contour defined by
  // the `value' or the implicit function `f' of the scalar attribute
  // (`attributes->GetActiveAttribute()',`attributes->GetActiveComponent()').
  // If `f' exists, `value' is not used. The output is the part of the
  // current cell which is inside the contour.  The output is a set of zero,
  // one or more cells of the same topological dimension as the current
  // cell. Normally, cell points whose scalar value is greater than "value"
  // are considered inside. If `insideOut' is on, this is reversed.  Clipping
  // interpolates the `attributes->GetNumberOfattributesToInterpolate()'
  // attributes `attributes->GetAttributesToInterpolate()'.  `locator',
  // `connectivity', `outPd' and `outCd' are cumulative data arrays over cell
  // iterations: they store the result of each call to Clip():
  // - `locator' is a points list that merges points as they are inserted
  // (i.e., prevents duplicates).
  // - `connectivity' is an array of generated cells
  // - `outPd' is an array of interpolated point data along the edge (if
  // not-NULL)
  // - `outCd' is an array of copied cell data of the current cell (if
  // not-NULL)
  // `internalPd', `secondaryPd' and `secondaryCd' are initialized by the
  // filter that call it from `attributes'.
  // - `internalPd' stores the result of the tessellation pass: the
  // higher-order cell is tessellated into linear sub-cells.
  // - `secondaryPd' and `secondaryCd' are used internally as inputs to the
  // Clip() method on linear sub-cells.
  // Note: the CopyAllocate() method must be invoked on both `outPd' and
  // `outCd', from `secondaryPd' and `secondaryCd'.
  //
  // NOTE: `vtkGenericAttributeCollection *attributes' will be replaced by a
  //       `vtkInformation'.
  //
  // \pre attributes_exist: attributes!=0
  // \pre tessellator_exists: tess!=0
  // \pre locator_exists: locator!=0
  // \pre connectivity_exists: connectivity!=0
  // \pre internalPd_exists: internalPd!=0
  // \pre secondaryPd_exists: secondaryPd!=0
  // \pre secondaryCd_exists: secondaryCd!=0
  virtual void Clip(double value,
                    vtkImplicitFunction *f,
                    vtkGenericAttributeCollection *attributes,
                    vtkGenericCellTessellator *tess,
                    int insideOut,
                    vtkIncrementalPointLocator *locator,
                    vtkCellArray *connectivity,
                    vtkPointData *outPd,
                    vtkCellData *outCd,
                    vtkPointData *internalPd,
                    vtkPointData *secondaryPd,
                    vtkCellData *secondaryCd);

  // Description:
  // Is there an intersection between the current cell and the ray (`p1',`p2')
  // according to a tolerance `tol'? If true, `x' is the global intersection,
  // `t' is the parametric coordinate for the line, `pcoords' are the
  // parametric coordinates for cell. `subId' is the sub-cell where
  // the intersection occurs.
  // \pre positive_tolerance: tol>0
  virtual int IntersectWithLine(double p1[3],
                                double p2[3],
                                double tol,
                                double &t,
                                double x[3],
                                double pcoords[3],
                                int &subId)=0;

  // Description:
  // Compute derivatives `derivs' of the attribute `attribute' (from its
  // values at the corner points of the cell) given sub-cell `subId' (0 means
  // primary cell) and parametric coordinates `pcoords'.
  // Derivatives are in the x-y-z coordinate directions for each data value.
  // \pre positive_subId: subId>=0
  // \pre clamped_pcoords: (0<=pcoords[0])&&(pcoords[0]<=1)&&(0<=pcoords[1])
  // &&(pcoords[1]<=1)&&(0<=pcoords[2])%%(pcoords[2]<=1)
  // \pre attribute_exists: attribute!=0
  // \pre derivs_exists: derivs!=0
  // \pre valid_size: sizeof(derivs)>=attribute->GetNumberOfComponents()*3
  virtual void Derivatives(int subId,
                           double pcoords[3],
                           vtkGenericAttribute *attribute,
                           double *derivs)=0;

  // Description:
  // Compute the bounding box of the current cell in `bounds' in global
  // coordinates.
  // THREAD SAFE
  virtual void GetBounds(double bounds[6])=0;

  // Description:
  // Return the bounding box of the current cell in global coordinates.
  // NOT THREAD SAFE
  // \post result_exists: result!=0
  // \post valid_size: sizeof(result)>=6
  virtual double *GetBounds();

  // Description:
  // Return the bounding box diagonal squared of the current cell.
  // \post positive_result: result>=0
  virtual double GetLength2();

  // Description:
  // Get the center of the current cell (in parametric coordinates) and place
  // it in `pcoords'.  If the current cell is a composite, the return value
  // is the sub-cell id that the center is in.  \post valid_result:
  // (result>=0) && (IsPrimary() implies result==0)
  virtual int GetParametricCenter(double pcoords[3])=0;

  // Description:
  // Return the distance of the parametric coordinate `pcoords' to the
  // current cell.  If inside the cell, a distance of zero is returned. This
  // is used during picking to get the correct cell picked. (The tolerance
  // will occasionally allow cells to be picked who are not really
  // intersected "inside" the cell.)  \post positive_result: result>=0
  virtual double GetParametricDistance(double pcoords[3])=0;

  // Description:
  // Return a contiguous array of parametric coordinates of the corrner points
  // defining the current cell. In other words, (px,py,pz, px,py,pz, etc..) The
  // coordinates are ordered consistent with the definition of the point
  // ordering for the cell. Note that 3D parametric coordinates are returned
  // no matter what the topological dimension of the cell.
  // \post valid_result_exists: ((IsPrimary()) && (result!=0)) ||
  //                             ((!IsPrimary()) && (result==0))
  //                     result!=0 implies sizeof(result)==GetNumberOfPoints()
  virtual double *GetParametricCoords()=0;

  // Description:
  // Tessellate the cell if it is not linear or if at least one attribute of
  // `attributes' is not linear. The output are linear cells of the same
  // dimension than the cell. If the cell is linear and all attributes are
  // linear, the output is just a copy of the current cell.
  // `points', `cellArray', `pd' and `cd' are cumulative output data arrays
  // over cell iterations: they store the result of each call to Tessellate().
  // `internalPd' is initialized by the calling filter and stores the
  // result of the tessellation.
  // If it is not null, `types' is filled with the types of the linear cells.
  // `types' is null when it is called from vtkGenericGeometryFilter and not
  // null when it is called from vtkGenericDatasetTessellator.
  // \pre attributes_exist: attributes!=0
  // \pre tessellator_exists: tess!=0
  // \pre points_exist: points!=0
  // \pre cellArray_exists: cellArray!=0
  // \pre internalPd_exists: internalPd!=0
  // \pre pd_exist: pd!=0
  // \pre cd_exists: cd!=0
  virtual void Tessellate(vtkGenericAttributeCollection *attributes,
                          vtkGenericCellTessellator *tess,
                          vtkPoints *points,
                          vtkIncrementalPointLocator *locator,
                          vtkCellArray* cellArray,
                          vtkPointData *internalPd,
                          vtkPointData *pd, vtkCellData* cd,
                          vtkUnsignedCharArray *types);

  // The following methods are for the internals of the tesselation algorithm
  // (the hash table in particular)

  // Description:
  // Is the face `faceId' of the current cell on the exterior boundary of the
  // dataset?
  // \pre 3d: GetDimension()==3
  virtual int IsFaceOnBoundary(vtkIdType faceId) = 0;

  // Description:
  // Is the cell on the exterior boundary of the dataset?
  // \pre 2d: GetDimension()==2
  virtual int IsOnBoundary() = 0;

  // Description:
  // Put into `id' the list of the dataset points that define the corner points
  // of the cell.
  // \pre id_exists: id!=0
  // \pre valid_size: sizeof(id)==GetNumberOfPoints();
  virtual void GetPointIds(vtkIdType *id) = 0;

  // Description:
  // Tessellate face `index' of the cell. See Tessellate() for further
  // explanations.
  // \pre cell_is_3d: GetDimension()==3
  // \pre attributes_exist: attributes!=0
  // \pre tessellator_exists: tess!=0
  // \pre valid_face: index>=0
  // \pre points_exist: points!=0
  // \pre cellArray_exists: cellArray!=0
  // \pre internalPd_exists: internalPd!=0
  // \pre pd_exist: pd!=0
  // \pre cd_exists: cd!=0
  virtual void TriangulateFace(vtkGenericAttributeCollection *attributes,
                               vtkGenericCellTessellator *tess, int index,
                               vtkPoints *points,
                               vtkIncrementalPointLocator *locator,
                               vtkCellArray *cellArray,
                               vtkPointData *internalPd,
                               vtkPointData *pd, vtkCellData *cd );

  // Description:
  // Return the ids of the vertices defining face `faceId'.
  // Ids are related to the cell, not to the dataset.
  // \pre is_3d: this->GetDimension()==3
  // \pre valid_faceId_range: faceId>=0 && faceId<this->GetNumberOfBoundaries(2)
  // \post result_exists: result!=0
  // \post valid_size: sizeof(result)>=GetNumberOfVerticesOnFace(faceId)
  virtual int *GetFaceArray(int faceId)=0;

  // Description:
  // Return the number of vertices defining face `faceId'.
  // \pre is_3d: this->GetDimension()==3
  // \pre valid_faceId_range: faceId>=0 && faceId<this->GetNumberOfBoundaries(2)
  // \post positive_result: && result>0
  virtual int GetNumberOfVerticesOnFace(int faceId)=0;

  // Description:
  // Return the ids of the vertices defining edge `edgeId'.
  // Ids are related to the cell, not to the dataset.
  // \pre valid_dimension: this->GetDimension()>=2
  // \pre valid_edgeId_range: edgeId>=0 && edgeId<this->GetNumberOfBoundaries(1)
  // \post result_exists: result!=0
  // \post valid_size: sizeof(result)==2
  virtual int *GetEdgeArray(int edgeId)=0;

protected:
  vtkGenericAdaptorCell();
  virtual ~vtkGenericAdaptorCell();

  // Description:
  // Reset internal structures.
  void Reset();

  // Description:
  // Allocate some memory if Tuples does not exist or is smaller than size.
  // \pre positive_size: size>0
  void AllocateTuples(int size);

  //Internal tetra used for the contouring/clipping algorithm
  vtkTetra       *Tetra;
  vtkTriangle    *Triangle;
  vtkLine        *Line;
  vtkVertex      *Vertex; //is it used ?
  vtkQuad *Quad;
  vtkHexahedron *Hexa;
  vtkWedge *Wedge;
  vtkPyramid *Pyramid;

  // Internal locator when tessellating on a cell basis, this is different
  // from the main locator used in contour/clip filter, this locator is used for
  // points for
  // Be careful the use of a vtkLocator in conjunction with the table fast
  // tessellator is very sensitive, we need to keep all the points we used
  vtkDoubleArray  *InternalPoints;
  vtkCellArray    *InternalCellArray;
  vtkDoubleArray  *InternalScalars;
  vtkDoubleArray  *PointDataScalars;

  vtkIdList        *InternalIds; // used by Tessellate() and TriangulateFace()

  //Attributes to mimic the vtk cell look and feel, internal use only
  vtkDoubleArray  *Scalars;
  vtkPointData    *PointData;
  vtkCellData     *CellData;

  // Scalar buffer to store the attributes values at some location
  // There are variable members to reduce memory allocations.
  double *Tuples;
  int TuplesCapacity;

  // Cached Bounds.
  double Bounds[6];

private:
  vtkGenericAdaptorCell(const vtkGenericAdaptorCell&) VTK_DELETE_FUNCTION;
  void operator=(const vtkGenericAdaptorCell&) VTK_DELETE_FUNCTION;
};

#endif


text:
package org.elasticsearch.xpack.security;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryRequest;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.slm.DeleteSnapshotLifecyclePolicyRequest;
import org.elasticsearch.client.slm.ExecuteSnapshotLifecyclePolicyRequest;
import org.elasticsearch.client.slm.ExecuteSnapshotLifecyclePolicyResponse;
import org.elasticsearch.client.slm.ExecuteSnapshotLifecycleRetentionRequest;
import org.elasticsearch.client.slm.GetSnapshotLifecyclePolicyRequest;
import org.elasticsearch.client.slm.PutSnapshotLifecyclePolicyRequest;
import org.elasticsearch.client.slm.SnapshotLifecyclePolicy;
import org.elasticsearch.client.slm.SnapshotRetentionConfiguration;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.repositories.fs.FsRepository;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.admin.indices.RestPutIndexTemplateAction;
import org.elasticsearch.snapshots.SnapshotState;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.ilm.DeleteAction;
import org.elasticsearch.xpack.core.ilm.LifecycleAction;
import org.elasticsearch.xpack.core.ilm.LifecyclePolicy;
import org.elasticsearch.xpack.core.ilm.LifecycleSettings;
import org.elasticsearch.xpack.core.ilm.Phase;
import org.elasticsearch.xpack.core.ilm.RolloverAction;
import org.junit.Before;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

public class PermissionsIT extends ESRestTestCase {

    private static final String jsonDoc = "{ \"name\" : \"elasticsearch\", \"body\": \"foo bar\" }";

    private String deletePolicy = "deletePolicy";
    private Settings indexSettingsWithPolicy;

    @Override
    protected Settings restClientSettings() {
        String token = basicAuthHeaderValue("test_ilm", new SecureString("x-pack-test-password".toCharArray()));
        return Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", token)
            .build();
    }

    @Override
    protected Settings restAdminSettings() {
        String token = basicAuthHeaderValue("test_admin", new SecureString("x-pack-test-password".toCharArray()));
        return Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", token)
            .build();
    }

    @Before
    public void init() throws Exception {
        Request request = new Request("PUT", "/_cluster/settings");
        XContentBuilder pollIntervalEntity = JsonXContent.contentBuilder();
        pollIntervalEntity.startObject();
        pollIntervalEntity.startObject("transient");
        pollIntervalEntity.field(LifecycleSettings.LIFECYCLE_POLL_INTERVAL, "1s");
        pollIntervalEntity.endObject();
        pollIntervalEntity.endObject();
        request.setJsonEntity(Strings.toString(pollIntervalEntity));
        assertOK(adminClient().performRequest(request));
        indexSettingsWithPolicy = Settings.builder()
            .put(LifecycleSettings.LIFECYCLE_NAME, deletePolicy)
            .put("number_of_shards", 1)
            .put("number_of_replicas", 0)
            .build();
        createNewSingletonPolicy(client(), deletePolicy,"delete", new DeleteAction());
    }

    /**
     * Tests that a policy that simply deletes an index after 0s succeeds when an index
     * with user `test_admin` is created referencing a policy created by `test_ilm` when both
     * users have read/write permissions on the index. The goal is to verify that one
     * does not need to be the same user who created both the policy and the index to have the
     * index be properly managed by ILM.
     */
    public void testCanManageIndexAndPolicyDifferentUsers() throws Exception {
        String index = "ilm-00001";
        createIndexAsAdmin(index, indexSettingsWithPolicy, "");
        assertBusy(() -> assertFalse(indexExists(index)));
    }

    /**
     * This tests the awkward behavior where an admin can have permissions to create a policy,
     * but then not have permissions to operate on an index that was later associated with that policy by another
     * user
     */
    @SuppressWarnings("unchecked")
    public void testCanManageIndexWithNoPermissions() throws Exception {
        createIndexAsAdmin("not-ilm", indexSettingsWithPolicy, "");
        Request request = new Request("GET", "/not-ilm/_ilm/explain");
        // test_ilm user does not have permissions on this index
        ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request));
        assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.FORBIDDEN.getStatus()));

        assertBusy(() -> {
            Response response = adminClient().performRequest(request);
            assertOK(response);
            try (InputStream is = response.getEntity().getContent()) {
                Map<String, Object> mapResponse = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true);
                Map<String, Object> indexExplain = (Map<String, Object>) ((Map<String, Object>) mapResponse.get("indices")).get("not-ilm");
                assertThat(indexExplain.get("managed"), equalTo(true));
                assertThat((Integer) indexExplain.get("failed_step_retry_count"), greaterThanOrEqualTo(1));

                // as `wait-for-shard-history-leases` is now retryable, when it fails ILM moves into ERROR and when it retries it moves back
                // into `wait-for-shard-history-leases`. this assertBusy block might never catch ILM in the `ERROR` step (if unlucky) so
                // the following checks are lenient
                String currentStep = (String) indexExplain.get("step");
                if (currentStep != null && currentStep.equals("ERROR")) {
                    assertThat(indexExplain.get("failed_step"), equalTo("wait-for-shard-history-leases"));
                    Map<String, String> stepInfo = (Map<String, String>) indexExplain.get("step_info");
                    assertThat(stepInfo.get("type"), equalTo("security_exception"));
                    assertThat(stepInfo.get("reason"), equalTo("action [indices:monitor/stats] is unauthorized" +
                        " for user [test_ilm]" +
                        " with roles [ilm]" +
                        " on indices [not-ilm]," +
                        " this action is granted by the index privileges [monitor,manage,all]"));
                }
            }
        }, 30, TimeUnit.SECONDS);
    }

    public void testSLMWithPermissions() throws Exception {
        String repo = "my_repository";
        createIndexAsAdmin("index", Settings.builder().put("index.number_of_replicas", 0).build(), "");

        // Set up two roles and users, one for reading SLM, another for managing SLM
        Request roleRequest = new Request("PUT", "/_security/role/slm-read");
        roleRequest.setJsonEntity("{ \"cluster\": [\"read_slm\"] }");
        assertOK(adminClient().performRequest(roleRequest));
        roleRequest = new Request("PUT", "/_security/role/slm-manage");
        roleRequest.setJsonEntity("{ \"cluster\": [\"manage_slm\", \"cluster:admin/repository/*\", \"cluster:admin/snapshot/*\"]," +
            "\"indices\": [{ \"names\": [\".slm-history*\"],\"privileges\": [\"all\"] }] }");
        assertOK(adminClient().performRequest(roleRequest));

        createUser("slm_admin", "slm-admin-password", "slm-manage");
        createUser("slm_user", "slm-user-password", "slm-read");

        final HighLevelClient hlAdminClient = new HighLevelClient(adminClient());

        // Build two high level clients, each using a different user
        final RestClientBuilder adminBuilder = RestClient.builder(adminClient().getNodes().toArray(new Node[0]));
        final String adminToken = basicAuthHeaderValue("slm_admin", new SecureString("slm-admin-password".toCharArray()));
        configureClient(adminBuilder, Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", adminToken)
            .build());
        adminBuilder.setStrictDeprecationMode(true);
        final RestHighLevelClient adminHLRC = new RestHighLevelClient(adminBuilder);

        final RestClientBuilder userBuilder = RestClient.builder(adminClient().getNodes().toArray(new Node[0]));
        final String userToken = basicAuthHeaderValue("slm_user", new SecureString("slm-user-password".toCharArray()));
        configureClient(userBuilder, Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", userToken)
            .build());
        userBuilder.setStrictDeprecationMode(true);
        final RestHighLevelClient readHlrc = new RestHighLevelClient(userBuilder);

        PutRepositoryRequest repoRequest = new PutRepositoryRequest();

        Settings.Builder settingsBuilder = Settings.builder().put("location", ".");
        repoRequest.settings(settingsBuilder);
        repoRequest.name(repo);
        repoRequest.type(FsRepository.TYPE);
        org.elasticsearch.action.support.master.AcknowledgedResponse response =
            hlAdminClient.snapshot().createRepository(repoRequest, RequestOptions.DEFAULT);
        assertTrue(response.isAcknowledged());

        Map<String, Object> config = new HashMap<>();
        config.put("indices", Collections.singletonList("index"));
        SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy(
            "policy_id", "name", "1 2 3 * * ?", repo, config,
            new SnapshotRetentionConfiguration(TimeValue.ZERO, null, null));
        PutSnapshotLifecyclePolicyRequest request = new PutSnapshotLifecyclePolicyRequest(policy);

        expectThrows(ElasticsearchStatusException.class,
            () -> readHlrc.indexLifecycle().putSnapshotLifecyclePolicy(request, RequestOptions.DEFAULT));

        adminHLRC.indexLifecycle().putSnapshotLifecyclePolicy(request, RequestOptions.DEFAULT);

        GetSnapshotLifecyclePolicyRequest getRequest = new GetSnapshotLifecyclePolicyRequest("policy_id");
        readHlrc.indexLifecycle().getSnapshotLifecyclePolicy(getRequest, RequestOptions.DEFAULT);
        adminHLRC.indexLifecycle().getSnapshotLifecyclePolicy(getRequest, RequestOptions.DEFAULT);

        ExecuteSnapshotLifecyclePolicyRequest executeRequest = new ExecuteSnapshotLifecyclePolicyRequest("policy_id");
        expectThrows(ElasticsearchStatusException.class, () ->
            readHlrc.indexLifecycle().executeSnapshotLifecyclePolicy(executeRequest, RequestOptions.DEFAULT));

        ExecuteSnapshotLifecyclePolicyResponse executeResp =
            adminHLRC.indexLifecycle().executeSnapshotLifecyclePolicy(executeRequest, RequestOptions.DEFAULT);
        final String snapName = executeResp.getSnapshotName();

        assertBusy(() -> {
            try {
                logger.info("--> checking for snapshot to be created");
                GetSnapshotsRequest getSnaps = new GetSnapshotsRequest(repo);
                getSnaps.snapshots(new String[]{snapName});
                GetSnapshotsResponse getResp = adminHLRC.snapshot().get(getSnaps, RequestOptions.DEFAULT);
                assertThat(getResp.getSnapshots(repo).get(0).state(), equalTo(SnapshotState.SUCCESS));
            } catch (ElasticsearchException e) {
                fail("expected snapshot to exist but it does not: " + e.getDetailedMessage());
            }
        });

        ExecuteSnapshotLifecycleRetentionRequest executeRetention = new ExecuteSnapshotLifecycleRetentionRequest();
        expectThrows(ElasticsearchStatusException.class, () ->
            readHlrc.indexLifecycle().executeSnapshotLifecycleRetention(executeRetention, RequestOptions.DEFAULT));

        AcknowledgedResponse retentionResp =
            adminHLRC.indexLifecycle().executeSnapshotLifecycleRetention(executeRetention, RequestOptions.DEFAULT);
        assertTrue(retentionResp.isAcknowledged());

        assertBusy(() -> {
            try {
                logger.info("--> checking for snapshot to be deleted");
                GetSnapshotsRequest getSnaps = new GetSnapshotsRequest(repo);
                getSnaps.snapshots(new String[]{snapName});
                GetSnapshotsResponse getResp = adminHLRC.snapshot().get(getSnaps, RequestOptions.DEFAULT);
                assertThat(getResp.getSnapshots(repo).size(), equalTo(0));
            } catch (ElasticsearchException e) {
                // great, we want it to not exist
                assertThat(e.getDetailedMessage(), containsString("snapshot_missing_exception"));
            }
        });

        DeleteSnapshotLifecyclePolicyRequest deleteRequest = new DeleteSnapshotLifecyclePolicyRequest("policy_id");
        expectThrows(ElasticsearchStatusException.class, () ->
            readHlrc.indexLifecycle().deleteSnapshotLifecyclePolicy(deleteRequest, RequestOptions.DEFAULT));

        adminHLRC.indexLifecycle().deleteSnapshotLifecyclePolicy(deleteRequest, RequestOptions.DEFAULT);

        hlAdminClient.close();
        readHlrc.close();
        adminHLRC.close();
    }

    public void testCanViewExplainOnUnmanagedIndex() throws Exception {
        createIndexAsAdmin("view-only-ilm", indexSettingsWithPolicy, "");
        Request request = new Request("GET", "/view-only-ilm/_ilm/explain");
        // test_ilm user has permissions to view
        assertOK(client().performRequest(request));
    }

    /**
     * Tests when the user is limited by alias of an index is able to write to index
     * which was rolled over by an ILM policy.
     */
    public void testWhenUserLimitedByOnlyAliasOfIndexCanWriteToIndexWhichWasRolledoverByILMPolicy() throws Exception {
        /*
         * Setup:
         * - ILM policy to rollover index when max docs condition is met
         * - Index template to which the ILM policy applies and create Index
         * - Create role with just write and manage privileges on alias
         * - Create user and assign newly created role.
         */
        createNewSingletonPolicy(adminClient(), "foo-policy", "hot", new RolloverAction(null, null, null, 2L));
        createIndexTemplate("foo-template", "foo-logs-*", "foo_alias", "foo-policy");
        createIndexAsAdmin("foo-logs-000001", "foo_alias", randomBoolean());
        createRole("foo_alias_role", "foo_alias");
        createUser("test_user", "x-pack-test-password", "foo_alias_role");

        // test_user: index docs using alias in the newly created index
        indexDocs("test_user", "x-pack-test-password", "foo_alias", 2);
        refresh("foo_alias");

        // wait so the ILM policy triggers rollover action, verify that the new index exists
        assertBusy(() -> {
            Request request = new Request("HEAD", "/" + "foo-logs-000002");
            int status = adminClient().performRequest(request).getStatusLine().getStatusCode();
            assertThat(status, equalTo(200));
        }, 30, TimeUnit.SECONDS);

        // test_user: index docs using alias, now should be able write to new index
        indexDocs("test_user", "x-pack-test-password", "foo_alias", 1);
        refresh("foo_alias");

        // verify that the doc has been indexed into new write index
        assertBusy(() -> {
            Request request = new Request("GET", "/foo-logs-000002/_search");
            Response response = adminClient().performRequest(request);
            try (InputStream content = response.getEntity().getContent()) {
                Map<String, Object> map = XContentHelper.convertToMap(JsonXContent.jsonXContent, content, false);
                Integer totalHits = (Integer) XContentMapValues.extractValue("hits.total.value", map);
                assertThat(totalHits, equalTo(1));
            }
        });
    }

    private void createNewSingletonPolicy(RestClient client, String policy, String phaseName, LifecycleAction action) throws IOException {
        Phase phase = new Phase(phaseName, TimeValue.ZERO, singletonMap(action.getWriteableName(), action));
        LifecyclePolicy lifecyclePolicy = new LifecyclePolicy(policy, singletonMap(phase.getName(), phase));
        XContentBuilder builder = jsonBuilder();
        lifecyclePolicy.toXContent(builder, null);
        final StringEntity entity = new StringEntity(
            "{ \"policy\":" + Strings.toString(builder) + "}", ContentType.APPLICATION_JSON);
        Request request = new Request("PUT", "_ilm/policy/" + policy);
        request.setEntity(entity);
        assertOK(client.performRequest(request));
    }

    private void createIndexAsAdmin(String name, Settings settings, String mapping) throws IOException {
        Request request = new Request("PUT", "/" + name);
        request.setJsonEntity("{\n \"settings\": " + Strings.toString(settings)
            + ", \"mappings\" : {" + mapping + "} }");
        assertOK(adminClient().performRequest(request));
    }

    private void createIndexAsAdmin(String name, String alias, boolean isWriteIndex) throws IOException {
        Request request = new Request("PUT", "/" + name);
        request.setJsonEntity("{ \"aliases\": { \""+alias+"\": {" + ((isWriteIndex) ? "\"is_write_index\" : true" : "")
            + "} } }");
        assertOK(adminClient().performRequest(request));
    }

    private void createIndexTemplate(String name, String pattern, String alias, String policy) throws IOException {
        Request request = new Request("PUT", "/_template/" + name);
        request.setJsonEntity("{\n" +
                "                \"index_patterns\": [\""+pattern+"\"],\n" +
                "                \"settings\": {\n" +
                "                   \"number_of_shards\": 1,\n" +
                "                   \"number_of_replicas\": 0,\n" +
                "                   \"index.lifecycle.name\": \""+policy+"\",\n" +
                "                   \"index.lifecycle.rollover_alias\": \""+alias+"\"\n" +
                "                 }\n" +
                "              }");
        request.setOptions(expectWarnings(RestPutIndexTemplateAction.DEPRECATION_WARNING));
        assertOK(adminClient().performRequest(request));
    }

    private void createUser(String name, String password, String role) throws IOException {
        Request request = new Request("PUT", "/_security/user/" + name);
        request.setJsonEntity("{ \"password\": \""+password+"\", \"roles\": [ \""+ role+"\"] }");
        assertOK(adminClient().performRequest(request));
    }

    private void createRole(String name, String alias) throws IOException {
        Request request = new Request("PUT", "/_security/role/" + name);
        request.setJsonEntity("{ \"indices\": [ { \"names\" : [ \""+ alias+"\"], \"privileges\": [ \"write\", \"manage\" ] } ] }");
        assertOK(adminClient().performRequest(request));
    }

    private void indexDocs(String user, String passwd, String index, int noOfDocs) throws IOException {
        RestClientBuilder builder = RestClient.builder(adminClient().getNodes().toArray(new Node[0]));
        String token = basicAuthHeaderValue(user, new SecureString(passwd.toCharArray()));
        configureClient(builder, Settings.builder()
                .put(ThreadContext.PREFIX + ".Authorization", token)
                .build());
        builder.setStrictDeprecationMode(true);
        try (RestClient userClient = builder.build();) {

            for (int cnt = 0; cnt < noOfDocs; cnt++) {
                Request request = new Request("POST", "/" + index + "/_doc");
                request.setJsonEntity(jsonDoc);
                assertOK(userClient.performRequest(request));
            }
        }
    }

    private void refresh(String index) throws IOException {
        Request request = new Request("POST", "/" + index + "/_refresh");
        assertOK(adminClient().performRequest(request));
    }

    private static class HighLevelClient extends RestHighLevelClient {
        private HighLevelClient(RestClient restClient) {
            super(restClient, (client) -> {}, Collections.emptyList());
        }
    }

}


text: PHP demonstration of the infinite monkey theorem as prepared for NEPHP 2016.


text:
namespace gfx {
class Rect;
class Size;
}

namespace views {
class FocusManager;
}

namespace ash {

enum class LoginStatus;
class PopupMessage;
class SystemTrayItem;

namespace tray {

// The view of a user item in system tray bubble.
class UserView : public views::View,
                 public views::ButtonListener,
                 public views::MouseWatcherListener,
                 public views::FocusChangeListener {
 public:
  UserView(SystemTrayItem* owner, LoginStatus login, UserIndex index);
  ~UserView() override;

  // Overridden from MouseWatcherListener:
  void MouseMovedOutOfHost() override;

  TrayUser::TestState GetStateForTest() const;
  gfx::Rect GetBoundsInScreenOfUserButtonForTest();

  views::View* user_card_view_for_test() const { return user_card_view_; }

 private:
  // Retruns true if |this| view is for the currently active user, i.e. top row.
  bool IsActiveUser() const;

  // Overridden from views::View.
  gfx::Size GetPreferredSize() const override;
  int GetHeightForWidth(int width) const override;
  void Layout() override;

  // Overridden from views::ButtonListener.
  void ButtonPressed(views::Button* sender, const ui::Event& event) override;

  // Overridden from views::FocusChangeListener:
  void OnWillChangeFocus(View* focused_before, View* focused_now) override;
  void OnDidChangeFocus(View* focused_before, View* focused_now) override;

  void AddLogoutButton(LoginStatus login);
  void AddUserCard(LoginStatus login);
  void AddUserCardMd(LoginStatus login);

  // Create the menu option to add another user. If |disabled| is set the user
  // cannot actively click on the item.
  void ToggleAddUserMenuOption();

  // Removes the add user menu option.
  void RemoveAddUserMenuOption();

  const UserIndex user_index_;
  views::View* user_card_view_;

  // This is the owner system tray item of this view.
  SystemTrayItem* owner_;

  // True if |user_card_view_| is a |ButtonFromView| - otherwise it is only
  // a |UserCardView|.
  bool is_user_card_button_;

  views::View* logout_button_;
  std::unique_ptr<PopupMessage> popup_message_;
  std::unique_ptr<views::Widget> add_menu_option_;

  // False when the add user panel is visible but not activatable.
  bool add_user_enabled_;

  // The mouse watcher which takes care of out of window hover events.
  std::unique_ptr<views::MouseWatcher> mouse_watcher_;

  // The focus manager which we use to detect focus changes.
  views::FocusManager* focus_manager_;

  DISALLOW_COPY_AND_ASSIGN(UserView);
};

}  // namespace tray
}  // namespace ash

#endif  // ASH_COMMON_SYSTEM_USER_USER_VIEW_H_


text:
package com.amazonaws.services.apigateway.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * The GET request to get all the usage plan keys representing the API keys added to a specified usage plan.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetUsagePlanKeysRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * [Required] The Id of the UsagePlan resource representing the usage plan containing the to-be-retrieved
     * UsagePlanKey resource representing a plan customer.
     *

     */
    private String usagePlanId;
    /**
     *

     * The current pagination position in the paged result set.
     *

     */
    private String position;
    /**
     *

     * The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     *

     */
    private Integer limit;
    /**
     *

     * A query parameter specifying the name of the to-be-returned usage plan keys.
     *

     */
    private String nameQuery;

    /**
     *

     * [Required] The Id of the UsagePlan resource representing the usage plan containing the to-be-retrieved
     * UsagePlanKey resource representing a plan customer.
     *

     *
     * @param usagePlanId
     *        [Required] The Id of the UsagePlan resource representing the usage plan containing the
     *        to-be-retrieved UsagePlanKey resource representing a plan customer.
     */

    public void setUsagePlanId(String usagePlanId) {
        this.usagePlanId = usagePlanId;
    }

    /**
     *

     * [Required] The Id of the UsagePlan resource representing the usage plan containing the to-be-retrieved
     * UsagePlanKey resource representing a plan customer.
     *

     *
     * @return [Required] The Id of the UsagePlan resource representing the usage plan containing the
     *         to-be-retrieved UsagePlanKey resource representing a plan customer.
     */

    public String getUsagePlanId() {
        return this.usagePlanId;
    }

    /**
     *

     * [Required] The Id of the UsagePlan resource representing the usage plan containing the to-be-retrieved
     * UsagePlanKey resource representing a plan customer.
     *

     *
     * @param usagePlanId
     *        [Required] The Id of the UsagePlan resource representing the usage plan containing the
     *        to-be-retrieved UsagePlanKey resource representing a plan customer.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsagePlanKeysRequest withUsagePlanId(String usagePlanId) {
        setUsagePlanId(usagePlanId);
        return this;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @param position
     *        The current pagination position in the paged result set.
     */

    public void setPosition(String position) {
        this.position = position;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @return The current pagination position in the paged result set.
     */

    public String getPosition() {
        return this.position;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @param position
     *        The current pagination position in the paged result set.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsagePlanKeysRequest withPosition(String position) {
        setPosition(position);
        return this;
    }

    /**
     *

     * The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     *

     *
     * @param limit
     *        The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     */

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    /**
     *

     * The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     *

     *
     * @return The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     */

    public Integer getLimit() {
        return this.limit;
    }

    /**
     *

     * The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     *

     *
     * @param limit
     *        The maximum number of returned results per page. The default value is 25 and the maximum value is 500.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsagePlanKeysRequest withLimit(Integer limit) {
        setLimit(limit);
        return this;
    }

    /**
     *

     * A query parameter specifying the name of the to-be-returned usage plan keys.
     *

     *
     * @param nameQuery
     *        A query parameter specifying the name of the to-be-returned usage plan keys.
     */

    public void setNameQuery(String nameQuery) {
        this.nameQuery = nameQuery;
    }

    /**
     *

     * A query parameter specifying the name of the to-be-returned usage plan keys.
     *

     *
     * @return A query parameter specifying the name of the to-be-returned usage plan keys.
     */

    public String getNameQuery() {
        return this.nameQuery;
    }

    /**
     *

     * A query parameter specifying the name of the to-be-returned usage plan keys.
     *

     *
     * @param nameQuery
     *        A query parameter specifying the name of the to-be-returned usage plan keys.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsagePlanKeysRequest withNameQuery(String nameQuery) {
        setNameQuery(nameQuery);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getUsagePlanId() != null)
            sb.append("UsagePlanId: ").append(getUsagePlanId()).append(",");
        if (getPosition() != null)
            sb.append("Position: ").append(getPosition()).append(",");
        if (getLimit() != null)
            sb.append("Limit: ").append(getLimit()).append(",");
        if (getNameQuery() != null)
            sb.append("NameQuery: ").append(getNameQuery());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetUsagePlanKeysRequest == false)
            return false;
        GetUsagePlanKeysRequest other = (GetUsagePlanKeysRequest) obj;
        if (other.getUsagePlanId() == null ^ this.getUsagePlanId() == null)
            return false;
        if (other.getUsagePlanId() != null && other.getUsagePlanId().equals(this.getUsagePlanId()) == false)
            return false;
        if (other.getPosition() == null ^ this.getPosition() == null)
            return false;
        if (other.getPosition() != null && other.getPosition().equals(this.getPosition()) == false)
            return false;
        if (other.getLimit() == null ^ this.getLimit() == null)
            return false;
        if (other.getLimit() != null && other.getLimit().equals(this.getLimit()) == false)
            return false;
        if (other.getNameQuery() == null ^ this.getNameQuery() == null)
            return false;
        if (other.getNameQuery() != null && other.getNameQuery().equals(this.getNameQuery()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getUsagePlanId() == null) ? 0 : getUsagePlanId().hashCode());
        hashCode = prime * hashCode + ((getPosition() == null) ? 0 : getPosition().hashCode());
        hashCode = prime * hashCode + ((getLimit() == null) ? 0 : getLimit().hashCode());
        hashCode = prime * hashCode + ((getNameQuery() == null) ? 0 : getNameQuery().hashCode());
        return hashCode;
    }

    @Override
    public GetUsagePlanKeysRequest clone() {
        return (GetUsagePlanKeysRequest) super.clone();
    }

}


text:
var app = (function() {
    'use strict';
    var baseUrl = 'https://api.themoviedb.org/3/',
        apiKey = 'f2c7335dd252082fb746119aede6e440',
        shows = [],
        basePosterUrl;

    function init() {
        $('#show-list-placeholder').on('click', 'li', function(e) {
            $(e.target).closest('li').find('.details').toggle();
        });

        buildData(populateList);
    }

    function populateList() {
        var source = $('#show-list-template').html(),
            template = Handlebars.compile(source);
        $('#show-list-placeholder').html(template({shows: shows}));
    }

    function buildData(callback) {
        //this function kicks off a chain of functions to get all of the data the page needs
        loadPosterConfig(callback);
    }

    function loadPosterConfig(callback) {
        var url = baseUrl + 'configuration?callback=?';

        if (typeof basePosterUrl === 'undefined') {
            $.getJSON(url, {'api_key': apiKey}, function(response) {
                basePosterUrl = response.images.secure_base_url + response.images.poster_sizes[2];
                retrieveTopShows(callback);
            });
        }
    }

    function retrieveTopShows(callback) {
        var url = baseUrl + 'tv/top_rated?callback=?';

        $.getJSON(url, {'api_key': apiKey}, function(response) {
                _.each(response.results, function(show) {
                    shows.push({
                        id: show.id,
                        name: show.name,
                        rating: show.vote_average,
                        posterUrl: basePosterUrl + show.poster_path
                    });
                    retrieveShowDescription(show.id, callback);
                });
            }
        );
    }

    function retrieveShowDescription(showId, callback) {
        var url = baseUrl + 'tv/' + showId + '?callback=?';

        $.getJSON(url, {'api_key': apiKey}, function(response) {
                _.find(shows, {id: showId}).overview = response.overview;
                if (typeof callback === 'function') {
                    //there is probably a better way to handle this instead of redrawing the page for every show...
                    callback();
                }
            }
        );
    }

    return {
        init: init,
        buildData: buildData
    };
})();


text:
function makeSymbol(sym, alp) {
    return {
        symbol: sym,
        alphabet: alp || "Turtle2D"
    };
}

/**
 * Testing {@link l2js.compiler.Compiler} for basic constructs of L2
 */
describe("Interpret", function() {
    var Interpret, Alphabet;

    beforeEach(function() {
        Interpret = l2js.interpret.Interpret;
        Alphabet = l2js.compiler.env.Alphabet;
        SubLSystem = l2js.compiler.env.SubLSystem;
    });

    // fake builder

    function Turtle2DBuilder() {

    };

    Turtle2DBuilder.prototype.interpret = function(symbol, ctx) {
        console.log(symbol);
    };

    l2js.interpret.Turtle2DBuilder = Turtle2DBuilder;

    describe("clear out SubLSystems with unspecified interpretation symbols", function() {
        var result, sub1, sub2, sub3;

        beforeEach(function() {
            result = {
                interpretation: []
            };

            sub1 = new SubLSystem();
            sub2 = new SubLSystem();
            sub3 = new SubLSystem();

            sub1.interpretation = [];
            sub2.interpretation = [makeSymbol("F2")];
        });

        it('and result contains only symbols and SubLSystems with symbols', function() {
            result.interpretation = [sub2];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(1);

            result.interpretation = [sub2, makeSymbol("f")];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(2);
        });

        it("in one level structure", function() {

            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);

            result.interpretation = [sub1];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);

            result.interpretation = [sub3];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);
        });

        it("in tree structure", function() {

            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);

            sub1.interpretation = [];
            result.interpretation = [sub1];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);

            sub1.interpretation = [sub3];
            result.interpretation = [sub1];
            interpret = new Interpret(result);
            expect(interpret.result.interpretation.length).toBe(0);

        });

    });

    describe("finds if exists next symbol", function() {

        var result, interpret;

        it('without sub-L-systems', function() {
            result = {
                interpretation: [makeSymbol("F1"), makeSymbol("F2")]
            };
            interpret = new Interpret(result);
            expect(interpret.hasNextSymbol()).toBeTruthy();
            interpret.next();
            expect(interpret.hasNextSymbol()).toBeTruthy();
            interpret.next();
            expect(interpret.hasNextSymbol()).not.toBeTruthy();

        });

        it('with sub-L-systems', function() {

            sub1 = new SubLSystem();
            sub1.interpretation = [makeSymbol("F2")];
            sub2 = new SubLSystem();
            sub2.interpretation = [makeSymbol("F3")];

            sub1.interpretation = [makeSymbol("F2"), sub2, makeSymbol("F4")];
            result = {
                interpretation: [makeSymbol("F1"), sub1, makeSymbol("F5")]
            };
            interpret = new Interpret(result);
            expect(interpret.hasNextSymbol()).toBeTruthy();
            expect(interpret.next().symbol).toBe("F1");
            expect(interpret.hasNextSymbol()).toBeTruthy();
            expect(interpret.next().symbol).toBe("F2");
            expect(interpret.hasNextSymbol()).toBeTruthy();
            expect(interpret.next().symbol).toBe("F3");
            expect(interpret.hasNextSymbol()).toBeTruthy();
            expect(interpret.next().symbol).toBe("F4");
            expect(interpret.hasNextSymbol()).toBeTruthy();
            expect(interpret.next().symbol).toBe("F5");
            expect(interpret.hasNextSymbol()).not.toBeTruthy();

        });

        describe('and supports callbacks', function() {

            beforeEach(function() {
                sub1 = new SubLSystem();
                sub1.interpretation = [makeSymbol("F2")];
                sub2 = new SubLSystem();
                sub2.interpretation = [makeSymbol("F3")];

                sub1.interpretation = [makeSymbol("F2"), sub2, makeSymbol("F4")];
                result = {
                    interpretation: [makeSymbol("F1"), sub1, makeSymbol("F5")]
                };

            });

            it('for the end of interpretation', function(done) {
                interpret = new Interpret(result, {
                    callbacks: {
                        end: function() {
                            expect(steps).toBe(6);
                            done();
                        }
                    }
                });
                var steps;
                for (steps = 1; steps <= 6; steps++) {
                    interpret.next();
                }
            });

            // TODO: start and end of sublsystem
        });
    });

});


text:
import React from 'react'
import { Divider, Segment } from 'shengnian-ui-react'

const DividerExampleSection = () => (
  <Segment>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
    <Divider section />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
  </Segment>
)

export default DividerExampleSection


text:
package com.finki.emt.bookstore.config;

import com.finki.emt.bookstore.security.AuthoritiesConstants;
import com.finki.emt.bookstore.security.CustomAccessDeniedHandler;
import com.finki.emt.bookstore.security.Http401UnauthorizedEntryPoint;
import com.finki.emt.bookstore.security.SecurityUtil;
import com.finki.emt.bookstore.security.jwt.JWTConfigurer;
import com.finki.emt.bookstore.security.jwt.TokenProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.inject.Inject;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Inject
    private Http401UnauthorizedEntryPoint authenticationEntryPoint;

    @Inject
    private CustomAccessDeniedHandler accessDeniedHandler;

    @Inject
    private UserDetailsService userDetailsService;

    @Inject
    private TokenProvider tokenProvider;

    @Inject
    private SecurityUtil securityUtil;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
                // users routes
                .antMatchers("/api/users/count")
                    .hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/users/{slug}/**")
                    .authenticated()
                .antMatchers("/api/users/**")
                    .hasAuthority(AuthoritiesConstants.ADMIN)

                // books routes
                .antMatchers("/api/books/count")
                    .hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers(HttpMethod.POST, "/api/books")
                    .hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers(HttpMethod.PUT, "/api/books/{slug}")
                    .hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers(HttpMethod.DELETE, "/api/books/{slug}")
                    .hasAuthority(AuthoritiesConstants.ADMIN)

                // favorite books routes
                .antMatchers("/api/books/{slug}/favorites/**")
                    .hasAuthority(AuthoritiesConstants.USER)

                // basket routes
                .antMatchers("/api/basket/**")
                    .hasAuthority(AuthoritiesConstants.USER)

                // orders routes
                .antMatchers("/api/orders/count")
                    .hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/orders/{id}/**")
                    .authenticated()
                .antMatchers("/api/orders/**")
                    .hasAuthority(AuthoritiesConstants.ADMIN)

                // promotion routes
                .antMatchers("/api/books/{slug}/promotion")
                    .hasAuthority(AuthoritiesConstants.ADMIN)

                .antMatchers("/api/**").permitAll()
        .and()
            .apply(securityConfigurerAdapter());
    }

    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider, securityUtil);
    }
}


text:
#!/usr/bin/env bash
#
#
#
# Runs a Hadoop hbase command as a daemon.
#
# Environment Variables
#
#   HBASE_CONF_DIR   Alternate hbase conf dir. Default is ${HBASE_HOME}/conf.
#   HBASE_LOG_DIR    Where log files are stored.  PWD by default.
#   HBASE_PID_DIR    The pid files are stored. /tmp by default.
#   HBASE_IDENT_STRING   A string representing this instance of hadoop. $USER by default
#   HBASE_NICENESS The scheduling priority for daemons. Defaults to 0.
#
# Modelled after $HADOOP_HOME/bin/hadoop-daemon.sh

usage="Usage: hbase-daemon.sh [--config <conf-dir>]\
 (start|stop|restart) <hbase-command> \
 <args...>"

# if no args specified, show usage
if [ $# -le 1 ]; then
  echo $usage
  exit 1
fi

bin=`dirname "${BASH_SOURCE-$0}"`
bin=`cd "$bin">/dev/null; pwd`

. "$bin"/hbase-config.sh

# get arguments
startStop=$1
shift

command=$1
shift

hbase_rotate_log ()
{
    log=$1;
    num=5;
    if [ -n "$2" ]; then
    num=$2
    fi
    if [ -f "$log" ]; then # rotate logs
    while [ $num -gt 1 ]; do
        prev=`expr $num - 1`
        [ -f "$log.$prev" ] && mv -f "$log.$prev" "$log.$num"
        num=$prev
    done
    mv -f "$log" "$log.$num";
    fi
}

wait_until_done ()
{
    p=$1
    cnt=${HBASE_SLAVE_TIMEOUT:-300}
    origcnt=$cnt
    while kill -0 $p > /dev/null 2>&1; do
      if [ $cnt -gt 1 ]; then
        cnt=`expr $cnt - 1`
        sleep 1
      else
        echo "Process did not complete after $origcnt seconds, killing."
        kill -9 $p
        exit 1
      fi
    done
    return 0
}

# get log directory
if [ "$HBASE_LOG_DIR" = "" ]; then
  export HBASE_LOG_DIR="$HBASE_HOME/logs"
fi
mkdir -p "$HBASE_LOG_DIR"

if [ "$HBASE_PID_DIR" = "" ]; then
  HBASE_PID_DIR=/tmp
fi

if [ "$HBASE_IDENT_STRING" = "" ]; then
  export HBASE_IDENT_STRING="$USER"
fi

# Some variables
# Work out java location so can print version into log.
if [ "$JAVA_HOME" != "" ]; then
  #echo "run java in $JAVA_HOME"
  JAVA_HOME=$JAVA_HOME
fi
if [ "$JAVA_HOME" = "" ]; then
  echo "Error: JAVA_HOME is not set."
  exit 1
fi
JAVA=$JAVA_HOME/bin/java
export HBASE_LOG_PREFIX=hbase-$HBASE_IDENT_STRING-$command-$HOSTNAME
export HBASE_LOGFILE=$HBASE_LOG_PREFIX.log
export HBASE_ROOT_LOGGER="INFO,DRFA"
export HBASE_SECURITY_LOGGER="INFO,DRFAS"
logout=$HBASE_LOG_DIR/$HBASE_LOG_PREFIX.out
loggc=$HBASE_LOG_DIR/$HBASE_LOG_PREFIX.gc
loglog="${HBASE_LOG_DIR}/${HBASE_LOGFILE}"
pid=$HBASE_PID_DIR/hbase-$HBASE_IDENT_STRING-$command.pid

if [ "$HBASE_USE_GC_LOGFILE" = "true" ]; then
  export HBASE_GC_OPTS=" -Xloggc:${loggc}"
fi

# Set default scheduling priority
if [ "$HBASE_NICENESS" = "" ]; then
    export HBASE_NICENESS=0
fi

case $startStop in

  (start)
    mkdir -p "$HBASE_PID_DIR"
    if [ -f $pid ]; then
      if kill -0 `cat $pid` > /dev/null 2>&1; then
        echo $command running as process `cat $pid`.  Stop it first.
        exit 1
      fi
    fi

    hbase_rotate_log $logout
    hbase_rotate_log $loggc
    echo starting $command, logging to $logout
    # Add to the command log file vital stats on our environment.
    echo "`date` Starting $command on `hostname`" >> $loglog
    echo "`ulimit -a`" >> $loglog 2>&1
    nohup nice -n $HBASE_NICENESS "$HBASE_HOME"/bin/hbase \
        --config "${HBASE_CONF_DIR}" \
        $command "$@" $startStop > "$logout" 2>&1 < /dev/null &
    echo $! > $pid
    sleep 1; head "$logout"
    ;;

  (stop)
    if [ -f $pid ]; then
      # kill -0 == see if the PID exists
      if kill -0 `cat $pid` > /dev/null 2>&1; then
        echo -n stopping $command
        echo "`date` Terminating $command" >> $loglog
        kill `cat $pid` > /dev/null 2>&1
        while kill -0 `cat $pid` > /dev/null 2>&1; do
          echo -n "."
          sleep 1;
        done
        rm $pid
        echo
      else
        retval=$?
        echo no $command to stop because kill -0 of pid `cat $pid` failed with status $retval
      fi
    else
      echo no $command to stop because no pid file $pid
    fi
    ;;

  (restart)
    thiscmd=$0
    args=$@
    # stop the command
    $thiscmd --config "${HBASE_CONF_DIR}" stop $command $args &
    wait_until_done $!
    # wait a user-specified sleep period
    sp=${HBASE_RESTART_SLEEP:-3}
    if [ $sp -gt 0 ]; then
      sleep $sp
    fi
    # start the command
    $thiscmd --config "${HBASE_CONF_DIR}" start $command $args &
    wait_until_done $!
    ;;

  (*)
    echo $usage
    exit 1
    ;;

esac


text:
[![Build Status](https://travis-ci.org/DanBloomberg/leptonica.svg?branch=master)](https://travis-ci.org/DanBloomberg/leptonica)
[![Build status](https://ci.appveyor.com/api/projects/status/vsk607rr6n4j2tmk?svg=true)](https://ci.appveyor.com/project/DanBloomberg/leptonica)

www.leptonica.org

## The library supports many operations that are useful on ##

  * Document images
  * Natural images

## Fundamental image processing and image analysis operations ##

  * Rasterop (aka bitblt)
  * Affine transforms (scaling, translation, rotation, shear) on images of arbitrary pixel depth
  * Projective and bilinear transforms
  * Binary and grayscale morphology, rank order filters, and convolution
  * Seedfill and connected components
  * Image transformations with changes in pixel depth, both at the same scale and with scale change
  * Pixelwise masking, blending, enhancement, arithmetic ops, etc.

## Ancillary utilities ##

  * I/O for standard image formats (_jpg_, _png_, _tiff_, _webp_, _jp2_, _bmp_, _pnm_, _gif_, _ps_, _pdf_)
  * Utilities to handle arrays of image-related data types (e.g., _pixa_, _boxa_, _pta_)
  * Utilities for stacks, generic arrays, queues, heaps, lists; number and string arrays; etc.

## Examples of some applications enabled and implemented ##

  * Octcube-based color quantization (w/ and w/out dithering)
  * Modified median cut color quantization (w/ and w/out dithering)
  * Skew determination of text images
  * Adaptive normalization and binarization
  * Segmentation of page images with mixed text and images
  * Location of baselines and local skew determination
  * jbig2 unsupervised classifier
  * Border representations of 1 bpp images and raster conversion for SVG
  * Postscript generation (levels 1, 2 and 3) of images for device-independent output
  * PDF generation (G4, DCT, FLATE) of images for device-independent output
  * Connectivity-preserving thinning and thickening of 1 bpp images
  * Image warping (captcha, stereoscopic)
  * Image dewarping based on content (textlines)
  * Watershed transform
  * Greedy splitting of components into rectangles
  * Location of largest fg or bg rectangles in 1 bpp images
  * Search for least-cost paths on binary and grayscale images
  * Barcode reader for 1D barcodes (very early version as of 1.55)

## Implementation characteristics ##

  * _Efficient_: image data is packed binary (into 32-bit words); operations on 32-bit data whenever possible
  * _Simple_: small number of data structures; simplest implementations provided that are efficient
  * _Consistent_: data allocated on the heap with simple ownership rules; function names usually begin with primary data structure (e.g., _pix_); simple code patterns throughout
  * _Robust_: all ptr args checked; extensive use of accessors; exit not permitted
  * _Tested_: thorough regression tests provided for most basic functions; valgrind tested
  * _ANSI C_: automatically generated prototype header file
  * _Portable_: endian-independent; builds in linux, osx, mingw, cygwin, windows
  * _Nearly thread-safe_: ref counting on some structs
  * _Documentation_: large number of in-line comments; web pages for further background
  * _Examples_: many programs provided to test and show usage of approx. 2200 functions in the library

## Open Source Projects that use Leptonica ##
  * [php](http://en.wikipedia.org/wiki/PHP)  (scripting language for dynamic web pages)
  * [tesseract](https://github.com/tesseract-ocr/tesseract/) (optical character recognition)
  * [jbig2enc](http://www.imperialviolet.org/jbig2.html) (encodes multipage binary image documents with jbig2 compression)

## Major contributors to Leptonica ##
  * Tom Powers: Tom has supported leptonica on Windows for many years.  He has made many contributions to code quality and documentation, including the beautiful "unofficial documentation" on the web site. Without his effort, leptonica would not run today on Windows.
  * David Bryan: David has worked for years to support leptonica on multiple platforms. He designed many nice features in leptonica, such as the severity-based error messaging system, and has identified and fixed countless bugs. And he has built and tested each distribution many times on cross-compilers.
  * James Le Cuirot: James has written and supported the autotools scripts on leptonica distributions for many years, and has helped test every distribution since 1.67.
  * Jeff Breidenbach: Jeff has built every debian distribution for leptonica. He has also made many improvements to formatted image I/O, including tiff, png and pdf. He is a continuous advocate for simplification.
  * Egor Pugin: Egor is co-maintainer of leptonica on github. He ported everything, including all the old distributions, from Google Code when it shut down. He set leptonica up for appveyor and travis testing, and has implemented the cppan project, which simplifies building executables on Windows.
  * Jürgen Buchmüller: Jürgen wrote text converters to modify leptonica source code so that it generates documentation using doxygen. He also wrote tiff wrappers for memory I/O.


text:
namespace blink {

bool bigIntegerToUint(const WebVector<unsigned char>& bigInteger, unsigned& result)
{
    result = 0;
    for (size_t i = 0; i < bigInteger.size(); ++i) {
        size_t iReversed = bigInteger.size() - i - 1;

        if (iReversed >= sizeof(result) && bigInteger[i])
            return false; // Too large for unsigned int.

        result |= bigInteger[i] << 8 * iReversed;
    }
    return true;
}

} // namespace blink


text:
#ifndef WebSpellCheckClient_h
#define WebSpellCheckClient_h

#include "../platform/WebString.h"
#include "../platform/WebVector.h"
#include "WebTextCheckingType.h"

namespace blink {

class WebString;
class WebTextCheckingCompletion;
struct WebTextCheckingResult;

class WebSpellCheckClient {
public:
    // The client should perform spell-checking on the given text. If the
    // text contains a misspelled word, then upon return misspelledOffset
    // will point to the start of the misspelled word, and misspelledLength
    // will indicates its length. Otherwise, if there was not a spelling
    // error, then upon return misspelledLength is 0. If optional_suggestions
    // is given, then it will be filled with suggested words (not a cheap step).
    virtual void spellCheck(const WebString& text,
                            int& misspelledOffset,
                            int& misspelledLength,
                            WebVector<WebString>* optionalSuggestions) { }

    // The client should perform spell-checking on the given text. This function will
    // enumerate all misspellings at once.
    virtual void checkTextOfParagraph(const WebString&,
                                      WebTextCheckingTypeMask mask,
                                      WebVector<WebTextCheckingResult>* results) { }

    // Requests asynchronous spelling and grammar checking, whose result should be
    // returned by passed completion object.
    virtual void requestCheckingOfText(const WebString& textToCheck,
                                       const WebVector<uint32_t>& markersInText,
                                       const WebVector<unsigned>& markerOffsets,
                                       WebTextCheckingCompletion* completionCallback) { }

    // Computes an auto-corrected replacement for a misspelled word. If no
    // replacement is found, then an empty string is returned.
    virtual WebString autoCorrectWord(const WebString& misspelledWord) { return WebString(); }

    // Show or hide the spelling UI.
    virtual void showSpellingUI(bool show) { }

    // Returns true if the spelling UI is showing.
    virtual bool isShowingSpellingUI() { return false; }

    // Update the spelling UI with the given word.
    virtual void updateSpellingUIWithMisspelledWord(const WebString& word) { }

protected:
    ~WebSpellCheckClient() { }
};

} // namespace blink

#endif


text:
/*
 * Project name:
     Demo3_4 : Timer of 1 ms with compare mode on Counter/Timer 2
 * Author: Avans-TI, JW
 * Revision History:
     20101222: - initial release;
 * Description:
     This program gives an interrupt on each ms
 * Test configuration:
     MCU:             ATmega128
     Dev.Board:       BIGAVR6
     Oscillator:      External Clock 08.0000 MHz
     Ext. Modules:    -
     SW:              AVR-GCC
 * NOTES:
     - Turn ON the PORT LEDs at SW12.1 - SW12.8
*/

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#define BIT(x)	(1 << (x))
#define CompareValue 10

unsigned char msCount = 0;

// wait(): busy waiting for 'ms' millisecond
// Used library: util/delay.h
void wait( int ms )
{
	for (int i=0; i<ms; i++)
	{
		_delay_ms( 1 );			// library function (max 30 ms at 8MHz)
	}
}

// Interrupt routine timer2 compare match toggle
//
ISR( TIMER2_COMP_vect )
{
	msCount++;					// Increment ms counter
	if ( msCount == 250 )
	{
		PORTC ^= BIT(0);		// Toggle bit 0 van PORTC
		msCount = 0;			// Reset ms_count value
	}
}

// Initialize timer 2: counting, preset, interrupt on overflow
void timer2Init( void )
{
	OCR2 = 250;					// Compare value of counter 2
	TIMSK |= BIT(7);			// T2 compare match interrupt enable
	SREG |= BIT(7);				// turn_on intr all
	TCCR2 = 0b00001011;			// Initialize T2: timer, prescaler=32,
								// 	compare output disconnected, CTC, RUN
}

// Main program: Counting on T2
int main( void )
{
	DDRC = 0xFF;				// set PORTC for output (shows toggle bit)
	timer2Init();

	while (1)
	{
		// do something else
		wait(250);				// every 10 ms (busy waiting)
		PORTC ^= BIT(7);
	}
}


text:
package com.huihuan.jerrys.shiro.server.web.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class DefaultExceptionHandler {
    /**
     * 没有权限 异常
     * <p/>
     * 后续根据不同的需求定制即可
     */
    @ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", e);
        mv.setViewName("unauthorized");
        return mv;
    }
}