text:
#import "NSObject.h"

@interface IBConnectionInterfaceStyle : NSObject
{
}

+ (id)invertedAnnotationStyle;
+ (id)annotationStyle;
+ (id)objectWellStyle;
+ (id)inspectorStyle;
+ (id)HUDStyle;
- (id)connectionWellFillColorDisabled;
- (id)completionMenuPopUpBackgroundColorHighlighted;
- (id)completionMenuPopUpBackgroundColor;
- (id)completionMenuPopUpTextColorHighlighted;
- (id)completionMenuPopUpTextColor;
- (id)connectionWellButtonImageForStateWarned:(unsigned long long)arg1;
- (id)connectionWellButtonImageForState:(unsigned long long)arg1;
- (id)connectionWellFillColor;
- (id)connectionWellBorderColorWhenRolloverOrPreceeded;
- (id)connectionWellFillColorRolloverOrPreceeded;
- (id)connectionWellBorderColor;
- (id)connectionWellPlusColorPressed;
- (id)connectionWellPlusColor;
- (id)connectionWellBorderColorDisabled;
- (id)predecessorViewDisconnectButtonImageForState:(unsigned long long)arg1;
- (id)predecessorViewTextColorDisabled;
- (id)predecessorViewTextColor;
- (id)predecessorViewDisconnectButtonRolledOverFillColor;
- (id)predecessorViewDisconnectButtonPressedStrokeColor;
- (id)predecessorViewDisconnectButtonRolledOverStrokeColor;
- (id)predecessorViewDisconnectButtonPressedFillColor;
- (id)predecessorViewDisconnectButtonFillColor;
- (id)predecessorViewDisconnectButtonDisabledFillColor;
- (id)predecessorViewDisconnectButtonDisabledIconColor;
- (id)predecessorViewDisconnectButtonPressedIconColor;
- (id)predecessorViewDisconnectButtonIconColor;
- (id)predecessorViewDisconnectButtonRolledOverIconColor;
- (id)predecessorViewWarningBangColor;
- (id)predecessorViewWarningTriangleColor;
- (id)predecessorViewWarningPressedColor;
- (id)predecessorViewFont;
- (id)prototypeViewBottomBorderColor;
- (id)prototypeViewBackgroundColor;
- (id)prototypeViewLinkBubbleBorderColor;
- (id)prototypeViewLinkBubbleBackgroundColor;
- (id)prototypeViewLinkBubbleBorderColorRolledOver;
- (id)prototypeViewLinkBubbleBackgroundColorRolledOver;
- (id)prototypeViewTextColor;
- (id)prototypeViewFont;
- (id)disclosureHeaderButtonImageForState:(unsigned long long)arg1;
- (id)disclosureHeaderButtonColorPressed;
- (id)disclosureHeaderButtonColor;
- (id)disclosureHeaderBottomBorderColor;
- (id)disclosureHeaderBackgroundColor;
- (id)disclosureHeaderTitleColor;
- (id)disclosureHeaderTitleFont;
- (id)disclosureView;
- (id)disclosureViewBottomBorderColor;
- (BOOL)fadesOutDragWindow;

@end


text:
window.engine = (new (function() {

  this.Q = MathJax.Hub.queue;
  this.tex = null;
  this.mml = null;
  this.buffer = [];

  // bind helper.
  this.bind = function(method) {
    var engine = this;
    return function() {
      return method.apply(engine, arguments);
    };
  };

  // Initialize engine.
  this._init = function() {
    this.Q.Push(this.bind(function () {
      this.tex = {
        div: document.getElementById("math-tex"),
        jax: MathJax.Hub.getAllJax("math-tex")[0],
        last_width: null,
        last_q: ''
      }
      this.mml = {
        div: document.getElementById("math-mml"),
        jax: MathJax.Hub.getAllJax("math-mml")[0],
        last_width: null,
        last_q: ''
      }
      this._process_buffered();
    }));
  };

  // This helper function determines whether or not a <text> node inside the SVG
  // output from MathJax is an error message.  It uses the default error message
  // fill color.  Note that the constant #C00 could be overriden by the MathJax
  // config!!
  this._text_is_error = function(txt) {
    return txt.getAttribute("fill") == "#C00" &&
      txt.getAttribute("stroke") == "none";
  };

  // Serialize an (svg) element
  this._serialize = function(svg) {
    var tmpDiv = document.createElement('div');
    tmpDiv.appendChild(svg);
    return tmpDiv.innerHTML;
  };

  // MathJax keeps parts of SVG symbols in one hidden svg at
  // the begining of the DOM, this function should take two
  // SVGs and return one stand-alone svg which could be
  // displayed like an image on some different page.
  this._merge = function(svg) {
    var origDefs = document.getElementById('MathJax_SVG_Hidden')
      .nextSibling.childNodes[0];
    var defs = origDefs.cloneNode(false);

    // append shallow defs and change xmlns.
    svg.insertBefore(defs, svg.childNodes[0]);
    svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");

    // clone and copy all used paths into local defs.
    // xlink:href in uses FIX
    var uses = svg.getElementsByTagName("use");
    for (var k = 0; k < uses.length; ++k) {
      var id = uses[k].getAttribute("href");
      defs.appendChild(
        document.getElementById(id.substr(1)).cloneNode(true)
      );
      uses[k].setAttribute("xlink:href", id);
    }

    svg.style.position = "static";
    return this._serialize(svg);
  };

  // If someone calls process() before init is complete,
  // that call will be stored into a buffer. After the init
  // is complete, all buffer stuff will get resolved.
  this._process_buffered = function() {
    for (var i = 0; i < this.buffer.length; ++i) {
      this.process(this.buffer[i][0], this.buffer[i][1]);
    }
    this.buffer = [];
  };

  // When process() is finished, the callback cb will be invoked with an
  // array [<q string>, <svg out>].
  // If there is an error during the rendering then the second
  // element, instead of a string, will be a nested array with
  // one string element giving the error message.
  this.process = function(query, cb) {
    // For debugging, the console doesn't work from here, but you can return dummy
    // data, as follows.  It will show up in the browser instead of the real results.
    //cb([query.num, query.q, ["debug message"]]);
    //return;

    var type = query.type;
    if (this[type] === null || this[type].jax === null) {
      this.buffer.push( [query, cb] );
    }
    else {

      var q = query.q,
          width = query.width,
          t = this[type],
          div = t.div,
          jax = t.jax;

      if (width === null) {
        //div.removeAttribute('style');
        // Let's just use a default width of 1000 (arbitrary)
        div.setAttribute('style', 'width: 1000px');
      }
      else {
        div.setAttribute('style', 'width: ' + width + 'px');
      }

      // Possibilities:
      // - if q and width are the same as last time, no need to Rerender
      // - if q is the same, but width is not, then Rerender() (calling
      //   Text() does not work)
      // - if q is not the same, call Text()

      if (t.last_q == q && t.last_width !== width) {
        this.Q.Push(["Rerender", jax]);
      }
      else if (t.last_q != q) {
        this.Q.Push(["Text", jax, q]);
      }
      t.last_q = q;
      t.last_width = width;

      this.Q.Push(this.bind(function() {
        var svg_elem = div.getElementsByTagName("svg")[0];
        var ret = null;
        if (!svg_elem) {
          ret = ['MathJax error'];
        }
        else {
          var texts = svg_elem.getElementsByTagName("text");
          for (var i = 0; i < texts.length; ++i) {
            if (this._text_is_error(texts[i])) {
              ret = [texts[i].textContent];
              break;
            }
          }
        }
        if (!ret) {    // no error
          ret = this._merge(svg_elem.cloneNode(true));
        }

        cb([query.num, query.q, ret]);
      }));
    }
  };

  this._init();
}));

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include <u.h>
#include <libc.h>
#include "gg.h"

int	thechar	= '7';
char*	thestring = "arm64";
LinkArch*	thelinkarch = &linkarm64;

void
linkarchinit(void)
{
}

vlong MAXWIDTH = 1LL<<50;

/*
 * go declares several platform-specific type aliases:
 * int, uint, float, and uintptr
 */
Typedef	typedefs[] =
{
	{"int",		TINT,		TINT64},
	{"uint",		TUINT,		TUINT64},
	{"uintptr",	TUINTPTR,	TUINT64},
	{0}
};

void
betypeinit(void)
{
	widthptr = 8;
	widthint = 8;
	widthreg = 8;

	zprog.link = P;
	zprog.as = AGOK;
	zprog.reg = NREG;
	zprog.from.name = D_NONE;
	zprog.from.type = D_NONE;
	zprog.from.reg = NREG;
	zprog.to = zprog.from;
	zprog.from3 = zprog.from;

	listinit7();
}


text:
import abc
import collections

from keystoneclient import exceptions
import six

from rally.common import logging

LOG = logging.getLogger(__name__)

Project = collections.namedtuple("Project", ["id", "name", "domain_id"])
User = collections.namedtuple("User",
                              ["id", "name", "project_id", "domain_id"])
Service = collections.namedtuple("Service", ["id", "name"])
Role = collections.namedtuple("Role", ["id", "name"])

@six.add_metaclass(abc.ABCMeta)
class KeystoneWrapper(object):
    def __init__(self, client):
        self.client = client

        LOG.warning(
            "Class %s is deprecated since Rally 0.8.0 and will be removed "
            "soon. Use "
            "rally.plugins.openstack.services.identity.identity.Identity "
            "instead." % self.__class__)

    def __getattr__(self, attr_name):
        return getattr(self.client, attr_name)

    @abc.abstractmethod
    def create_project(self, project_name, domain_name="Default"):
        """Creates new project/tenant and return project object.

        :param project_name: Name of project to be created.
        :param domain_name: Name or id of domain where to create project, for
                            implementations that don't support domains this
                            argument must be None or 'Default'.
        """

    @abc.abstractmethod
    def delete_project(self, project_id):
        """Deletes project."""

    @abc.abstractmethod
    def create_user(self, username, password, email=None, project_id=None,
                    domain_name="Default", default_role="member"):
        """Create user.

        :param username: name of user
        :param password: user password
        :param project: user's default project
        :param domain_name: Name or id of domain where to create project, for
                            implementations that don't support domains this
                            argument must be None or 'Default'.
        :param default_role: user's default role
        """

    @abc.abstractmethod
    def delete_user(self, user_id):
        """Deletes user."""

    @abc.abstractmethod
    def list_users(self):
        """List all users."""

    @abc.abstractmethod
    def list_projects(self):
        """List all projects/tenants."""

    def delete_service(self, service_id):
        """Deletes service."""
        self.client.services.delete(service_id)

    def list_services(self):
        """List all services."""
        return map(KeystoneWrapper._wrap_service, self.client.services.list())

    def create_role(self, name, **kwargs):
        """create a role.

        :param name: name of role
        :param kwargs: Optional additional arguments for roles creation
        """

    def delete_role(self, role_id):
        """Deletes role."""
        self.client.roles.delete(role_id)

    def list_roles(self):
        """List all roles."""
        return map(KeystoneWrapper._wrap_role, self.client.roles.list())

    @abc.abstractmethod
    def add_role(self, role_id, user_id, project_id):
        """Assign role to user."""

    @abc.abstractmethod
    def remove_role(self, role_id, user_id, project_id):
        """Remove role from user."""

    @staticmethod
    def _wrap_service(service):
        return Service(id=service.id, name=service.name)

    @staticmethod
    def _wrap_role(role):
        return Role(id=role.id, name=role.name)

class KeystoneV2Wrapper(KeystoneWrapper):
    def _check_domain(self, domain_name):
        if domain_name.lower() != "default":
            raise NotImplementedError("Domain functionality not implemented "
                                      "in Keystone v2")

    @staticmethod
    def _wrap_v2_tenant(tenant):
        return Project(id=tenant.id, name=tenant.name, domain_id="default")

    @staticmethod
    def _wrap_v2_role(role):
        return Role(id=role.id, name=role.name)

    @staticmethod
    def _wrap_v2_user(user):
        return User(id=user.id, name=user.name,
                    project_id=getattr(user, "tenantId", None),
                    domain_id="default")

    def create_project(self, project_name, domain_name="Default"):
        self._check_domain(domain_name)
        tenant = self.client.tenants.create(project_name)
        return KeystoneV2Wrapper._wrap_v2_tenant(tenant)

    def delete_project(self, project_id):
        self.client.tenants.delete(project_id)

    def create_user(self, username, password, email=None, project_id=None,
                    domain_name="Default", default_role="member"):
        # NOTE(liuyulong): For v2 wrapper the `default_role` here is not used.
        self._check_domain(domain_name)
        user = self.client.users.create(username, password, email, project_id)
        return KeystoneV2Wrapper._wrap_v2_user(user)

    def delete_user(self, user_id):
        self.client.users.delete(user_id)

    def list_users(self):
        return map(KeystoneV2Wrapper._wrap_v2_user, self.client.users.list())

    def list_projects(self):
        return map(KeystoneV2Wrapper._wrap_v2_tenant,
                   self.client.tenants.list())

    def create_role(self, name):
        role = self.client.roles.create(name)
        return KeystoneV2Wrapper._wrap_v2_role(role)

    def add_role(self, role_id, user_id, project_id):
        self.client.roles.add_user_role(user_id, role_id, tenant=project_id)

    def remove_role(self, role_id, user_id, project_id):
        self.client.roles.remove_user_role(user_id, role_id, tenant=project_id)

class KeystoneV3Wrapper(KeystoneWrapper):
    def _get_domain_id(self, domain_name_or_id):
        try:
            # First try to find domain by ID
            return self.client.domains.get(domain_name_or_id).id
        except exceptions.NotFound:
            # Domain not found by ID, try to find it by name
            domains = self.client.domains.list(name=domain_name_or_id)
            if domains:
                return domains[0].id
            # Domain not found by name, raise original NotFound exception
            raise

    @staticmethod
    def _wrap_v3_project(project):
        return Project(id=project.id, name=project.name,
                       domain_id=project.domain_id)

    @staticmethod
    def _wrap_v3_role(role):
        return Role(id=role.id, name=role.name)

    @staticmethod
    def _wrap_v3_user(user):
        # When user has default_project_id that is None user.default_project_id
        # will raise AttributeError
        project_id = getattr(user, "default_project_id", None)
        return User(id=user.id, name=user.name, project_id=project_id,
                    domain_id=user.domain_id)

    def create_project(self, project_name, domain_name="Default"):
        domain_id = self._get_domain_id(domain_name)
        project = self.client.projects.create(
            name=project_name, domain=domain_id)
        return KeystoneV3Wrapper._wrap_v3_project(project)

    def delete_project(self, project_id):
        self.client.projects.delete(project_id)

    def create_user(self, username, password, email=None, project_id=None,
                    domain_name="Default", default_role="member"):
        domain_id = self._get_domain_id(domain_name)
        user = self.client.users.create(name=username, password=password,
                                        default_project=project_id,
                                        email=email, domain=domain_id)
        for role in self.client.roles.list():
            if default_role in role.name.lower():
                self.client.roles.grant(role.id, user=user.id,
                                        project=project_id)
                break
        else:
            LOG.warning(
                "Unable to set %s role to created user." % default_role)
        return KeystoneV3Wrapper._wrap_v3_user(user)

    def delete_user(self, user_id):
        self.client.users.delete(user_id)

    def list_users(self):
        return map(KeystoneV3Wrapper._wrap_v3_user, self.client.users.list())

    def list_projects(self):
        return map(KeystoneV3Wrapper._wrap_v3_project,
                   self.client.projects.list())

    def create_role(self, name, domain, **kwargs):
        role = self.client.roles.create(name, domain=domain, **kwargs)
        return KeystoneV3Wrapper._wrap_v3_role(role)

    def add_role(self, role_id, user_id, project_id):
        self.client.roles.grant(role_id, user=user_id, project=project_id)

    def remove_role(self, role_id, user_id, project_id):
        self.client.roles.revoke(role_id, user=user_id, project=project_id)

def wrap(client):
    """Returns keystone wrapper based on keystone client version."""
    LOG.warning("Method wrap from %s and whole Keystone wrappers are "
                "deprecated since Rally 0.8.0 and will be removed soon. Use "
                "rally.plugins.openstack.services.identity.identity.Identity "
                "instead." % __file__)

    if client.version == "v2.0":
        return KeystoneV2Wrapper(client)
    elif client.version == "v3":
        return KeystoneV3Wrapper(client)
    else:
        raise NotImplementedError(
            "Wrapper for version %s is not implemented." % client.version)


text:
Engulf is an original puzzle game featuring 56 unique levels.

## HTML5 implementation (2017)

Play it here:

[https://helderman.github.io/engulf/html5/engulf.html](https://helderman.github.io/engulf/html5/engulf.html)

## Scratch implementation (2017)

The game can be played
[here](https://scratch.mit.edu/projects/144893330/).

### Instructions

Use your mouse to guide the color-changing ball through 56 unique levels.
Instructions are in the game.
ALL levels are possible!

Please feel free to remix and show everyone
your most BEAUTIFUL, most CHALLENGING, most ORIGINAL level designs!
(All you need is Scratch's costume editor; see inside for guidelines.)

### Notes and Credits

Experimental multi-level puzzle game.
Idea, design and programming by
[heldlaw](https://scratch.mit.edu/users/heldlaw/),
February-June 2017.

Title screen made using [GIMP](https://www.gimp.org/);
most notably the 'Cubism' filter.

Title font: Grudge BRK. Copyright © ÆNIGMA FONTS, 1999.

All other graphics (including the levels)
were drawn using Scratch's costume editor (in vector mode).

- Level "Julie's" is based on a design by
  [julieheldlaw](https://scratch.mit.edu/users/julieheldlaw/).
- Level "Pills" was inspired by Namco's
  [Pac-Man](https://en.wikipedia.org/wiki/Pac-Man).

Sound effects:
[Cute Magic Sounds.mp3](http://www.freesound.org/people/LittleRainySeasons/sounds/368323/)
by
[LittleRainySeasons](http://www.freesound.org/people/LittleRainySeasons/).
Licensed under the
[Creative Commons 0 License](http://creativecommons.org/publicdomain/zero/1.0/).

I found inspiration for the basic game concept in:

- designing levels for
  [Switches](https://scratch.mit.edu/projects/33587070/),
  a puzzle game by
  [archimedes496](https://scratch.mit.edu/users/archimedes496/)
- playing various platform games on Scratch
- watching a TV commercial for
  [Splatoon](https://en.wikipedia.org/wiki/Splatoon)
- memories of playing
  [Marble Madness](https://en.wikipedia.org/wiki/Marble_Madness)
- my obsession to get maximum value out of a minimum of code
- walking the dog at night


text:
#ifndef _RTPP_COMMAND_COPY_H_
#define _RTPP_COMMAND_COPY_H_

struct rtpp_session;

int handle_copy(const struct rtpp_cfg *, struct rtpp_session *, int, char *,
  int);

#define RSF_MODE_DFLT(cfsp) (((cfsp)->record_pcap == 0) ? 0 : 1)

#endif


text:
function [cRefractionD, emmetropes, myopes, group] = wvfSortSubjectDataJaekenArtal2012(varargin)
% Sort subjects of Jaeken/Artal report into emmotropes and myopes
%
% Syntax:
%    [centralRefraction, emmetropes, myopes, group] = wvfSortSubjectDataJaekenArtal2012()
%
% Description:
%    Analyze the central 5 degrees of individual Subject defocus zernike
%    coefficient for a given eye (mean central refraction, or Mc, in diopters) to sort
%    Subjects as emmetrope (Mc between -0.75D and 1.0D) or myope (<
%    -0.75D). Hyperopic Subjects (Mc > 1.0D) are excluded (3 in total).
%    Pupil size was 4 mm in diameter.
%
%    Data are reported as Table 1 in the published article:
%    Jaeken, B. & Artal, P. (2012) Optical Quality of Emmetropic and Myopic
%    Eyes in the Periphery Measured with High-Angular Resolution. Investigative
%    Ophthalmology & Visual Science, June 2012, Vol. 53, No. 7
%
%       In Table 1, there are 6 groups + general Emmetrope versus Myope.
%           Group 1: Mc > 0.51 D
%           Group 2: 0.5 D > Mc > -0.49 D
%           Group 3: -0.5 D > Mc > -1.49 D
%           Group 4: -1.5 D > Mc > -2.49 D
%           Group 5: -2.5 D > Mc > -3.49 D
%           Group 6: Mc < -3.5 D
%
%    For information on Zernike coefficient and their names:
%    http://www.telescope-optics.net/monochromatic_eye_aberrations.htm

%    Table of names
%    =================================
%      j   name
%
%      0  'piston'
%      1  'vertical_tilt'
%      2  'horizontal_tilt'
%      3  'oblique_astigmatism'
%      4  'defocus'
%      5  'vertical_astigmatism'
%      6  'vertical_trefoil'
%      7  'vertical_coma'
%      8  'horizontal_coma'
%      9  'oblique_trefoil'
%      10 'oblique_quadrafoil'
%      11 'oblique_secondary_astigmatism'
%      12 'primary_spherical', 'spherical'
%      13 'vertical_secondary_astigmatism'
%      14 'vertical_quadrafoil'
%
% Inputs:
%    None.
%
% Outputs:
%    centralRefraction      - mean central refraction (Subjects x eyes x central 5 degrees eccen) (in
%                             diopters)
%    emmetropes             - struct with 2 fields, corresponding to indexing vectors (130 Subjects, RE;LE]), with a 1 for emmetropes
%    myopes                 - struct with 2 fields, corresponding to indexing vectors (130 Subjects, RE;LE]), with a 1 for myopes
%    group                  - struct with 6 fields, corresponding to indexing vectors (130 Subjects, RE;LE), for each refraction group in
%                             Table 1 of Jaeken & Artal (2012)
%
% Optional key/value pairs:
%    'verbose'              - Boolean (default false). Control whether plot
%                             and printout show up.
%
% Example as are provided in the source code.
%
% See also wvfLoadJaekenArtal2012Data

% History:
%  05/03/2018 EK (NYU)   First version.
%  05/05/18   dhb        Cosmetic. Sub in wvfDefocusMicronsForDiopters for
%                        Eline's version.
%  05/05/18   dhb        Add 'verbose' key/value pair, and use it.

% Examples:
%{
    [centralRefraction, emmetropes, myopes, group] = wvfSortSubjectDataJaekenArtal2012;
%}

%% Parse
p = inputParser;
p.addOptional('verbose',false,@islogical);
p.parse(varargin{:});

%% 1. Load data from ISETBIO database
data = rawDataReadData('zCoefsJaekenArtal2012','datatype','isetbiomatfileonpath');
data = data.data;

%% 2. Define parameters to reshape and analyze dataset
totalZCoefs         = length(0:14);             % total number of zernike coefficients
totalSubjects       = 130;                      % total number of Subjects
totalEyes           = length({'right','left'}); % total number of eyes (used in this order, in the dataset, also known as OD - Oculus Dexter and OS - Oculus Sinister)
totalEccen          = length(-40:1:40);         % total number of measured central eccentricities (in degrees, 0 corresponds to fovea)

eccen               = -2:2;                     % Central 5 degrees, fovea =0
j                   = 4;                        % Defocus coefficient equals J=4
pupilDiameterMM     = 4;                        % Pupil diameter in mm during measurement

cmap                = jet(6);                   % Article defines Subject data into 6 groups, colors are used below to mark the boundaries of these groups

% define thresholds for grouping Subjects:
threshEM            = -0.75;                    % Threshold (Diopters) that defines the cut off between Emmetropes (> -0.75) and Myopes (< -0.75)
thresh1             = [0.51 1];                 % Threshold (Diopters) that defines Group 1
thresh2             = [-0.49 0.5];              % Threshold (Diopters) that defines Group 2
thresh3             = [-1.49 -0.5];             % Threshold (Diopters) that defines Group 3
thresh4             = [-2.49 -1.5];             % Threshold (Diopters) that defines Group 4
thresh5             = [-3.49 -2.5];             % Threshold (Diopters) that defines Group 5
thresh6             = [-3.5 -6.5];              % Threshold (Diopters) that defines Group 6

%% 3. Truncate headers and reshape data
data = data(2:end,4:end);
data = reshape(data, totalZCoefs, totalSubjects, totalEyes, totalEccen); % zernike x subject x eye x eccentricity

%% 4. Analyze dataset
thisZCoef       = wvfOSAIndexToVectorIndex(j);      % since j index (OSA) starts from 0, and Matlab doesn't, we convert to vector index
eccenIdx        = ismember(-40:1:40, eccen);  % eccentricity indices

% Get subset of data corresponding to central 5 degrees, only defocus
cRefractionZ    = data(thisZCoef, :, :, eccenIdx);

% Convert zernike coefficients (um) to diopters. In the dataset the
% convention of negative numbers are used, so we multiply by -1
cRefractionD    = -1*wvfDefocusMicronsToDiopters(squeeze(cRefractionZ), pupilDiameterMM);

% exclude hyperopic Subjects (spherical refraction larger than 1D):
hyperopic       = any(nanmean(cRefractionD,3)>1.0,2); % should be Subjects [33, 44, 86];
cRefractionD(hyperopic,:,:) = NaN;

% Calculate the mean of the central five degrees for each eye
mcRE = nanmean(cRefractionD(:,1,:),3);
mcLE = nanmean(cRefractionD(:,2,:),3);

%% Visualize mean refraction per eye, with 6 groups as background colors
if (p.Results.verbose)
    vcNewGraphWin([],'wide'); clf; hold all
    fill([1,totalSubjects, totalSubjects, 1],[thresh1(1),  thresh1(1), thresh1(2), thresh1(2)], cmap(1,:));
    fill([1,totalSubjects, totalSubjects, 1],[thresh2(1),  thresh2(1), thresh2(2), thresh2(2)], cmap(2,:));
    fill([1,totalSubjects, totalSubjects, 1],[thresh3(1),  thresh3(1), thresh3(2), thresh3(2)], cmap(3,:));
    fill([1,totalSubjects, totalSubjects, 1],[thresh4(1),  thresh4(1), thresh4(2), thresh4(2)], cmap(4,:));
    fill([1,totalSubjects, totalSubjects, 1],[thresh5(1),  thresh5(1), thresh5(2), thresh5(2)], cmap(5,:));
    fill([1,totalSubjects, totalSubjects, 1],[thresh6(1),  thresh6(1), thresh6(2), thresh6(2)], cmap(6,:));

    % Plot the data per eye
    plot(1:totalSubjects, mcRE', 'r-o','LineWidth',3);
    plot(1:totalSubjects, mcLE', 'k:o','LineWidth',3);

    % Plot x = 0 line
    plot(1:totalSubjects, zeros(1,totalSubjects), 'k', 'LineWidth',2);

    % Plot Myope versus Emmetrope threhold
    plot(1:totalSubjects, threshEM*ones(1,totalSubjects), 'k--','LineWidth',2);

    % Label axes and legend
    xlabel('Subject nr');
    ylabel('Mean central refraction (Diopters)')
    set(gca,'FontSize',20,'TickDir', 'out','TickLength', [0.015 0.015]);
    title('Jaeken & Artal (2012) subject division into refractive groups')
    h = findobj(gca);
    legend(h(end:-1:2),{'GR1', 'GR2', 'GR3', 'GR4', 'GR5', 'GR6', ...
        'Right eye (OD)', 'Left eye (OS)', ...
        '0', 'Emmetrope/Myope Threshold'}, ...
        'Location','bestoutside'); legend boxoff

    axis([1 totalSubjects, thresh6(2) thresh1(2)]);
end

% Find indices for Myopes and Emmetropes
myopes.RE = find(mcRE < threshEM);
myopes.LE = find(mcLE < threshEM);

emmetropes.RE = find(mcRE >= threshEM);
emmetropes.LE = find(mcLE >= threshEM);

% Find indices for separate groups
group(1).RE = find(mcRE > thresh1(1));
group(1).LE = find(mcLE > thresh1(1));

group(2).RE = find((mcRE <= thresh2(2)) & (mcRE > thresh2(1)));
group(2).LE = find((mcLE  <= thresh2(2)) & (mcLE > thresh2(1)));

group(3).RE = find((mcRE <= thresh3(2)) & (mcRE > thresh3(1)));
group(3).LE = find((mcLE  <= thresh3(2)) & (mcLE > thresh3(1)));

group(4).RE = find((mcRE <= thresh4(2)) & (mcRE > thresh4(1)));
group(4).LE = find((mcLE  <= thresh4(2)) & (mcLE > thresh4(1)));

group(5).RE = find((mcRE <= thresh5(2)) & (mcRE > thresh5(1)));
group(5).LE = find((mcLE  <= thresh5(2)) & (mcLE > thresh5(1)));

group(6).RE = find(mcRE  < thresh6(1));
group(6).LE = find(mcLE   < thresh6(1));

% Print out the group statistics mean +/- std, (#)
if (p.Results.verbose)
    fprintf('\nReproduction of Table 1 Jaeken & Artal (2012):\n')
    fprintf('Mc(diopters) Myopes RE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcRE(myopes.RE)), nanstd(mcRE(myopes.RE)), length(myopes.RE))
    fprintf('Mc(diopters) Myopes LE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcLE(myopes.LE)), nanstd(mcLE(myopes.LE)), length(myopes.LE))

    fprintf('Mc(diopters) Emmetropes RE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcRE(emmetropes.RE)),nanstd(mcRE(emmetropes.RE)), length(emmetropes.LE))
    fprintf('Mc(diopters) Emmetropes LE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcLE(emmetropes.LE)),nanstd(mcLE(emmetropes.LE)), length(emmetropes.LE))

    rd = randperm(length(emmetropes.LE),length(myopes.RE));

    fprintf('Mc(diopters) Random selection of Emmetropes RE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcRE(emmetropes.LE(rd))),nanstd(mcRE(emmetropes.LE(rd))), length(emmetropes.LE(rd)))
    fprintf('Mc(diopters) Random selection of Emmetropes LE: %1.2f +/- %1.2f, (%d)\n', nanmean(mcLE(emmetropes.LE(rd))),nanstd(mcLE(emmetropes.LE(rd))), length(emmetropes.LE(rd)))

    for ii = 1:6
        fprintf('Mc(diopters) GR%d RE: %1.2f +/- %1.2f, (%d)\n', ii, nanmean(mcRE(group(ii).RE)), nanstd(mcRE(group(ii).RE)), length(group(ii).LE))
        fprintf('Mc(diopters) GR%d LE: %1.2f +/- %1.2f, (%d)\n', ii, nanmean(mcLE(group(ii).LE)), nanstd(mcLE(group(ii).LE)), length(group(ii).LE))
    end

    fprintf('Number of emmetropes: %d\n', length(unique([emmetropes.RE;emmetropes.LE])))
    fprintf('Number of myopes: %d\n', length(unique([myopes.RE;myopes.LE])))
end

return


text:
<?php

namespace MikeRoetgers\DataMapper;

class EntityAutoMapperTest extends \PHPUnit_Framework_TestCase
{
    public function testAutoGet()
    {
        $entity = new TestEntity();
        $entity->setId('1');

        $mapper = new EntityAutoMapper();
        $id = $mapper->autoGet('id', $entity);
        $this->assertEquals(1, $id);
    }

    public function testAutoGetException()
    {
        $this->setExpectedException('Exception');
        $entity = new \stdClass();

        $mapper = new EntityAutoMapper();
        $mapper->autoGet('test', $entity, true);
    }

    public function testAutoSet()
    {
        $entity = new TestEntity();

        $mapper = new EntityAutoMapper();
        $mapper->autoSet('id', 1, $entity);

        $this->assertAttributeEquals(1, 'id', $entity);
    }

    public function testAutoSetException()
    {
        $this->setExpectedException('Exception');
        $entity = new \stdClass();

        $mapper = new EntityAutoMapper();
        $mapper->autoSet('test', 'value', $entity, true);
    }
}


text:
@tableofcontents

@prev_tutorial{tutorial_dnn_googlenet}
@next_tutorial{tutorial_dnn_halide_scheduling}

|    |    |
| -: | :- |
| Original author | Dmitry Kurtaev |
| Compatibility | OpenCV >= 3.3 |

## Introduction
This tutorial guidelines how to run your models in OpenCV deep learning module
using Halide language backend. Halide is an open-source project that let us
write image processing algorithms in well-readable format, schedule computations
according to specific device and evaluate it with a quite good efficiency.

An official website of the Halide project: http://halide-lang.org/.

An up to date efficiency comparison: https://github.com/opencv/opencv/wiki/DNN-Efficiency

## Requirements
### LLVM compiler

@note LLVM compilation might take a long time.

- Download LLVM source code from http://releases.llvm.org/4.0.0/llvm-4.0.0.src.tar.xz.
Unpack it. Let **llvm_root** is a root directory of source code.

- Create directory **llvm_root**/tools/clang

- Download Clang with the same version as LLVM. In our case it will be from
http://releases.llvm.org/4.0.0/cfe-4.0.0.src.tar.xz. Unpack it into
**llvm_root**/tools/clang. Note that it should be a root for Clang source code.

- Build LLVM on Linux
@code
cd llvm_root
mkdir build && cd build
cmake -DLLVM_ENABLE_TERMINFO=OFF -DLLVM_TARGETS_TO_BUILD="X86" -DLLVM_ENABLE_ASSERTIONS=ON -DCMAKE_BUILD_TYPE=Release ..
make -j4
@endcode

- Build LLVM on Windows (Developer Command Prompt)
@code
mkdir \\path-to-llvm-build\\ && cd \\path-to-llvm-build\\
cmake.exe -DLLVM_ENABLE_TERMINFO=OFF -DLLVM_TARGETS_TO_BUILD=X86 -DLLVM_ENABLE_ASSERTIONS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=\\path-to-llvm-install\\ -G "Visual Studio 14 Win64" \\path-to-llvm-src\\
MSBuild.exe /m:4 /t:Build /p:Configuration=Release .\\INSTALL.vcxproj
@endcode

@note `\\path-to-llvm-build\\` and `\\path-to-llvm-install\\` are different directories.

### Halide language.

- Download source code from GitHub repository, https://github.com/halide/Halide
or using git. The root directory will be a **halide_root**.
@code
git clone https://github.com/halide/Halide.git
@endcode

- Build Halide on Linux
@code
cd halide_root
mkdir build && cd build
cmake -DLLVM_DIR=llvm_root/build/lib/cmake/llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_VERSION=40 -DWITH_TESTS=OFF -DWITH_APPS=OFF -DWITH_TUTORIALS=OFF ..
make -j4
@endcode

- Build Halide on Windows (Developer Command Prompt)
@code
cd halide_root
mkdir build && cd build
cmake.exe -DLLVM_DIR=\\path-to-llvm-install\\lib\\cmake\\llvm -DLLVM_VERSION=40 -DWITH_TESTS=OFF -DWITH_APPS=OFF -DWITH_TUTORIALS=OFF -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 14 Win64" ..
MSBuild.exe /m:4 /t:Build /p:Configuration=Release .\\ALL_BUILD.vcxproj
@endcode

## Build OpenCV with Halide backend
When you build OpenCV add the following configuration flags:

- `WITH_HALIDE` - enable Halide linkage

- `HALIDE_ROOT_DIR` - path to Halide build directory

## Set Halide as a preferable backend
@code
net.setPreferableBackend(DNN_BACKEND_HALIDE);
@endcode


text:
package org.maera.plugin.webresource;

import java.util.Collections;
import java.util.List;

/**
 * Default configuration for the plugin resource locator, for those applications that do not want to perform
 * any super-batching.
 */
public class DefaultResourceBatchingConfiguration implements ResourceBatchingConfiguration {
    public boolean isSuperBatchingEnabled() {
        return false;
    }

    public List<String> getSuperBatchModuleCompleteKeys() {
        return Collections.emptyList();
    }
}


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

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@class FPRMSGPerfMetric;

/** Logger used to dispatch events to Google Data Transport layer. */
@interface FPRGDTLogger : NSObject

/** Log source initialized against. */
@property(nonatomic, readonly) NSInteger logSource;

/** Default initializer. */
- (instancetype)init NS_UNAVAILABLE;

/**
 * Instantiates an instance of this class.
 *
 * @param logSource The log source for this logger to be used.
 * @return Instance of FPRGDTLogger.
 */
- (instancetype)initWithLogSource:(NSInteger)logSource NS_DESIGNATED_INITIALIZER;

/**
 * Logs an event that needs to be dispatched.
 *
 * @remark Events are logged/dispatched asynchrounously using a serial dispatch queue.
 * @param event The event to log.
 */
- (void)logEvent:(FPRMSGPerfMetric *)event;

@end

NS_ASSUME_NONNULL_END


text:
const RETURN_URL_PATH = 'moderator/return-url';

export interface IReturnURL {
  pathname: string;
  query?: {
    [key: string]: string;
  };
}

export function getReturnURL(): IReturnURL {
  const data = sessionStorage[RETURN_URL_PATH];

  if (data) {
    return JSON.parse(data);
  }
}

export function setReturnURL(data: IReturnURL): void {
  sessionStorage[RETURN_URL_PATH] = JSON.stringify(data);
}

export function clearReturnURL(): void {
  delete sessionStorage[RETURN_URL_PATH];
}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Categoria extends Model
{
  public $timestamps = false;
  protected $table = 'categoria';
  protected $fillable = ['nombre','descripcion'];
  protected $primaryKey = 'idCategoria';

  /**
  * The roles that belong to the user.
  */
  public function proveedoresSituacion()
  {
    return $this->belongsToMany('App\Proveedor', 'situacionProveedor', 'idCategoria', 'idProveedor')->withPivot('situacion','precio');
  }

  /**
  * The roles that belong to the user.
  */
  public function proveedoresEtiquetado()
  {
    return $this->belongsToMany('App\Proveedor', 'etiquetado', 'Categoria_idCategoria', 'Proveedor_idProveedor');
  }

  /**
  * Get the post that owns the comment.
  */
  public function evento()
  {
    return $this->belongsTo('App\Evento');
  }

  public function misProveedoresCarrito($idCategoria){
    $proveedores = Proveedor::whereHas('categoriasSituacion', function ($query) use($idCategoria) {
    $query->where('situacionProveedor.idCategoria',$idCategoria);
    $query->where('situacion','CARRITO_COMPRAS');
    })->get();
    return $proveedores;
  }

  public static function misProveedores($idCategoria){
    $proveedores = Proveedor::whereHas('categoriasSituacion', function ($query) use($idCategoria) {
    $query->where('situacionProveedor.idCategoria',$idCategoria);
    $query->where('situacion','COTIZACION');
    })->get();
    return $proveedores;
  }

  public static function proveedores($idCategoria){
    $proveedores = Proveedor::whereHas('categoriasEtiquetado', function ($query) use($idCategoria) {
    $query->where('etiquetado.Categoria_idCategoria',$idCategoria);
    })->get();
    return $proveedores;
  }

  public static function eliminarSituacion($idCategoria,$idProveedor){
    DB::table('situacionProveedor')->where('idCategoria',$idCategoria)->where('idProveedor',$idProveedor)->delete();
  }
}


text:
namespace content {

DownloadCreateInfo::DownloadCreateInfo(const base::Time& start_time,
                                       int64_t total_bytes,
                                       const net::BoundNetLog& bound_net_log,
                                       scoped_ptr<DownloadSaveInfo> save_info)
    : start_time(start_time),
      total_bytes(total_bytes),
      download_id(DownloadItem::kInvalidId),
      has_user_gesture(false),
      transition_type(ui::PAGE_TRANSITION_LINK),
      save_info(std::move(save_info)),
      request_bound_net_log(bound_net_log) {}

DownloadCreateInfo::DownloadCreateInfo()
    : DownloadCreateInfo(base::Time(),
                         0,
                         net::BoundNetLog(),
                         make_scoped_ptr(new DownloadSaveInfo)) {}

DownloadCreateInfo::~DownloadCreateInfo() {}

std::string DownloadCreateInfo::DebugString() const {
  return base::StringPrintf(
      "{"
      " download_id = %u"
      " url = \"%s\""
      " request_handle = %s"
      " total_bytes = %" PRId64 " }",
      download_id, url().spec().c_str(), request_handle->DebugString().c_str(),
      total_bytes);
}

const GURL& DownloadCreateInfo::url() const {
  return url_chain.empty() ? GURL::EmptyGURL() : url_chain.back();
}

}  // namespace content


text:
proof_of_reserves
=================

proof of reserves


text:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SyntaxString {
	private char left = '(';
	private char right = ')';
	public String syntaxTree = "";
	public String gornAddress = "";

	private boolean checkIfParenthesesAreBalanced() {
		int parenthesesCount = 0;
		boolean initialLeftParenthesisFlag = false;
		boolean unbalancedFlag = false;
		for(int i = 0; i < syntaxTree.length(); i++) {
			if(parenthesesCount < 0){
				unbalancedFlag = true;
				break;
			}
			else if(syntaxTree.charAt(i) == left){
				parenthesesCount++;
				initialLeftParenthesisFlag = true;
			}
			else if(syntaxTree.charAt(i) == right) {
				parenthesesCount--;
			}
		}
		if(unbalancedFlag == true || initialLeftParenthesisFlag == false || parenthesesCount != 0) {
			return false;
		}
		else {
			return true;
		}
	}

	private String findGornAddressNonRecursive() {
		String subTree = syntaxTree;
		String[] splitGornAddress = gornAddress.split("\\.");
		int[] intSplitGornAddress = new int[splitGornAddress.length];
		for(int i = 0; i < splitGornAddress.length; i++) {
			intSplitGornAddress[i] = Integer.parseInt(splitGornAddress[i]);
		}

		String returnValue = "";
		String result = "";

		int balance = 0;
		int matches = 0;
		int addressCounter = 0;

		boolean firstParenthesisTag = false;

		for(int i = 0; i < intSplitGornAddress.length; i++) {
			int node = intSplitGornAddress[i];
			firstParenthesisTag = false;
			matches = 0;
			balance = 0;
			result = "";

			for(int j = 0; j < subTree.length(); j++){
				char syntaxChar = subTree.charAt(j);
				if(syntaxChar == left) {
					balance++;
				}
				else if(syntaxChar == right) {
					balance--;
				}
				if(syntaxChar == left) {
					firstParenthesisTag = true;
				}
				if (matches == node && firstParenthesisTag == true) {
					result = new StringBuilder(result).append(syntaxChar).toString();
					//System.out.println(result);
				}
				if(firstParenthesisTag == true && balance == 0 && syntaxChar == right) {
					if (matches == node) {
						subTree = result;

						subTree = subTree.replaceAll("^\\s+", "");
						subTree = subTree.replaceAll("\\s+$", "");
						subTree = subTree.replaceAll("^\\(|\\)$", "");

						break;
					}
					matches++;
				}
			}

			addressCounter++;
			if (addressCounter == intSplitGornAddress.length) {
				returnValue = subTree;
			}
		}
		return returnValue;
	}

	public static String[] readlines(String filename) throws IOException {
		FileReader fileReader = new FileReader(filename);
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		List<String> lines = new ArrayList<String>();
		String line = null;
		while((line = bufferedReader.readLine()) != null) {
			lines.add(line);
		}
		bufferedReader.close();
		return lines.toArray(new String[lines.size()]);
	}

	public static void main(String[] args) {
		SyntaxString syntaxString = new SyntaxString();

		try {
			String[] fileContents = SyntaxString.readlines(args[0]);
			for (int i = 0; i < fileContents.length; i+=3) {
				syntaxString.syntaxTree = fileContents[i];
				syntaxString.gornAddress = fileContents[i+1];

				boolean parenthesesAreBalanced = syntaxString.checkIfParenthesesAreBalanced();
				if (parenthesesAreBalanced == false) {
					System.out.println("The parentheses are not balanced in : " + fileContents[i]);
				}

				String gornResult = syntaxString.findGornAddressNonRecursive();
				System.out.println(gornResult);
				System.out.println(fileContents[i+2]);
			}
		} catch (IOException e){
			System.err.println("Caught IOException: " + e.getMessage());
		}
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Canthium salubenii Bridson

### Remarks
null


text:
This project would not have been possible without these dependencies:

- [ircmaxell/php-cfg](https://github.com/ircmaxell/php-cfg/)
- [nikic/php-parser](https://github.com/nikic/php-parser/)

## Tests

More than 2400 tests cases from [PHP Vulnerability test suite](https://github.com/stivalet/PHP-Vulnerability-test-suite) are used to test progpilot.
To run the tests suite go to [./projects/tests](../projects/tests/) folder and execute [phpunit](https://phpunit.de/).

## License

Progpilot is licensed under the [MIT License](../LICENSE)

## Authors

- Eric Therond | [github](https://github.com/eric-therond/) | [website](https://www.designsecurity.org) | [eric.therond.fr@gmail.com](mailto:eric.therond.fr@gmail.com)

See also the list of [contributors](https://github.com/designsecurity/progpilot/contributors) who participated in this project.

## Contribute

If you want to contribute to this project see [the contributing rules](./CONTRIBUTING.md).

## Roadmap

There is a lot of tasks to do:
- Passing by reference
- Pushing elements into array (like array[] = ele; or push_array())
- Property of an object is an object
- definitions on the same line (def = eee; def = aaa;)
- If property hasn't been declared but used later (class { miss public $property;})
- Chained functions calls : $obj->func1()->func2()
- Chained references  : $var = "eee"; $ref1 = &$var; $ref2 = &$ref1;
- Sprintf strings transformations
- $tainted = $tainted + 0; => cast to int
- Handle all tainted flows when severals definitions taint the same expression


text:
using System;
using BooksQL.API.GraphQL.Types;
using BooksQL.API.Repositories;
using GraphQL.Types;

namespace BooksQL.API.GraphQL
{
    public class BooksQuery : ObjectGraphType
    {
        public BooksQuery(BooksRepository booksRepository)
        {
            Field<ListGraphType<BookType>>(
                "books",
                resolve: context => booksRepository.GetBooks()
            );

            Field<BookType>(
                "book",
                arguments: new QueryArguments(new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "iSBN" }),
                resolve: context =>
                {
                    var isbn = context.GetArgument<string>("iSBN");
                    return booksRepository.GetBook(isbn);
                }
            );
        }
    }
}


text:
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20150326
//----------------------------------------------------

package org.eclipse.php.internal.core.compiler.ast.parser.php5;

/** CUP generated interface containing symbol constants. */
public interface CompilerParserConstants {
  /* terminals */
  public static final int T_BOOLEAN_AND = 94;
  public static final int T_INLINE_HTML = 10;
  public static final int T_EMPTY = 45;
  public static final int T_PROTECTED = 136;
  public static final int T_CLOSE_RECT = 127;
  public static final int T_IS_NOT_EQUAL = 99;
  public static final int T_INCLUDE = 69;
  public static final int T_OPEN_TAG_WITH_ECHO = 14;
  public static final int T_QUATE = 142;
  public static final int T_GLOBAL = 41;
  public static final int T_PRINT = 78;
  public static final int T_OR_EQUAL = 87;
  public static final int T_LOGICAL_XOR = 76;
  public static final int T_FUNCTION = 34;
  public static final int T_STATIC = 132;
  public static final int T_NEKUDA = 115;
  public static final int T_THROW = 39;
  public static final int T_CLASS = 47;
  public static final int T_ABSTRACT = 133;
  public static final int T_ENCAPSED_AND_WHITESPACE = 12;
  public static final int T_MOD_EQUAL = 85;
  public static final int T_BREAK = 32;
  public static final int T_WHILE = 17;
  public static final int T_DO = 16;
  public static final int T_CONST = 35;
  public static final int T_CONTINUE = 33;
  public static final int T_FUNC_C = 57;
  public static final int T_DIV = 111;
  public static final int T_LOGICAL_OR = 75;
  public static final int T_OPEN_PARENTHESE = 138;
  public static final int T_REFERENCE = 97;
  public static final int T_COMMA = 74;
  public static final int T_ELSE = 131;
  public static final int T_IS_EQUAL = 98;
  public static final int T_LIST = 53;
  public static final int T_OR = 95;
  public static final int T_IS_IDENTICAL = 100;
  public static final int T_INC = 116;
  public static final int T_ELSEIF = 130;
  public static final int T_TRY = 37;
  public static final int T_PRIVATE = 135;
  public static final int T_UNSET_CAST = 124;
  public static final int T_INCLUDE_ONCE = 70;
  public static final int T_ENDIF = 129;
  public static final int T_SR_EQUAL = 90;
  public static final int EOF = 0;
  public static final int T_PUBLIC = 137;
  public static final int T_OBJECT_OPERATOR = 51;
  public static final int T_TILDA = 114;
  public static final int T_PAAMAYIM_NEKUDOTAYIM = 66;
  public static final int T_IS_SMALLER_OR_EQUAL = 102;
  public static final int T_XOR_EQUAL = 88;
  public static final int T_ENDFOREACH = 22;
  public static final int T_CONSTANT_ENCAPSED_STRING = 13;
  public static final int T_BACKQUATE = 143;
  public static final int T_AT = 125;
  public static final int T_AS = 27;
  public static final int T_CURLY_CLOSE = 65;
  public static final int T_ENDDECLARE = 24;
  public static final int T_CATCH = 38;
  public static final int T_CASE = 30;
  public static final int T_VARIABLE = 8;
  public static final int T_NEW = 128;
  public static final int T_MINUS_EQUAL = 81;
  public static final int T_PLUS = 108;
  public static final int T_SL_EQUAL = 89;
  public static final int T_ENDWHILE = 18;
  public static final int T_ENDFOR = 20;
  public static final int T_CLONE = 26;
  public static final int T_BOOLEAN_OR = 93;
  public static final int T_UNSET = 43;
  public static final int T_INTERFACE = 48;
  public static final int T_SWITCH = 28;
  public static final int T_IS_GREATER_OR_EQUAL = 103;
  public static final int T_OPEN_RECT = 126;
  public static final int T_CURLY_OPEN_WITH_DOLAR = 63;
  public static final int T_FINAL = 134;
  public static final int T_REQUIRE = 72;
  public static final int T_FILE = 59;
  public static final int T_DEC = 117;
  public static final int T_CLOSE_PARENTHESE = 139;
  public static final int T_CLASS_C = 55;
  public static final int T_EVAL = 71;
  public static final int T_RGREATER = 104;
  public static final int T_IS_NOT_IDENTICAL = 101;
  public static final int T_NOT = 113;
  public static final int T_REQUIRE_ONCE = 73;
  public static final int T_DOLLAR_OPEN_CURLY_BRACES = 62;
  public static final int T_VAR = 42;
  public static final int T_START_HEREDOC = 60;
  public static final int T_ENDSWITCH = 29;
  public static final int T_OBJECT_CAST = 122;
  public static final int T_ECHO = 15;
  public static final int T_LINE = 58;
  public static final int T_FOR = 19;
  public static final int T_IMPLEMENTS = 50;
  public static final int T_ARRAY_CAST = 121;
  public static final int T_CHARACTER = 11;
  public static final int T_TIMES = 110;
  public static final int T_DOLLAR = 141;
  public static final int T_DOUBLE_CAST = 119;
  public static final int T_BOOL_CAST = 123;
  public static final int T_PRECENT = 112;
  public static final int T_LNUMBER = 4;
  public static final int T_CURLY_OPEN = 64;
  public static final int T_DEFINE = 68;
  public static final int T_QUESTION_MARK = 91;
  public static final int T_USE = 40;
  public static final int T_KOVA = 96;
  public static final int T_IF = 3;
  public static final int T_MUL_EQUAL = 82;
  public static final int T_ARRAY = 54;
  public static final int T_LGREATER = 105;
  public static final int T_SEMICOLON = 92;
  public static final int T_NEKUDOTAIM = 140;
  public static final int T_VAR_COMMENT = 67;
  public static final int T_CONCAT_EQUAL = 84;
  public static final int T_SINGLE_QUATE = 144;
  public static final int T_AND_EQUAL = 86;
  public static final int T_DNUMBER = 5;
  public static final int T_MINUS = 109;
  public static final int T_FOREACH = 21;
  public static final int T_EXIT = 2;
  public static final int T_DECLARE = 23;
  public static final int T_STRING_VARNAME = 7;
  public static final int T_EXTENDS = 49;
  public static final int T_METHOD_C = 56;
  public static final int T_INT_CAST = 118;
  public static final int T_ISSET = 44;
  public static final int T_LOGICAL_AND = 77;
  public static final int error = 1;
  public static final int T_RETURN = 36;
  public static final int T_DEFAULT = 31;
  public static final int T_SR = 107;
  public static final int T_EQUAL = 79;
  public static final int T_SL = 106;
  public static final int T_END_HEREDOC = 61;
  public static final int T_DOUBLE_ARROW = 52;
  public static final int T_STRING_CAST = 120;
  public static final int T_STRING = 6;
  public static final int T_PLUS_EQUAL = 80;
  public static final int T_INSTANCEOF = 25;
  public static final int T_DIV_EQUAL = 83;
  public static final int T_NUM_STRING = 9;
  public static final int T_HALT_COMPILER = 46;
  public static final String[] terminalNames = new String[] {
  "EOF",
  "error",
  "T_EXIT",
  "T_IF",
  "T_LNUMBER",
  "T_DNUMBER",
  "T_STRING",
  "T_STRING_VARNAME",
  "T_VARIABLE",
  "T_NUM_STRING",
  "T_INLINE_HTML",
  "T_CHARACTER",
  "T_ENCAPSED_AND_WHITESPACE",
  "T_CONSTANT_ENCAPSED_STRING",
  "T_OPEN_TAG_WITH_ECHO",
  "T_ECHO",
  "T_DO",
  "T_WHILE",
  "T_ENDWHILE",
  "T_FOR",
  "T_ENDFOR",
  "T_FOREACH",
  "T_ENDFOREACH",
  "T_DECLARE",
  "T_ENDDECLARE",
  "T_INSTANCEOF",
  "T_CLONE",
  "T_AS",
  "T_SWITCH",
  "T_ENDSWITCH",
  "T_CASE",
  "T_DEFAULT",
  "T_BREAK",
  "T_CONTINUE",
  "T_FUNCTION",
  "T_CONST",
  "T_RETURN",
  "T_TRY",
  "T_CATCH",
  "T_THROW",
  "T_USE",
  "T_GLOBAL",
  "T_VAR",
  "T_UNSET",
  "T_ISSET",
  "T_EMPTY",
  "T_HALT_COMPILER",
  "T_CLASS",
  "T_INTERFACE",
  "T_EXTENDS",
  "T_IMPLEMENTS",
  "T_OBJECT_OPERATOR",
  "T_DOUBLE_ARROW",
  "T_LIST",
  "T_ARRAY",
  "T_CLASS_C",
  "T_METHOD_C",
  "T_FUNC_C",
  "T_LINE",
  "T_FILE",
  "T_START_HEREDOC",
  "T_END_HEREDOC",
  "T_DOLLAR_OPEN_CURLY_BRACES",
  "T_CURLY_OPEN_WITH_DOLAR",
  "T_CURLY_OPEN",
  "T_CURLY_CLOSE",
  "T_PAAMAYIM_NEKUDOTAYIM",
  "T_VAR_COMMENT",
  "T_DEFINE",
  "T_INCLUDE",
  "T_INCLUDE_ONCE",
  "T_EVAL",
  "T_REQUIRE",
  "T_REQUIRE_ONCE",
  "T_COMMA",
  "T_LOGICAL_OR",
  "T_LOGICAL_XOR",
  "T_LOGICAL_AND",
  "T_PRINT",
  "T_EQUAL",
  "T_PLUS_EQUAL",
  "T_MINUS_EQUAL",
  "T_MUL_EQUAL",
  "T_DIV_EQUAL",
  "T_CONCAT_EQUAL",
  "T_MOD_EQUAL",
  "T_AND_EQUAL",
  "T_OR_EQUAL",
  "T_XOR_EQUAL",
  "T_SL_EQUAL",
  "T_SR_EQUAL",
  "T_QUESTION_MARK",
  "T_SEMICOLON",
  "T_BOOLEAN_OR",
  "T_BOOLEAN_AND",
  "T_OR",
  "T_KOVA",
  "T_REFERENCE",
  "T_IS_EQUAL",
  "T_IS_NOT_EQUAL",
  "T_IS_IDENTICAL",
  "T_IS_NOT_IDENTICAL",
  "T_IS_SMALLER_OR_EQUAL",
  "T_IS_GREATER_OR_EQUAL",
  "T_RGREATER",
  "T_LGREATER",
  "T_SL",
  "T_SR",
  "T_PLUS",
  "T_MINUS",
  "T_TIMES",
  "T_DIV",
  "T_PRECENT",
  "T_NOT",
  "T_TILDA",
  "T_NEKUDA",
  "T_INC",
  "T_DEC",
  "T_INT_CAST",
  "T_DOUBLE_CAST",
  "T_STRING_CAST",
  "T_ARRAY_CAST",
  "T_OBJECT_CAST",
  "T_BOOL_CAST",
  "T_UNSET_CAST",
  "T_AT",
  "T_OPEN_RECT",
  "T_CLOSE_RECT",
  "T_NEW",
  "T_ENDIF",
  "T_ELSEIF",
  "T_ELSE",
  "T_STATIC",
  "T_ABSTRACT",
  "T_FINAL",
  "T_PRIVATE",
  "T_PROTECTED",
  "T_PUBLIC",
  "T_OPEN_PARENTHESE",
  "T_CLOSE_PARENTHESE",
  "T_NEKUDOTAIM",
  "T_DOLLAR",
  "T_QUATE",
  "T_BACKQUATE",
  "T_SINGLE_QUATE"
  };
}


text:
package com.cloud.network;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import com.cloud.network.rules.HealthCheckPolicy;
import org.apache.cloudstack.api.InternalIdentity;

@Entity
@Table(name = ("load_balancer_healthcheck_policies"))
@PrimaryKeyJoinColumn(name = "load_balancer_id", referencedColumnName = "id")
public class LBHealthCheckPolicyVO implements HealthCheckPolicy {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "load_balancer_id")
    private long loadBalancerId;

    @Column(name = "pingpath")
    private String pingPath;

    @Column(name = "description")
    private String description;

    @Column(name = "uuid")
    private String uuid;

    @Column(name = "response_time")
    private int responseTime;

    @Column(name = "healthcheck_interval")
    private int healthcheckInterval;

    @Column(name = "healthcheck_thresshold")
    private int healthcheckThresshold;

    @Column(name = "unhealth_thresshold")
    private int unhealthThresshold;

    @Column(name = "revoke")
    private boolean revoke = false;

    protected LBHealthCheckPolicyVO() {
        this.uuid = UUID.randomUUID().toString();
    }

    public LBHealthCheckPolicyVO(long loadBalancerId, String pingPath, String description, int responseTime,
            int healthcheckInterval, int healthcheckThresshold, int unhealthThresshold) {
        this.loadBalancerId = loadBalancerId;

        if (pingPath == null || pingPath.isEmpty())
            this.pingPath = "/";
        else
            this.pingPath = pingPath;

        if (responseTime == 0)
            this.responseTime = 2;
        else
            this.responseTime = responseTime;

        if (healthcheckInterval == 0)
            this.healthcheckInterval = 5;
        else
            this.healthcheckInterval = healthcheckInterval;

        if (healthcheckThresshold == 0)
            this.healthcheckThresshold = 2;
        else
            this.healthcheckThresshold = healthcheckThresshold;

        if (unhealthThresshold == 0)
            this.unhealthThresshold = 1;
        else
            this.unhealthThresshold = unhealthThresshold;
        this.uuid = UUID.randomUUID().toString();

    }

    public int getResponseTime() {
        return responseTime;
    }

    public int getHealthcheckInterval() {
        return healthcheckInterval;
    }

    public int getHealthcheckThresshold() {
        return healthcheckThresshold;
    }

    public int getUnhealthThresshold() {
        return unhealthThresshold;
    }

    public long getId() {
        return id;
    }

    public long getLoadBalancerId() {
        return loadBalancerId;
    }

    public String getpingpath() {
        return pingPath;
    }

    public String getDescription() {
        return description;
    }

    public boolean isRevoke() {
        return revoke;
    }

    public void setRevoke(boolean revoke) {
        this.revoke = revoke;
    }

    @Override
    public String getUuid() {
        return this.uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}


text:
package com.google.android.exoplayer2.extractor.ts;

import static com.google.android.exoplayer2.extractor.ts.TsPayloadReader.FLAG_DATA_ALIGNMENT_INDICATOR;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.extractor.ExtractorOutput;
import com.google.android.exoplayer2.extractor.TrackOutput;
import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.DvbSubtitleInfo;
import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.ParsableByteArray;
import java.util.Collections;
import java.util.List;

/** Parses DVB subtitle data and extracts individual frames. */
public final class DvbSubtitleReader implements ElementaryStreamReader {

  private final List<DvbSubtitleInfo> subtitleInfos;
  private final TrackOutput[] outputs;

  private boolean writingSample;
  private int bytesToCheck;
  private int sampleBytesWritten;
  private long sampleTimeUs;

  /** @param subtitleInfos Information about the DVB subtitles associated to the stream. */
  public DvbSubtitleReader(List<DvbSubtitleInfo> subtitleInfos) {
    this.subtitleInfos = subtitleInfos;
    outputs = new TrackOutput[subtitleInfos.size()];
    sampleTimeUs = C.TIME_UNSET;
  }

  @Override
  public void seek() {
    writingSample = false;
    sampleTimeUs = C.TIME_UNSET;
  }

  @Override
  public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
    for (int i = 0; i < outputs.length; i++) {
      DvbSubtitleInfo subtitleInfo = subtitleInfos.get(i);
      idGenerator.generateNewId();
      TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
      output.format(
          new Format.Builder()
              .setId(idGenerator.getFormatId())
              .setSampleMimeType(MimeTypes.APPLICATION_DVBSUBS)
              .setInitializationData(Collections.singletonList(subtitleInfo.initializationData))
              .setLanguage(subtitleInfo.language)
              .build());
      outputs[i] = output;
    }
  }

  @Override
  public void packetStarted(long pesTimeUs, @TsPayloadReader.Flags int flags) {
    if ((flags & FLAG_DATA_ALIGNMENT_INDICATOR) == 0) {
      return;
    }
    writingSample = true;
    if (pesTimeUs != C.TIME_UNSET) {
      sampleTimeUs = pesTimeUs;
    }
    sampleBytesWritten = 0;
    bytesToCheck = 2;
  }

  @Override
  public void packetFinished() {
    if (writingSample) {
      if (sampleTimeUs != C.TIME_UNSET) {
        for (TrackOutput output : outputs) {
          output.sampleMetadata(sampleTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleBytesWritten, 0, null);
        }
      }
      writingSample = false;
    }
  }

  @Override
  public void consume(ParsableByteArray data) {
    if (writingSample) {
      if (bytesToCheck == 2 && !checkNextByte(data, 0x20)) {
        // Failed to check data_identifier
        return;
      }
      if (bytesToCheck == 1 && !checkNextByte(data, 0x00)) {
        // Check and discard the subtitle_stream_id
        return;
      }
      int dataPosition = data.getPosition();
      int bytesAvailable = data.bytesLeft();
      for (TrackOutput output : outputs) {
        data.setPosition(dataPosition);
        output.sampleData(data, bytesAvailable);
      }
      sampleBytesWritten += bytesAvailable;
    }
  }

  private boolean checkNextByte(ParsableByteArray data, int expectedValue) {
    if (data.bytesLeft() == 0) {
      return false;
    }
    if (data.readUnsignedByte() != expectedValue) {
      writingSample = false;
    }
    bytesToCheck--;
    return writingSample;
  }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _isWindow = require("./isWindow.js");

var _isWindow2 = _interopRequireDefault(_isWindow);

var _ownerDocument = require("./ownerDocument.js");

var _ownerDocument2 = _interopRequireDefault(_ownerDocument);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function isBody(node) {
  return node && node.tagName.toLowerCase() === "body";
}

function isBodyOverflowing(node) {
  var doc = (0, _ownerDocument2.default)(node);
  var win = (0, _isWindow2.default)(doc);
  var fullWidth = win.innerWidth;

  if (!fullWidth) {
    var documentElementRect = doc.documentElement.getBoundingClientRect();
    fullWidth = documentElementRect.right - Math.abs(documentElementRect.left);
  }

  return doc.body.clientWidth < fullWidth;
}

function isOverflowing(container) {
  var win = (0, _isWindow2.default)(container);

  return win || isBody(container) ? isBodyOverflowing(container) : container.scrollHeight > container.clientHeight;
}

exports.default = isOverflowing;


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Rytigynia lebrunii Robyns

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Http
{
    /// Represents a request or response header.
    [DebuggerDisplay("Count = {Count}", Name = "{Name}")]
    [DebuggerTypeProxy(typeof(HeaderDebugView))]
    public class Header : List<string>, IHeader
    {
        /// Initializes a new instance of the <see cref="T:Http.Header" /> class with a specified header name.
        /// <param name="name">The name of the header.</param>
        public Header(string name)
            : this(name, false)
        {
        }

        ///
        /// Initializes a new instance of the <see cref="T:Http.Header" /> class with a specified header name and an
        /// additional value that indicates whether the header is required.
        ///
        /// <param name="name">The name of the header.</param>
        /// <param name="required">A value that indicates whether the header is required.</param>
        public Header(string name, bool required)
            : base(1)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Argument is null or empty", nameof(name));
            }
            Name = name;
            Required = required;
        }

        /// <inheritdoc />
        public string Name { get; }

        /// <inheritdoc />
        public bool Required { get; }

        [DebuggerDisplay("{Values}")]
        private class HeaderDebugView
        {
            private readonly Header header;

            public HeaderDebugView(Header header)
            {
                this.header = header;
            }

            [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
            public string[] Values => header.ToArray();
        }
    }
}


text:
package org.frameworkset.spi.annotations;

import java.lang.annotation.*;

/**
 *
Description: 标记业务组件,将组件发布为业务组件

 *

 *
Copyright (c) 2020

 * @Date 2020/6/26 10:29
 * @author biaoping.yin
 * @version 1.0
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BService {

	String name() default "";
	String value()default "";
}


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Should;
using Xunit;

namespace Roslyn.Samples.SanityCheck.Tests
{
    public class SolutionSanity
    {
        private readonly List<SyntaxNode> _documents;

        public SolutionSanity()
        {
            var workspace = MSBuildWorkspace.Create();
            var solution = workspace.OpenSolutionAsync(@"C:\Users\filipw\Documents\dev\roslyn-samples\SolutionSanity\Roslyn.Samples.SanityCheck.sln").Result;

            _documents = new List<SyntaxNode>();

            foreach (var projectId in solution.ProjectIds)
            {
                var project = solution.GetProject(projectId);
                foreach (var documentId in project.DocumentIds)
                {
                    var document = solution.GetDocument(documentId);
                    if (document.SupportsSyntaxTree)
                    {
                        var root = document.GetSyntaxRootAsync().Result;
                        _documents.Add(root);
                    }
                }
            }
        }

        [Fact]
        public void Interfaces_ShouldBePrefixedWithI()
        {
            var interfaces = _documents.SelectMany(x => x.DescendantNodes().OfType<InterfaceDeclarationSyntax>()).ToList();
            interfaces.All(x => x.Identifier.ToString().StartsWith("I")).ShouldBeTrue();
        }
    }
}


text:
'use strict';

// MODULES //

var iterMap = require( '@stdlib/math/iter/tools/map' );
var exp10 = require( '@stdlib/math/base/special/exp10' );

// MAIN //

/**
* Returns an iterator which iteratively evaluates the base `10` exponential function.
*
* ## Notes
*
* -   If an environment supports `Symbol.iterator` **and** a provided iterator is iterable, the returned iterator is iterable.
*
* @param {Iterator} iterator - input iterator
* @throws {TypeError} must provide an iterator protocol-compliant object
* @returns {Iterator} iterator
*
* @example
* var uniform = require( '@stdlib/random/iter/uniform' );
*
* var iter = iterExp10( uniform( -50.0, 50.0 ) );
*
* var v = iter.next().value;
* // returns <number>
*
* v = iter.next().value;
* // returns <number>
*
* v = iter.next().value;
* // returns <number>
*
* // ...
*/
function iterExp10( iterator ) {
	return iterMap( iterator, exp10 );
}

// EXPORTS //

module.exports = iterExp10;


text:
{-# LANGUAGE OverloadedStrings
  , LambdaCase
  #-}
module PrepGhcJS.Types where

import Turtle
import Data.Either

data PrepConfig = PrepConfig
 { master        :: Turtle.FilePath
 , workdir       :: Turtle.FilePath
 , checkResolver :: IO Text
 , tag           :: Text
 , copyIgnore    :: [Text]
 , copyOverride  :: [Text]
 , forceVersion  :: [(Text, Text)]
 , forceFresh    :: [(Text, Text)]
 , overwriteFiles:: [(Text, Text)]
 , ghc           :: Text
 , nameSuffix    :: Text
 , extraBlob   :: Text
 , extraBoot     :: [Text]
 , extraBuild    :: [Text]
 }

defPC = PrepConfig

fromPath :: Turtle.FilePath -> Text
fromPath = either (const "") id . toText


text:
require_relative "../resource"
require_relative "../dist"
require_relative "helpers/cron_validations"
require "digest/md5"

class Chef
  class Resource
    class ChefClientCron < Chef::Resource
      unified_mode true

      provides :chef_client_cron

      description "Use the **chef_client_cron** resource to setup the #{Chef::Dist::PRODUCT} to run as a cron job. This resource will also create the specified log directory if it doesn't already exist."
      introduced "16.0"
      examples <<~DOC
      **Setup #{Chef::Dist::PRODUCT} to run using the default 30 minute cadence**:

      ```ruby
      chef_client_cron "Run #{Chef::Dist::PRODUCT} as a cron job"
      ```

      **Run #{Chef::Dist::PRODUCT} twice a day**:

      ```ruby
      chef_client_cron "Run #{Chef::Dist::PRODUCT} every 12 hours" do
        minute 0
        hour "0,12"
      end
      ```

      **Run #{Chef::Dist::PRODUCT} with extra options passed to the client**:

      ```ruby
      chef_client_cron "Run an override recipe" do
        daemon_options ["--override-runlist mycorp_base::default"]
      end
      ```
      DOC

      extend Chef::ResourceHelpers::CronValidations

      property :job_name, String,
        default: Chef::Dist::CLIENT,
        description: "The name of the cron job to create."

      property :comment, String,
        description: "A comment to place in the cron.d file."

      property :user, String,
        description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.",
        default: "root"

      property :minute, [Integer, String],
        description: "The minute at which #{Chef::Dist::PRODUCT} is to run (0 - 59) or a cron pattern such as '0,30'.",
        default: "0,30", callbacks: {
          "should be a valid minute spec" => method(:validate_minute),
        }

      property :hour, [Integer, String],
        description: "The hour at which #{Chef::Dist::PRODUCT} is to run (0 - 23) or a cron pattern such as '0,12'.",
        default: "*", callbacks: {
          "should be a valid hour spec" => method(:validate_hour),
        }

      property :day, [Integer, String],
        description: "The day of month at which #{Chef::Dist::PRODUCT} is to run (1 - 31) or a cron pattern such as '1,7,14,21,28'.",
        default: "*", callbacks: {
          "should be a valid day spec" => method(:validate_day),
        }

      property :month, [Integer, String],
        description: "The month in the year on which #{Chef::Dist::PRODUCT} is to run (1 - 12, jan-dec, or *).",
        default: "*", callbacks: {
          "should be a valid month spec" => method(:validate_month),
        }

      property :weekday, [Integer, String],
        description: "The day of the week on which #{Chef::Dist::PRODUCT} is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7.",
        default: "*", callbacks: {
          "should be a valid weekday spec" => method(:validate_dow),
        }

      property :splay, [Integer, String],
        default: 300,
        coerce: proc { |x| Integer(x) },
        callbacks: { "should be a positive number" => proc { |v| v > 0 } },
        description: "A random number of seconds between 0 and X to add to interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time."

      property :mailto, String,
        description: "The e-mail address to e-mail any cron task failures to."

      property :accept_chef_license, [true, false],
        description: "Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement/>",
        default: false

      property :config_directory, String,
        default: Chef::Dist::CONF_DIR,
        description: "The path of the config directory."

      property :log_directory, String,
        default: lazy { platform?("mac_os_x") ? "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize}" : "/var/log/#{Chef::Dist::DIR_SUFFIX}" },
        default_description: "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize} on macOS and /var/log/#{Chef::Dist::DIR_SUFFIX} otherwise",
        description: "The path of the directory to create the log file in."

      property :log_file_name, String,
        default: "client.log",
        description: "The name of the log file to use."

      property :append_log_file, [true, false],
        default: true,
        description: "Append to the log file instead of overwriting the log file on each run."

      property :chef_binary_path, String,
        default: "/opt/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}",
        description: "The path to the #{Chef::Dist::CLIENT} binary."

      property :daemon_options, Array,
        default: lazy { [] },
        description: "An array of options to pass to the #{Chef::Dist::CLIENT} command."

      property :environment, Hash,
        default: lazy { {} },
        description: "A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`."

      action :add do
        # TODO: Replace this with a :create_if_missing action on directory when that exists
        unless ::Dir.exist?(new_resource.log_directory)
          directory new_resource.log_directory do
            owner new_resource.user
            mode "0750"
            recursive true
          end
        end

        declare_resource(cron_resource_type, new_resource.job_name) do
          minute new_resource.minute
          hour        new_resource.hour
          day         new_resource.day
          weekday     new_resource.weekday
          month       new_resource.month
          environment new_resource.environment
          mailto      new_resource.mailto if new_resource.mailto
          user        new_resource.user
          comment     new_resource.comment if new_resource.comment
          command     cron_command
        end
      end

      action :remove do
        declare_resource(cron_resource_type, new_resource.job_name) do
          action :delete
        end
      end

      action_class do
        #
        # Generate a uniformly distributed unique number to sleep from 0 to the splay time
        #
        # @param [Integer] splay The number of seconds to splay
        #
        # @return [Integer]
        #
        def splay_sleep_time(splay)
          seed = node["shard_seed"] || Digest::MD5.hexdigest(node.name).to_s.hex
          random = Random.new(seed.to_i)
          random.rand(splay)
        end

        #
        # The complete cron command to run
        #
        # @return [String]
        #
        def cron_command
          cmd = ""
          cmd << "/bin/sleep #{splay_sleep_time(new_resource.splay)}; "
          cmd << "#{new_resource.chef_binary_path} "
          cmd << "#{new_resource.daemon_options.join(" ")} " unless new_resource.daemon_options.empty?
          cmd << "-c #{::File.join(new_resource.config_directory, "client.rb")} "
          cmd << "--chef-license accept " if new_resource.accept_chef_license
          cmd << log_command
          cmd << " || echo \"#{Chef::Dist::PRODUCT} execution failed\"" if new_resource.mailto
          cmd
        end

        #
        # The portion of the overall cron job that handles logging based on the append_log_file property
        #
        # @return [String]
        #
        def log_command
          if new_resource.append_log_file
            "-L #{::File.join(new_resource.log_directory, new_resource.log_file_name)}"
          else
            "> #{::File.join(new_resource.log_directory, new_resource.log_file_name)} 2>&1"
          end
        end

        #
        # The type of cron resource to run. Linux systems all support the /etc/cron.d directory
        # and can use the cron_d resource, but Solaris / AIX / FreeBSD need to use the crontab
        # via the legacy cron resource.
        #
        # @return [Symbol]
        #
        def cron_resource_type
          linux? ? :cron_d : :cron
        end
      end
    end
  end
end


text:
require 'fog/openstack/volume/requests/get_transfer_details'
require 'fog/openstack/volume/v2/requests/real'


text:
import json
import logging
import mock
import os
import shutil
import sys
import time
import tempfile
import unittest

import docker
import requests.exceptions
from plugins.systems.ctprobe_container_crawler import CTProbeContainerCrawler
from utils.process_utils import start_child

# Tests the FprobeContainerCrawler class
# Throws an AssertionError if any test fails

CTPROBE_FRAME = \
    '[{"data":"xAAAAAABAAYAAAAAAAAAAAIAAAA0AAGAFAABgAgAAQCsEQABCAACAKwRAA4cA' \
    'AKABQABAAYAAAAGAAIAiEYAAAYAAwARWwAANAACgBQAAYAIAAEArBEADggAAgCsEQABHAAC' \
    'gAUAAQAGAAAABgACABFbAAAGAAMAiEYAAAgADADhBU3ACAADAAAAAYgIAAcAAAAAeDAABIA' \
    'sAAGABQABAAEAAAAFAAIABwAAAAUAAwAAAAAABgAEAAMAAAAGAAUAAAAAAA==","metadat' \
    'a":{"ip-addresses":["172.17.0.14"]}},{"data":"jAAAAAIBAAAAAAAAAAAAAAIAA' \
    'AA0AAGAFAABgAgAAQCsEQABCAACAKwRAA4cAAKABQABAAYAAAAGAAIAiDYAAAYAAwARWwAA' \
    'NAACgBQAAYAIAAEArBEADggAAgCsEQABHAACgAUAAQAGAAAABgACABFbAAAGAAMAiDYAAAg' \
    'ADAAM3QUACAADAAAAAY4=","metadata":{"ip-addresses":["172.17.0.14"]}}]'

def simulate_ctprobe(url):
    """ simulate writing by ctprobe """
    filename = url.split('://')[1]
    with open(filename, 'w') as f:
        f.write(CTPROBE_FRAME)
    with open(filename + ".tmp", 'w') as f:
        f.write(CTPROBE_FRAME)

def mocked_add_collector(self, url, ipaddresses, ifname):
    code, content = self.send_request('add_collector',
                                      [url, ipaddresses, ifname])
    if code == 200:
        # in this case we simulate a file being written...
        simulate_ctprobe(url)
        return True
    else:
        raise Exception('HTTP Error %d: %s' % (code, content['error']))

def mocked_start_child(params, pass_fds, null_fds, ign_sigs, setsid=False,
                       **kwargs):
    return start_child(['sleep', '1'], pass_fds, null_fds, ign_sigs, setsid)

def mocked_start_child_ctprobe_except(params, pass_fds, null_fds, ign_sigs,
                                      setsid=False, **kwargs):
    if params[0] == 'conntrackprobe':
        raise Exception('Refusing to start %s' % params[0])

def mocked_session_get(self, path, data=''):
    class Session(object):
        def __init__(self, status_code, content):
            self.status_code = status_code
            self.content = json.dumps(content)

    return Session(200, {'error': ''})

def mocked_session_get_fail(self, path, data=''):
    class Session(object):
        def __init__(self, status_code, content):
            self.status_code = status_code
            self.content = json.dumps(content)

    return Session(400, {'error': 'Bad request'})

def mocked_ethtool_get_peer_ifindex(ifname):
    raise Exception('ethtool exception')

def mocked_check_ctprobe_alive(self, pid):
    return True

# Tests conducted with a single container running.
class CtprobeFunctionalTests(unittest.TestCase):
    image_name = 'alpine:latest'

    def setUp(self):
        self.docker = docker.Client(
            base_url='unix://var/run/docker.sock', version='auto')
        try:
            if len(self.docker.containers()) != 0:
                raise Exception(
                    "Sorry, this test requires a machine with no docker"
                    "containers running.")
        except requests.exceptions.ConnectionError:
            print ("Error connecting to docker daemon, are you in the docker"
                   "group? You need to be in the docker group.")

        self.docker.pull(repository='alpine', tag='latest')
        self.container = self.docker.create_container(
            image=self.image_name, command='ping -w 30 8.8.8.8')
        self.tempd = tempfile.mkdtemp(prefix='crawlertest.')
        self.docker.start(container=self.container['Id'])

        self.output_dir = os.path.join(self.tempd, 'crawler-ctprobe')

        self.params = {
            'ctprobe_user': 'nobody',
            'ctprobe_output_dir': self.output_dir,
            'output_filepattern': 'testfile',
        }

        logging.basicConfig(stream=sys.stderr)
        self.logger = logging.getLogger("crawlutils").setLevel(logging.INFO)

    def tearDown(self):
        self.docker.stop(container=self.container['Id'])
        self.docker.remove_container(container=self.container['Id'])

        shutil.rmtree(self.tempd)
        CTProbeContainerCrawler.ctprobe_pid = 0
        CTProbeContainerCrawler.ifaces_monitored = []

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'ConntrackProbeClient.add_collector', mocked_add_collector)
    def test_crawl_outcontainer_ctprobe(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: expecting collector output')

        num = len(CTProbeContainerCrawler.ifaces_monitored)

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # the fake collector writes the single frame immediately
        res = []
        for data in ctc.crawl(self.container['Id'], avoid_setns=False,
                              **self.params):
            res.append(data)
        assert len(res) == 1
        assert len(CTProbeContainerCrawler.ifaces_monitored) == num + 1

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get_fail)
    def test_start_netlink_collection_fault1(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: collector cannot be configured')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # with ctprobe failing to start, we won't get data
        res = []
        for data in ctc.crawl(self.container['Id'], avoid_setns=False,
                              **self.params):
            res.append(data)
        assert len(res) == 0
        assert len(CTProbeContainerCrawler.ifaces_monitored) == 0

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'ConntrackProbeClient.add_collector', mocked_add_collector)
    def test_start_netlink_collection_fault4(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: collector cannot be configured')

        ctprobe_user = self.params['ctprobe_user']
        self.params['ctprobe_user'] = 'user-does-not-exist'

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # with ctprobe failing to start, we won't get data
        assert not ctc.crawl(self.container['Id'], avoid_setns=False,
                             **self.params)
        assert len(CTProbeContainerCrawler.ifaces_monitored) == 0

        self.params['ctprobe_user'] = ctprobe_user

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child_ctprobe_except)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'ConntrackProbeClient.add_collector', mocked_add_collector)
    def test_start_netlink_collection_fault5(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: conntrackprobe fails to start')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        assert not ctc.crawl(self.container['Id'], avoid_setns=False,
                             **self.params)
        assert len(CTProbeContainerCrawler.ifaces_monitored) == 0

        assert not ctc.check_ctprobe_alive(CTProbeContainerCrawler.ctprobe_pid)
        # this should always fail
        assert not ctc.check_ctprobe_alive(1)

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'ethtool_get_peer_ifindex', mocked_ethtool_get_peer_ifindex)
    def test_start_netlink_collection_fault6(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: ethtool throws an error')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # with ctprobe failing to start, we won't get data
        res = []
        for data in ctc.crawl(self.container['Id'], avoid_setns=False,
                              **self.params):
            res.append(data)
        assert len(res) == 0
        assert len(CTProbeContainerCrawler.ifaces_monitored) == 0

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'ConntrackProbeClient.add_collector', mocked_add_collector)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'CTProbeContainerCrawler.check_ctprobe_alive',
                mocked_check_ctprobe_alive)
    def test_remove_datafiles(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: datafiles of disappeared interface '
                    'being removed')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        CTProbeContainerCrawler.ifaces_monitored.append(ifname)

        self.params['output_filepattern'] = 'ctprobe-{ifname}-{timestamp}'

        # create a datafile for this fake interface
        timestamp = int(time.time())
        filepattern = 'ctprobe-{ifname}-{timestamp}' \
                      .format(ifname=ifname, timestamp=timestamp)
        # have the ctprobe write a file with the ifname in
        # the filename
        ctc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())
        simulate_ctprobe('file+json://%s/%s' % (self.output_dir, filepattern))
        written_file = os.path.join(self.output_dir, filepattern)
        assert os.path.isfile(written_file)

        CTProbeContainerCrawler.next_cleanup = 0
        # calling ctc.crawl() will trigger a cleanup of that file
        # since our fake interface never existed
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file)

    @mock.patch('plugins.systems.ctprobe_container_crawler.start_child',
                mocked_start_child)
    @mock.patch('plugins.systems.ctprobe_container_crawler.'
                'requests_unixsocket.Session.get', mocked_session_get)
    def test_remove_stale_files(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: stale file being removed')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        CTProbeContainerCrawler.ifaces_monitored.append(ifname)

        self.params['output_filepattern'] = 'ctprobe-{ifname}-{timestamp}'

        # have the fake socket-datacollector write a file with the ifname in
        # the filename
        ctc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())

        written_file = os.path.join(self.output_dir, 'test.output')
        with open(written_file, 'a') as f:
            f.write('hello')

        assert os.path.isfile(written_file)

        # mock the stale file timeout so that our file will get removed
        # with in reasonable time
        CTProbeContainerCrawler.STALE_FILE_TIMEOUT = 5

        # calling ctc.crawl() will not trigger a cleanup of that file
        # the first time
        logger.info('1st crawl')
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should still be here
        assert os.path.isfile(written_file)

        # the next time we will crawl, the file will be removed
        CTProbeContainerCrawler.next_cleanup = time.time()
        time.sleep(CTProbeContainerCrawler.STALE_FILE_TIMEOUT + 1)

        logger.info('2nd crawl')
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file)

    if __name__ == '__main__':
        unittest.main()