text:
using std::make_shared;
using std::shared_ptr;

class VectorFieldPlannerTest : public ::testing::Test
{
public:
  using FCLCollisionDetector = dart::collision::FCLCollisionDetector;
  using DistanceMetric = aikido::distance::DistanceMetric;
  using MetaSkeletonStateSpacePtr
      = aikido::statespace::dart::MetaSkeletonStateSpacePtr;
  using MetaSkeletonStateSpace
      = aikido::statespace::dart::MetaSkeletonStateSpace;
  using SO2 = aikido::statespace::SO2;
  using GeodesicInterpolator = aikido::statespace::GeodesicInterpolator;
  using ScopedState = MetaSkeletonStateSpace::ScopedState;

  using BodyNode = dart::dynamics::BodyNode;
  using BodyNodePtr = dart::dynamics::BodyNodePtr;
  using Joint = dart::dynamics::Joint;
  using Skeleton = dart::dynamics::Skeleton;
  using Shape = dart::dynamics::Shape;
  using BoxShape = dart::dynamics::BoxShape;
  using JointPtr = dart::dynamics::JointPtr;
  using SkeletonPtr = dart::dynamics::SkeletonPtr;

  using PrismaticJoint = dart::dynamics::PrismaticJoint;
  using RevoluteJoint = dart::dynamics::RevoluteJoint;
  using WeldJoint = dart::dynamics::WeldJoint;
  using BallJoint = dart::dynamics::BallJoint;
  using VisualAspect = dart::dynamics::VisualAspect;
  using CollisionAspect = dart::dynamics::CollisionAspect;
  using DynamicsAspect = dart::dynamics::DynamicsAspect;
  using constantsd = dart::math::constantsd;
  using Vector3d = Eigen::Vector3d;

  enum TypeOfDOF
  {
    DOF_X,
    DOF_Y,
    DOF_Z,
    DOF_ROLL,
    DOF_PITCH,
    DOF_YAW,
    BALL
  };

  VectorFieldPlannerTest() : mErrorTolerance(1e-3)
  {
    mSkel = createNLinkRobot();
    mNumDof = mSkel->getNumDofs();

    mUpperPositionLimits = Eigen::VectorXd::Constant(mNumDof, constantsd::pi());
    mLowerPositionLimits
        = Eigen::VectorXd::Constant(mNumDof, -constantsd::pi());
    mUpperVelocityLimits = Eigen::VectorXd::Constant(mNumDof, 4.0);
    mLowerVelocityLimits = Eigen::VectorXd::Constant(mNumDof, -4.0);

    mSkel->setPositionUpperLimits(mUpperPositionLimits);
    mSkel->setPositionLowerLimits(mLowerPositionLimits);
    mSkel->setVelocityUpperLimits(mUpperVelocityLimits);
    mSkel->setVelocityLowerLimits(mLowerVelocityLimits);
    mStateSpace = std::make_shared<MetaSkeletonStateSpace>(mSkel.get());
    mBodynode = mSkel->getBodyNodes().back();

    mStartConfig = Eigen::VectorXd::Zero(mNumDof);
    mStartConfig << 2.13746, -0.663612, 1.77876, 1.87515, 2.58646, -1.90034,
        -1.03533;

    mGoalConfig = Eigen::VectorXd(mNumDof);
    mPassingConstraint = std::make_shared<PassingConstraint>(mStateSpace);
  }

  std::pair<Joint*, BodyNode*> add1DofJoint(
      SkeletonPtr _skel,
      BodyNode* _parent,
      const BodyNode::Properties& _node,
      const std::string& _name,
      double _val,
      double _min,
      double _max,
      int _type)
  {
    dart::dynamics::GenericJoint<dart::math::R1Space>::Properties properties(
        _name);
    properties.mPositionLowerLimits[0] = _min;
    properties.mPositionUpperLimits[0] = _max;
    std::pair<Joint*, BodyNode*> newComponent;
    if (DOF_X == _type)
      newComponent = _skel->createJointAndBodyNodePair<PrismaticJoint>(
          _parent,
          PrismaticJoint::Properties(
              properties, Eigen::Vector3d(1.0, 0.0, 0.0)),
          _node);
    else if (DOF_Y == _type)
      newComponent = _skel->createJointAndBodyNodePair<PrismaticJoint>(
          _parent,
          PrismaticJoint::Properties(
              properties, Eigen::Vector3d(0.0, 1.0, 0.0)),
          _node);
    else if (DOF_Z == _type)
      newComponent = _skel->createJointAndBodyNodePair<PrismaticJoint>(
          _parent,
          PrismaticJoint::Properties(
              properties, Eigen::Vector3d(0.0, 0.0, 1.0)),
          _node);
    else if (DOF_YAW == _type)
      newComponent = _skel->createJointAndBodyNodePair<RevoluteJoint>(
          _parent,
          RevoluteJoint::Properties(properties, Eigen::Vector3d(0.0, 0.0, 1.0)),
          _node);
    else if (DOF_PITCH == _type)
      newComponent = _skel->createJointAndBodyNodePair<RevoluteJoint>(
          _parent,
          RevoluteJoint::Properties(properties, Eigen::Vector3d(0.0, 1.0, 0.0)),
          _node);
    else if (DOF_ROLL == _type)
      newComponent = _skel->createJointAndBodyNodePair<RevoluteJoint>(
          _parent,
          RevoluteJoint::Properties(properties, Eigen::Vector3d(1.0, 0.0, 0.0)),
          _node);

    newComponent.first->setPosition(0, _val);
    return newComponent;
  }

  //==============================================================================
  /// Creates a N link manipulator with the given dimensions where each joint is
  /// the specified type
  SkeletonPtr createNLinkRobot()
  {
    Vector3d dim(0.1, 0.1, 0.2);

    SkeletonPtr robot = Skeleton::create();
    // robot->disableSelfCollision();

    // Create the first link, the joint with the ground and its shape
    BodyNode::Properties node(BodyNode::AspectProperties("link0"));
    //  node.mInertia.setLocalCOM(Vector3d(0.0, 0.0, dim(2)/2.0));
    std::shared_ptr<Shape> shape(new BoxShape(dim));

    std::pair<Joint*, BodyNode*> pair1;
    pair1 = add1DofJoint(
        robot,
        nullptr,
        node,
        "joint0",
        0.0,
        -constantsd::pi(),
        constantsd::pi(),
        DOF_ROLL);

    Joint* joint = pair1.first;
    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
    // T.translation() = Eigen::Vector3d(0.0, 0.0, -0.5*dim(2));
    // joint->setTransformFromParentBodyNode(T);
    T.translation() = Eigen::Vector3d(0.0, 0.0, 0.5 * dim(2));
    joint->setTransformFromChildBodyNode(T);
    // joint->setDampingCoefficient(0, 0.01);

    auto currentNode = pair1.second;
    currentNode
        ->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(
            shape);

    BodyNode* parentNode = currentNode;

    // Create links iteratively
    for (int i = 1; i < 7; ++i)
    {
      std::ostringstream ssLink;
      std::ostringstream ssJoint;
      ssLink << "link" << i;
      ssJoint << "joint" << i;

      node = BodyNode::Properties(BodyNode::AspectProperties(ssLink.str()));
      //    node.mInertia.setLocalCOM(Vector3d(0.0, 0.0, dim(2)/2.0));
      shape = std::shared_ptr<Shape>(new BoxShape(dim));

      std::pair<Joint*, BodyNode*> newPair;

      TypeOfDOF type;
      if (i % 2 == 1)
        type = DOF_PITCH;
      else
        type = DOF_ROLL;
      newPair = add1DofJoint(
          robot,
          parentNode,
          node,
          ssJoint.str(),
          0.0,
          -constantsd::pi(),
          constantsd::pi(),
          type);

      Joint* joint = newPair.first;
      Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
      T.translation() = Eigen::Vector3d(0.0, 0.0, -0.5 * dim(2));
      joint->setTransformFromParentBodyNode(T);
      T.translation() = Eigen::Vector3d(0.0, 0.0, 0.5 * dim(2));
      joint->setTransformFromChildBodyNode(T);
      // joint->setDampingCoefficient(0, 0.01);

      auto current_node = newPair.second;
      current_node
          ->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(
              shape);

      parentNode = current_node;
    }

    // If finished, initialize the skeleton
    // addEndEffector(robot, parentNode, dim);

    return robot;
  }

  // Parameters
  double mErrorTolerance;

  // DART setup
  SkeletonPtr mSkel;
  std::vector<std::pair<JointPtr, BodyNodePtr>> mJnBn;
  MetaSkeletonStateSpacePtr mStateSpace;
  BodyNodePtr mBodynode;
  std::size_t mNumDof;
  double mLinearVelocity;

  Eigen::VectorXd mUpperPositionLimits;
  Eigen::VectorXd mLowerPositionLimits;
  Eigen::VectorXd mUpperVelocityLimits;
  Eigen::VectorXd mLowerVelocityLimits;

  // Arguments for planner
  Eigen::VectorXd mStartConfig;
  Eigen::VectorXd mGoalConfig;
  shared_ptr<PassingConstraint> mPassingConstraint;
};

TEST_F(VectorFieldPlannerTest, ComputeJointVelocityFromTwistTest)
{
  using aikido::planner::vectorfield::computeJointVelocityFromTwist;

  Eigen::VectorXd jointVelocityUpperLimits = mSkel->getVelocityUpperLimits();
  Eigen::VectorXd jointVelocityLowerLimits = mSkel->getVelocityLowerLimits();

  double maxStepSize = 0.01;
  double padding = 2e-3;

  // Linear only
  Eigen::Vector6d desiredTwist1 = Eigen::Vector6d::Zero();
  desiredTwist1.tail<3>() << 1.0, 1.0, 1.0;

  Eigen::VectorXd qd = Eigen::VectorXd::Zero(mNumDof);
  EXPECT_TRUE(computeJointVelocityFromTwist(
      qd,
      desiredTwist1,
      mSkel,
      mBodynode,
      padding,
      jointVelocityLowerLimits,
      jointVelocityUpperLimits,
      true,
      maxStepSize));

  // Angular only
  Eigen::Vector6d desiredTwist2 = Eigen::Vector6d::Zero();
  desiredTwist2.head<3>() << 1.0, 1.0, 1.0;

  EXPECT_TRUE(computeJointVelocityFromTwist(
      qd,
      desiredTwist2,
      mSkel,
      mBodynode,
      padding,
      jointVelocityLowerLimits,
      jointVelocityUpperLimits,
      true,
      maxStepSize));

  // Both linear and angular
  Eigen::Vector6d desiredTwist3 = Eigen::Vector6d::Zero();
  desiredTwist3.head<3>() << 1.0, 1.0, 1.0;
  desiredTwist3.tail<3>() << 1.0, 1.0, 1.0;

  EXPECT_TRUE(computeJointVelocityFromTwist(
      qd,
      desiredTwist2,
      mSkel,
      mBodynode,
      padding,
      jointVelocityLowerLimits,
      jointVelocityUpperLimits,
      true,
      maxStepSize));
}

TEST_F(VectorFieldPlannerTest, PlanToEndEffectorOffsetTest)
{
  using aikido::planner::dart::ConfigurationToEndEffectorOffset;
  using aikido::planner::vectorfield::
      VectorFieldConfigurationToEndEffectorOffsetPlanner;

  Eigen::Vector3d direction;
  direction << 1., 1., 0.;
  direction.normalize();
  double signedDistance = 0.41;
  double distanceTolerance = 0.01;

  mSkel->setPositions(mStartConfig);
  Eigen::Isometry3d startTrans = mBodynode->getTransform();
  Eigen::VectorXd startVec = startTrans.translation();

  double positionTolerance = 0.01;
  double angularTolerance = 0.15;
  double initialStepSize = 0.01;
  double jointLimitTolerance = 1e-3;
  double constraintCheckResolution = 1e-2;
  std::chrono::duration<double> timelimit(60.0);

  // Create problem.
  auto offsetProblem = ConfigurationToEndEffectorOffset(
      mStateSpace,
      mSkel,
      mBodynode,
      direction,
      signedDistance,
      mPassingConstraint);

  // Create planner.
  VectorFieldConfigurationToEndEffectorOffsetPlanner vfOffsetPlanner(
      mStateSpace,
      mSkel,
      distanceTolerance,
      positionTolerance,
      angularTolerance,
      initialStepSize,
      jointLimitTolerance,
      constraintCheckResolution,
      timelimit);

  // Invoke planning method.
  auto traj = vfOffsetPlanner.plan(offsetProblem);

  EXPECT_FALSE(traj == nullptr) << "Trajectory not found";

  if (traj == nullptr)
  {
    return;
  }

  // Extract and evaluate first waypoint
  auto firstWayPoint = mStateSpace->createState();
  traj->evaluate(0.0, firstWayPoint);
  Eigen::VectorXd testStart(mStateSpace->getDimension());
  Eigen::VectorXd referenceStart(mStateSpace->getDimension());
  mStateSpace->convertStateToPositions(firstWayPoint, testStart);
  EXPECT_LE((testStart - mStartConfig).norm(), mErrorTolerance);

  int stepNum = 10;
  double timeStep = traj->getDuration() / stepNum;

  double minDistance = signedDistance - distanceTolerance;
  double maxDistance = signedDistance + distanceTolerance;

  for (double t = traj->getStartTime(); t <= traj->getEndTime(); t += timeStep)
  {
    auto waypoint = mStateSpace->createState();
    traj->evaluate(t, waypoint);

    mStateSpace->setState(mSkel.get(), waypoint);
    Eigen::Isometry3d waypointTrans = mBodynode->getTransform();
    Eigen::Vector3d waypointVec = waypointTrans.translation();

    Eigen::Vector3d linear_error
        = startVec + direction * minDistance - waypointVec;
    Eigen::Vector3d const linear_orthogonal_error
        = linear_error - linear_error.dot(direction) * direction;
    double const linear_orthogonal_magnitude = linear_orthogonal_error.norm();
    EXPECT_LE(linear_orthogonal_magnitude, positionTolerance);
  }

  auto endpoint = mStateSpace->createState();
  traj->evaluate(traj->getEndTime(), endpoint);
  mStateSpace->setState(mSkel.get(), endpoint);
  Eigen::Isometry3d endTrans = mBodynode->getTransform();
  double movedDistance
      = (endTrans.translation() - startTrans.translation()).norm();

  // Verify the moving distance
  EXPECT_GE(movedDistance, minDistance);
  EXPECT_LE(movedDistance, maxDistance);
}

TEST_F(VectorFieldPlannerTest, DirectionZeroVector)
{
  using aikido::planner::dart::ConfigurationToEndEffectorOffset;
  using aikido::planner::vectorfield::
      VectorFieldConfigurationToEndEffectorOffsetPlanner;

  Eigen::Vector3d direction = Eigen::Vector3d::Zero();
  double signedDistance = 0.21;

  mSkel->setPositions(mStartConfig);

  // Create Problem, which should fail.
  EXPECT_THROW(
      ConfigurationToEndEffectorOffset(
          mStateSpace,
          mSkel,
          mBodynode,
          direction,
          signedDistance,
          mPassingConstraint),
      std::invalid_argument);
}

TEST_F(VectorFieldPlannerTest, PlanToEndEffectorPoseTest)
{
  using aikido::planner::vectorfield::computeGeodesicDistance;
  using aikido::planner::vectorfield::MoveEndEffectorOffsetVectorField;
  using dart::math::eulerXYXToMatrix;

  Eigen::VectorXd goalConfig = Eigen::VectorXd::Zero(mNumDof);
  goalConfig << 1.13746, -0.363612, 0.77876, 1.07515, 1.58646, -1.00034,
      -0.03533;
  mSkel->setPositions(goalConfig);
  Eigen::Isometry3d targetPose = mBodynode->getTransform();

  double poseErrorTolerance = 0.01;
  double initialStepSize = 0.05;
  double r = 1.0;
  double jointLimitTolerance = 1e-2;
  double constraintCheckResolution = 1e-2;
  std::chrono::duration<double> timelimit(300.);

  mSkel->setPositions(mStartConfig);

  auto traj1 = aikido::planner::vectorfield::planToEndEffectorPose(
      mStateSpace,
      mSkel,
      mBodynode,
      mPassingConstraint,
      targetPose,
      poseErrorTolerance,
      r,
      initialStepSize,
      jointLimitTolerance,
      constraintCheckResolution,
      timelimit);

  EXPECT_FALSE(traj1 == nullptr) << "Trajectory not found";

  if (traj1 == nullptr)
  {
    return;
  }

  // Extract and evalute first waypoint
  auto firstWayPoint = mStateSpace->createState();
  traj1->evaluate(0.0, firstWayPoint);
  Eigen::VectorXd testStart(mNumDof);
  mStateSpace->convertStateToPositions(firstWayPoint, testStart);

  double errorTolerance = 1e-3;
  EXPECT_TRUE((testStart - mStartConfig).norm() <= errorTolerance);

  auto endpoint = mStateSpace->createState();
  traj1->evaluate(traj1->getEndTime(), endpoint);
  mStateSpace->setState(mSkel.get(), endpoint);
  Eigen::Isometry3d endTrans = mBodynode->getTransform();

  double poseError = computeGeodesicDistance(endTrans, targetPose, r);
  EXPECT_LE(poseError, poseErrorTolerance);
}

redpajama_set_name: RedPajamaGithub


text:
import ConstantsModule from './constants';
import ScorecardModule from './scorecard';
import HeadingModule from './heading';
import NavbarModule from './navbar';
import AuthModule from './auth';
import GetScoresModule from './getScores';
import CourseDescriptionModule from './courseDescription';

const module = angular
  .module('app.common', [
    ConstantsModule,
    ScorecardModule,
    HeadingModule,
    NavbarModule,
    AuthModule,
    GetScoresModule,
    CourseDescriptionModule
  ]);

export default module.name;


text:
package net.sourceforge.pmd.lang.java.rule;

import java.util.List;

import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTEqualityExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
import net.sourceforge.pmd.lang.java.ast.ASTRelationalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;

/**
 * This is an abstract rule for patterns which compare a method invocation to 0.
 * It could be further abstracted to find code that compares something to
 * another definable pattern
 *
 * @author acaplan
 */
public abstract class AbstractInefficientZeroCheck extends AbstractJavaRule {

    public abstract boolean appliesToClassName(String name);

    public abstract boolean isTargetMethod(NameOccurrence occ);

    public Object visit(ASTVariableDeclaratorId node, Object data) {
	Node nameNode = node.getTypeNameNode();
        if (nameNode instanceof ASTPrimitiveType) {
            return data;
        }
        if (!appliesToClassName(node.getNameDeclaration().getTypeImage())) {
            return data;
        }

        List<NameOccurrence> declars = node.getUsages();
        for (NameOccurrence occ: declars) {
            if (!isTargetMethod(occ)) {
                continue;
            }
            Node expr = occ.getLocation().jjtGetParent().jjtGetParent().jjtGetParent();
            if ((expr instanceof ASTEqualityExpression ||
                    (expr instanceof ASTRelationalExpression && ">".equals(expr.getImage())))
                && isCompareZero(expr)) {
                addViolation(data, occ.getLocation());
            }
        }
        return data;
    }

    /**
     * We only need to report if this is comparing against 0
     *
     * @param equality
     * @return true if this is comparing to 0 else false
     */
    private boolean isCompareZero(Node equality) {
        return checkComparison(equality, 0) || checkComparison(equality, 1);

    }

    /**
     * Checks if the equality expression passed in is of comparing against the
     * value passed in as i
     *
     * @param equality
     * @param i
     *            The ordinal in the equality expression to check
     * @return true if the value in position i is 0, else false
     */
    private boolean checkComparison(Node equality, int i) {
	Node target = equality.jjtGetChild(i).jjtGetChild(0);
        if (target.jjtGetNumChildren() == 0) {
            return false;
        }
        target = target.jjtGetChild(0);
        return target instanceof ASTLiteral && "0".equals(target.getImage());
    }

}


text:
package com.libre.takes.doc;

import com.libre.om.Base;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.flash.RsFlash;
import org.takes.facets.forward.RsForward;
import org.takes.rq.RqHref;

/**
 * Reject friend.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.3
 */
final class TkEjectFriend implements Take {

    /**
     * Base.
     */
    private final transient Base base;

    /**
     * Ctor.
     * @param bse Base
     */
    TkEjectFriend(final Base bse) {
        this.base = bse;
    }

    @Override
    public Response act(final Request req) throws IOException {
        final String friend = new RqHref.Smart(
            new RqHref.Base(req)
        ).single("friend");
        new RqDoc(req, this.base).doc().friends().eject(friend);
        return new RsForward(
            new RsFlash(String.format("friend \"%s\" ejected", friend))
        );
    }

}


text:
Reports

Leads by clients

        <form action="table-leads" id="LeadsByClients">

            Select Date Range

              <input type="text" class="input-sm form-control" name="start"/>
              to
              <input type="text" class="input-sm form-control" name="end"/>

              Select Client

            <select name="client" class="form-control">
              <option value="0">All</option>

              <?php
              foreach ($clients as $key => $value) {
                echo "<option value='" . $value['id'] . "'>" . $value['campaign_name'] . "</option>";
              }

              ?>
            </select>

            <input type="submit" class="btn btn-primary">

        </form>

Leads by Sources

        <form action="table-leads" id="LeadsBySources">

            Select Date Range

              <input type="text" class="input-sm form-control" name="start"/>
              to
              <input type="text" class="input-sm form-control" name="end"/>

              Select Source Provider

            <select name="source" id="sources" class="form-control">
              <option value="0">All</option>
              <?php
              foreach ($LeadSources as $key => $value) {
                echo "<option value='" . $value['source'] . "'>" . $value['name'] . "</option>";
              }
              ?>
            </select>

              Select State

            <select name="State" id="state" class="form-control">
              <option value="">All</option>
              <option value="NSW">NSW</option>
              <option value="VIC">VIC</option>
              <option value="WA">WA</option>
              <option value="QLD">QLD</option>
              <option value="SA">SA</option>
              <option value="ACT">ACT</option>
              <option value="TAS">TAS</option>
            </select>

            <input type="submit" class="btn btn-primary">

        </form>

            ID
            Campaign Name
            State
            Date
            View

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Lead details

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
layout: default
title: CAS - Delegate Authentication Authentication Policy
category: Authentication
---

{% include variables.html %}

# Delegated Authentication - Authentication Policy

Service definitions may be conditionally authorized to use an external identity provider
by defining their own access strategy and authentication policy:

```json
{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "sample",
  "name" : "sample",
  "id" : 100,
  "accessStrategy" : {
    "@class" : "org.apereo.cas.services.DefaultRegisteredServiceAccessStrategy",
    "delegatedAuthenticationPolicy" : {
      "@class" : "org.apereo.cas.services.DefaultRegisteredServiceDelegatedAuthenticationPolicy",
      "allowedProviders" : [ "java.util.ArrayList", [ "Facebook", "Twitter" ] ],
      "permitUndefined": true,
      "exclusive": false
    }
  }
}
```

The following fields are supported for the authentication policy:

| Type                    | Description
|-------------------------|--------------------------------------------------------------------------------------
| `allowedProviders`      | The list of allowed providers should contain the external identity provider names (i.e. client names).
| `permitUndefined`       | Decides whether access should be granted in the event that no allowed providers are defined explicitly.
| `exclusive`             | Decides whether authentication should be exclusively limited to allowed providers, disabling other methods such as username/password, etc.

## Configuration

{% include_cached casproperties.html properties="cas.authn.pac4j.core" %}

## Auto Redirection

By default, the list of available identity providers are displayed in a selection menu and the user is allowed to
choose the provider. In certain scenarios, the browser may be instructed to auto-redirect to a pre-selected identity provider.

### Pre-selected Identity Provider

An identity provider can be instructed via CAS configuration to always perform an auto-redirect, regardless of the application
type and/or authentication requests. The selected identity provider is considered by CAS to be the *primary* strategy for handling
authentication requests.

### Identity Provider Exclusivity

Authentication requests from the following application will be auto-redirected to the identity provider that is identified
as `Twitter` in the CAS configuration, since the delegated authentication policy only allows the single exclusive use of this provider,
removing selection menu and the ability to choose other alternative authentication methods.

```json
{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "sample",
  "name" : "sample",
  "id" : 100,
  "accessStrategy" : {
    "@class" : "org.apereo.cas.services.DefaultRegisteredServiceAccessStrategy",
    "delegatedAuthenticationPolicy" : {
      "@class" : "org.apereo.cas.services.DefaultRegisteredServiceDelegatedAuthenticationPolicy",
      "allowedProviders" : [ "java.util.ArrayList", [ "Twitter" ] ],
      "exclusive": true
    }
  }
}
```

### Identity Provider Cookie Selection

A chosen identity provider from the selection menu can be optionally tracked and stored using a dedicated cookie,
which will then be used on subsequent attempts to auto-redirect to the identity provider, skipping the selection menu.

{% include_cached casproperties.html properties="cas.authn.pac4j.cookie" %}

### Identity Provider Groovy Selection

The auto-redirection strategy of a given identity provider may also be decided dynamically via a Groovy resource
whose path is defined via CAS settings. The Groovy script would have the following outline:

```groovy
import org.apereo.cas.web.*

def run(Object[] args) {
    def requestContext = args[0]
    def service = args[1]
    def registeredService = args[2]
    def provider = args[3] as DelegatedClientIdentityProviderConfiguration
    def logger = args[4]
    logger.info("Checking ${provider.name}...")

    if (provider.name.equals("Twitter")) {
        provider.autoRedirect = true
        return provider
    }
    return null
}
```

The following parameters are passed to the script:

| Parameter             | Description
|---------------------------------------------------------------------------------------------------------
| `requestContext`        | Reference to the Spring Webflow request context, as `RequestContext`.
| `service`               | Reference to the application authentication request as `Service`, if any.
| `registeredService`     | Reference to registered service definition, if any.
| `provider`              | Reference to the identity provider configuration identified as `DelegatedClientIdentityProviderConfiguration`.
| `logger`                | The object responsible for issuing log messages such as `logger.info(...)`.

### Identity Provider Custom Selection

If you wish to create your own redirection strategy, you will need to
design a component and register it with CAS as such:

```java
@Bean
public DelegatedClientIdentityProviderRedirectionStrategy delegatedClientIdentityProviderRedirectionStrategy() {
    return new CustomDelegatedClientIdentityProviderRedirectionStrategy();
}
```

[See this guide](../configuration/Configuration-Management-Extensions.html) to learn more about
how to register configurations into the CAS runtime.


text:
package org.testifyproject.junit4.fixture;

import org.testifyproject.junit4.fixture.common.Hello;

/**
 *
 * @author saden
 */
public class ImplicitType {

    private final Hello hello;

    ImplicitType(Hello hello) {
        this.hello = hello;
    }

    public String execute() {
        return hello.greet();

    }

    public Hello getHello() {
        return hello;
    }

}


text:
package com.variaveis.entity;

import java.util.List;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="variavel")
public class Variavel {

	@Id
	@GeneratedValue
	@Column(name="id_variavel")
	private Integer id;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="id_grupo")
	private Grupo grupo;

	@Column(name="nome_variavel")
	private String nomeVariavel;

	@Column(name="nome_exibido")
	private String nomeExibido;

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

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

	@Column(name="clausula_where")
	private String clausulaWhere;

	@Column(name="contexto")
	@Enumerated(EnumType.ORDINAL)
	private Contexto contexto;

	@Column(name="tipo_variavel")
	@Enumerated(EnumType.ORDINAL)
	private TipoVariavel tipoVariavel;

	@Column(name="menu_especificacao")
	private String menuEspecificacao;

	@Column(name="campo_especificacao")
	private String campoEspecificacao;

	@Column(name="descricao_especificacao")
	private String descricaoEspecificacao;

	@ElementCollection(targetClass = Visao.class)
	@CollectionTable(name = "variavel_visao",
	    joinColumns = @JoinColumn(name = "id_variavel"))
	@Column(name = "id_visao")
	private List<Visao> visoes;

	@ManyToMany(fetch = FetchType.LAZY)
	@JoinTable(name="variavel_parametro",
    	joinColumns={@JoinColumn(name="id_variavel")},
    	inverseJoinColumns={@JoinColumn(name="id_parametro")})
	private List<Parametro> parametro;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Grupo getGrupo() {
		return grupo;
	}

	public void setGrupo(Grupo grupo) {
		this.grupo = grupo;
	}

	public String getNomeVariavel() {
		return nomeVariavel;
	}

	public void setNomeVariavel(String nomeVariavel) {
		this.nomeVariavel = nomeVariavel;
	}

	public String getNomeExibido() {
		return nomeExibido;
	}

	public void setNomeExibido(String nomeExibido) {
		this.nomeExibido = nomeExibido;
	}

	public String getTabela() {
		return tabela;
	}

	public void setTabela(String tabela) {
		this.tabela = tabela;
	}

	public String getCampo() {
		return campo;
	}

	public void setCampo(String campo) {
		this.campo = campo;
	}

	public String getClausulaWhere() {
		return clausulaWhere;
	}

	public void setClausulaWhere(String clausulaWhere) {
		this.clausulaWhere = clausulaWhere;
	}

	public Contexto getContexto() {
		return contexto;
	}

	public void setContexto(Contexto contexto) {
		this.contexto = contexto;
	}

	public TipoVariavel getTipoVariavel() {
		return tipoVariavel;
	}

	public void setTipoVariavel(TipoVariavel tipoVariavel) {
		this.tipoVariavel = tipoVariavel;
	}

	public String getMenuEspecificacao() {
		return menuEspecificacao;
	}

	public void setMenuEspecificacao(String menuEspecificacao) {
		this.menuEspecificacao = menuEspecificacao;
	}

	public String getCampoEspecificacao() {
		return campoEspecificacao;
	}

	public void setCampoEspecificacao(String campoEspecificacao) {
		this.campoEspecificacao = campoEspecificacao;
	}

	public String getDescricaoEspecificacao() {
		return descricaoEspecificacao;
	}

	public void setDescricaoEspecificacao(String descricaoEspecificacao) {
		this.descricaoEspecificacao = descricaoEspecificacao;
	}

	public List<Visao> getVisoes() {
		return visoes;
	}

	public void setVisoes(List<Visao> visoes) {
		this.visoes = visoes;
	}

	public List<Parametro> getParametro() {
		return parametro;
	}

	public void setParametro(List<Parametro> parametro) {
		this.parametro = parametro;
	}

}


text:
import animate from './BetaAnimation';
import LoginDialog from './LoginDialog';
import DictionaryList from './DictionaryList';

import React from 'react';
import {Nav, Navbar, NavDropdown, MenuItem} from 'react-bootstrap';

const Header = ({title, onSelect}) =>
  <Navbar fixedTop fluid>
    <Navbar.Header>
      <Navbar.Brand>

          Slovareg
          BETA

      </Navbar.Brand>
      <Navbar.Toggle />
    </Navbar.Header>

    <Navbar.Collapse>

        <NavDropdown
          id='navigation'
          title={title}>
          <MenuItem eventKey='profile'>Profile</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey='logout'>Log Out</MenuItem>
        </NavDropdown>

    </Navbar.Collapse>
  </Navbar>;

const Footer = () =>

    Реализовано с помощью сервиса API «Яндекс.Словарь»

;

const SlovaregPage = React.createClass({
  propTypes: {
    // fb
    // globalConfig -- promise
    onLogout: React.PropTypes.func,
    onLogin: React.PropTypes.func,  // returns promise
  },

  componentDidMount() {
    if (this.props.fb.getAuth()) {
      const beta = document.getElementById('beta');
      animate(beta, 90.0, 0.0);
    }
  },

  handleSelect(eventKey) {
    if (eventKey === 'logout') {
      this.props.onLogout();
    } else if (eventKey === 'profile') {
      // TODO:
    }
  },

  render() {
    if (this.props.fb.getAuth()) {
      return (

          <DictionaryList fb={this.props.fb}/>

      );
    } else {
      return (
        <LoginDialog onSubmit={this.props.onLogin}/>
      );
    }
  }
});

export default SlovaregPage;


text:
<!DOCTYPE html>

<title>Edugate | Categories</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,400italic,700,900,300">
    <link type="text/css" rel="stylesheet" href="assets/font/font-icon/font-awesome-4.4.0/css/font-awesome.css">
    <link type="text/css" rel="stylesheet" href="assets/font/font-icon/font-svg/css/Glyphter.css">

    <link type="text/css" rel="stylesheet" href="assets/libs/animate/animate.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/bootstrap-3.3.5/css/bootstrap.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/owl-carousel-2.0/assets/owl.carousel.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/selectbox/css/jquery.selectbox.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/fancybox/css/jquery.fancybox.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/fancybox/css/jquery.fancybox-buttons.css">
    <link type="text/css" rel="stylesheet" href="assets/libs/media-element/build/mediaelementplayer.min.css">

    <link type="text/css" rel="stylesheet" href="#" id="color-skins">

hello.shinway@gmail.com

+84 909 015 345

loginregister

                    <button type="button" data-toggle="collapse" data-target=".navigation" class="navbar-toggle edugate-navbar"></button>

Home

Home page 01

Home page 02

Home page 03

Courses

courses

course detail

events

event detail

gallery

gallery 3 column

gallery 4 column

gallery masonry

pages

categories

profile teacher

about us

login

register

404 page

FAQ page

News

news list

news grid

news grid nonsidebar

news masonry

news detail

Contact

                            <form><input type="text" placeholder="Search" class="searchbox"/>
                                <button type="submit" class="searchbutton fa fa-search"></button>
                            </form>

all categories

Home

Categories

                                <form><select class="form-select style-1 selectbox">
                                    <option value="all">all categories</option>
                                    <option value="languages">languages</option>
                                    <option value="science">science</option>
                                </select><select class="form-select style-2 selectbox">
                                    <option value="price">price</option>
                                    <option value="datetime">datetime</option>
                                    <option value="teacher">teacher</option>
                                </select><input type="text" placeholder="Do you want to learn today?" class="form-input"/>
                                    <button type="submit" class="form-submit btn btn-blue">search now</button>

                                </form>

Showing 1-6 of total 12 courses

language

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

software

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

social media

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

photography

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

business

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

communication

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

total courses 92

                                                    <button class="btn btn-green">all course</button>

‹

1

2

...

14

›

BECOME AN INSTRUCTOR

Join thousand of instructors and earn money hassle free!

                    <button onclick="window.location.href='contact.html'" class="btn btn-blue btn-bold">GET STARTED NOW</button>

EDUGATE

Edugate is a great start for an education personnel or organization to start the online business with 1 Click.

hello@edugate.com

P: 3333 222 1111

99 Barnard St - Suite 111

United States - GA 22222

USEFUL LINKS

Teachers

Courses

Support

Why Edugate

Social Media

Site Map

Company

Latest Courses

Partners

Blog Post

Help Topic

Policies

GALLERY

<img src="assets/images/gallery/gallery-08.jpg"
                                                                                alt="" class="img-responsive"/>

                                    View more

MAILING

Sign up for our mailing list to get latest updates and offers.

                                    <form action="http://swlabs.co/edugate/index.html">

<input type="text" placeholder="Email address" class="form-control form-email-widget"/><input type="submit" value="✓" class="btn btn-email"/>

                                    </form>

We respect your privacy

HOME

COURSES

ABOUT

PAGES

NEWS

CONTACT

@ SWLABS

setting color


text:
[![PyPI version](https://badge.fury.io/py/demisto-py.svg)](https://badge.fury.io/py/demisto-py)
[![CircleCI](https://circleci.com/gh/demisto/demisto-py/tree/master.svg?style=svg)](https://circleci.com/gh/demisto/demisto-py/tree/master)

# Demisto Client for Python

A Python library for the Demisto API.

Version 2.x is compatible with Demisto server version 4.5 and later.

## Demisto for Python Usage

This section covers the steps you need to take to get the client configured.

### 1. Get a Demisto API Key

Follow these instructions to generate your Demisto API Key.

1. In Demisto, navigate to **Settings > API Keys**.
2. Click the **Generate Your Key** button.

To avoid hard coding configurations in your code, it is possible to specify configruation params
as the following environment variables (env variables will be used if parameters are not specified):

* DEMISTO_BASE_URL
* DEMISTO_API_KEY
* DEMISTO_USERNAME
* DEMISTO_PASSWORD
* DEMISTO_VERIFY_SSL (true/false. Default: true)
* XSIAM_AUTH_ID (for Cortex XSIAM only. If set, Cortex XSIAM API will be used)
* SSL_CERT_FILE (specify an alternate certificate bundle)

### 2. Create a Demisto client instance with the api-key and server-url

```python
import demisto_client

# Also possible to set env variables: DEMISTO_API_KEY and DEMISTO_BASE_URL
api_key = 'YOUR_API_KEY'
host = 'https://YOUR_DEMISTO_HOST'

api_instance = demisto_client.configure(base_url=host, api_key=api_key)

```

**For Cortex XSIAM, we need to set the auth_id**
```python
import demisto_client

# Also possible to set env variables: DEMISTO_API_KEY, DEMISTO_BASE_URL and XSIAM_AUTH_ID
api_key = 'YOUR_API_KEY'
auth_id = 'THE AUTHORIZATION ID'
host = 'https://YOUR_XSIAM_HOST'

api_instance = demisto_client.configure(base_url=host, api_key=api_key, auth_id=auth_id)

```

**Alternatively, you can login with username and password (only in xsoar):**

```python
import demisto_client

# Also possible to set env variables: DEMISTO_USERNAME DEMISTO_PASSWORD and DEMISTO_BASE_URL
host = 'https://YOUR_DEMISTO_HOST'
username = 'YOUR_USERNAME'
password = 'YOUR_PASSWORD'

api_instance = demisto_client.configure(base_url=host, username=username, password=password)
```

### 3. Create incidents

```python
import demisto_client.demisto_api
from demisto_client.demisto_api.rest import ApiException

api_key = 'YOUR_API_KEY'
host = 'https://YOUR_DEMISTO_HOST'

api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False)
create_incident_request = demisto_client.demisto_api.CreateIncidentRequest()

create_incident_request.name = 'Sample Simulation Incident'
create_incident_request.type = 'Simulation'
create_incident_request.owner = 'Admin'

try:
    api_response = api_instance.create_incident(create_incident_request=create_incident_request)
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->create_incident: %s\n" % e)

```

Additional examples available in the [docs](docs/README.md) and under the [examples folder](examples/).

## API Documentation

API Documentation based upon the Demisto Server Swagger API is available [here](docs/README.md)

## Troubleshooting

### API Key

If when using an API key you encounter a response similar to the following:

```json
{"id":"forbidden","status":403,"title":"Forbidden","detail":"Issue with CSRF code","error":"http: named cookie not present","encrypted":false,"multires":null}
```

It means your API key is invalid. Make sure you are using a valid API key. You can check your API key by using curl with the following request:

```bash
  curl -i -k -H 'Authorization: YOUR_API_KEY'  https://your-demisto.server.url/about
```

For a valid API key you will receive a response similar to the following:

```BASH
HTTP/1.1 200 OK
Strict-Transport-Security: max-age=10886400000000000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Xss-Protection: 1; mode=block
Date: Thu, 04 Jun 2020 09:27:53 GMT
Content-Length: 189
Content-Type: text/plain; charset=utf-8

{"demistoVersion":"5.5.0", ...}
```

## Contributing

Contributions are welcome and appreciated. To contribute follow the instructions below and submit a PR.

Before merging any PRs, we need all contributors to sign a contributor license agreement. By signing a contributor license agreement, we ensure that the community is free to use your contributions.

When you open a new pull request, a bot will evaluate whether you have signed the CLA. If required, the bot will comment on the pull request, including a link to accept the agreement. The CLA document is also available for review as a [PDF](https://github.com/demisto/content/blob/master/docs/cla.pdf).

If the `license/cla` status check remains on *Pending*, even though all contributors have accepted the CLA, you can recheck the CLA status by visiting the following link (replace **[PRID]** with the ID of your PR): <https://cla-assistant.io/check/demisto/demisto-py?pullRequest=[PRID>] .

## Dev Environment Setup

We recommend installing both development environments. We use [tox](https://github.com/tox-dev/tox) for managing environments and running unit tests.

Install `tox`:

```bash
pip install tox
```

List configured environments:

```bash
tox -l
```

Then setup dev virtual envs for python 3 (will also install all necessary requirements):

```bash
tox --devenv py310
```

Switch to python 3 env by running:

```bash
. py310/bin/activate
```

## Running Unit Tests

We use pytest to run unit tests. Inside a virtual env you can run unit test using:

```bash
python -m pytest -v
```

Additionally, our build uses tox to run on multiple envs. To use tox to run on all supported environments (py38, py39, py310), run:

```bash
tox -q
```

## Code Generation

Library code was generated using the Demisto Server 4.5.0 Swagger definition with modifications to support later Server versions.

**Important:** All code under [demisto_client/demisto_api](demisto_client/demisto_api) is generated using the swagger code generation tool. Do not modify this code directly.

We use a script to run the generate tool and then modify as needed.
If you would like to contribute **DO NOT** modify the generated code directly, modify the script: [gen-code.sh](gen-code.sh) and then re-generate the code.

To generate the code run (requires bash, sed and docker):

```bash
./gen-code.sh
```

## Publishing a Release (demisto devs)

After merging to `master`, a test deployment will be pushed to: <https://test.pypi.org/project/demisto-py/> .
You can test the test package by following the pip install instructions. For example:

```bash
pip install -i https://test.pypi.org/simple/ demisto-py
```

Steps to publish a production release:

* Make sure [CHANGELOG.md](CHANGELOG.md) is up to date.
* Create and push a tag with the release version using git. For example:

  ```bash
  git tag v2.0.19
  git push origin v2.0.19
  ```

* Check that the circleci build completes successfully. Once done, the release will be pushed to: <https://pypi.org/project/demisto-py/> .
* Update GitHub releases: go to [tags page](https://github.com/demisto/demisto-py/tags) and for the relevant tag choose from the right drop down menu: `Create release`. Name the release the same as the tag. Copy the text from previous releases for the description.

Congratulations! The release is now public.

## License

Apache 2.0 - See [LICENSE](LICENSE) for more information.


text:
package modules.maps;

import fp.forevo.manager.MasterScript;
import fp.forevo.manager.TestObjectManager;
import fp.forevo.proxy.*;

/**
 * Class generated automaticaly. Do not edit from text editor. Change it using Test Object Manager.
 * @author Test Object Manager by ForProgress
 * @see www.forprogress.com.pl
 * @since 2016-09-14 23:56:39
 */
public class FirstWindowMap extends MasterScript {

	private TestObjectManager tomgr = new TestObjectManager(getProjectPath(this.getClass()), "res/modules/FirstWindow/FirstWindow.map");

	/**
	 * Description:
	 */
	protected Window FirtsWindow = getWindow(tomgr, "FirtsWindow");

	/**
	 * Description:

	 * Driver: Sikuli

	 * Class: Button

	 *

	 * File: btn_restart.PNG

	 * Similarity: 0.8

	 * Offset:  0:0

	 * Tags:

	 *

	 *

	 *

	 *

	 *

	 *

	 */
	protected Button btnRestart = getButton(tomgr, FirtsWindow, "btnRestart");

	/**
	 * Description:

	 * Driver: Sikuli

	 * Class: Image

	 *

	 * File: red_square.PNG

	 * Similarity: 0.99

	 * Offset:  0:0

	 * Tags:

	 *

	 *

	 *

	 *

	 *

	 *

	 */
	protected Image redSquare = getImage(tomgr, FirtsWindow, "redSquare");

}


text:
package com.rogueai.framework.snmp2bean.api;

public abstract class AbstractSnmpSession implements SnmpSession {

    private int retries = 3;

    private int timeout = 3000;

    private SmiTypeProvider smiTypeProvider;

    private SnmpErrorMsgProvider errorMsgProvider;

    public int getRetries() {
        return retries;
    }

    public void setRetries(int retries) {
        this.retries = retries;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setSmiTypeProvider(SmiTypeProvider typeProvider) {
        this.smiTypeProvider = typeProvider;
    }

    public void setSnmpErrorMsgProvider(SnmpErrorMsgProvider errorMsgProvider) {
        this.errorMsgProvider = errorMsgProvider;
    }

    public final SmiTypeProvider getSmiTypeProvider() {
        return smiTypeProvider;
    }

    public final SnmpErrorMsgProvider getSnmpErrorMsgProvider() {
        return errorMsgProvider;
    }
}


text:
package com.bear.web.utils;

import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang.StringUtils;

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

/**
 * Created by VIJAY-YAN on 2014/8/8.
 */
public class Conditions {
    static Logger log = Logger.getLogger(Conditions.class);
    public static final String EQUAL = "EQUAL"; // 相等
    public static final String NOT_EQUAL = "NOT_EQUAL"; // 不相等
    public static final String LESS_THEN = "LESS_THEN"; // 小于
    public static final String LESS_EQUAL = "LESS_EQUAL"; // 小于等于
    public static final String GREATER_EQUAL = "GREATER_EQUAL"; // 大于等于
    public static final String GREATER_THEN = "GREATER_THEN"; // 大于
    public static final String FUZZY = "FUZZY"; // 模糊匹配 %xxx%
    public static final String FUZZY_LEFT = "FUZZY_LEFT"; // 左模糊 %xxx
    public static final String FUZZY_RIGHT = "FUZZY_RIGHT"; // 右模糊 xxx%
    public static final String NOT_EMPTY = "NOT_EMPTY"; // 不为空值的情况
    public static final String EMPTY = "EMPTY"; // 空值的情况
    // 用于接收SQL语句
    private ThreadLocal<String> sql = new ThreadLocal<String>();
    // 用于接收参数数组
    private ThreadLocal<List<Object>> paramList = new ThreadLocal<List<Object>>();
    // 用于存放设置的条件
    private ThreadLocal<Map<String, Object[]>> conditionMap = new ThreadLocal<Map<String, Object[]>>();
    // 用于存放需要排除的字段
    private ThreadLocal<Map<String, String>> excludeFieldMap = new ThreadLocal<Map<String, String>>();

    // 构造方法(表示没有设置查询类型的字段全部按照等于来处理)
    public Conditions() {
        conditionMap.set(new HashMap<String, Object[]>());
        excludeFieldMap.set(new HashMap<String, String>());
    }

    // 构造方法(设置后表示字段所有的查询方式按照设置类型来处理,除非后面针对字段的重新设置)
    public Conditions(String type) {
        Map<String, Object[]> map = new HashMap<String, Object[]>();
        map.put("GLOBALTYPE", new String[]{type});
        conditionMap.set(map);
        excludeFieldMap.set(new HashMap<String, String>());
    }

    /**
     * ************************************************************************
     * 设置字段的查询类型
     *
     * @param QueryType 查询类型
     * @param filedName 字段名称数组
     */
    public void setFiledQuery(String QueryType, String... filedName) {
        if (StringUtils.isNotBlank(QueryType) && !Common.isNullOrEmpty(filedName)) {
            Map<String, Object[]> map = conditionMap.get();
            map.put(QueryType, filedName);
            conditionMap.set(map);
        }
    }

    /**
     * ************************************************************************
     * 设置需要排除的字段
     *

     * setexcludeField

     *
     * @param filedName
     * @return 返回对象
     * @Exception 异常对象
     */
    public void setExcludeField(String... filedName) {
        if (!Common.isNullOrEmpty(filedName)) {
            Map<String, String> map = excludeFieldMap.get();
            for (String str : filedName) {
                map.put(str, str);
            }
            excludeFieldMap.set(map);
        }
    }

    /**
     * ************************************************************************
     * 查询空值或者不为空值的情况 setNullFieldQuery
     *
     * @param QueryType
     * @param filedName
     * @return 返回对象
     * @Exception 异常对象
     */
    public void setNullOrNotNullFieldQuery(String QueryType, String... filedName) {
        if (StringUtils.isNotBlank(QueryType) && !Common.isNullOrEmpty(filedName)) {
            if (!NOT_EMPTY.equals(QueryType) && !EMPTY.equals(QueryType)) {
                log.error("空值或者非空查询的类型只能为:EMPTY、NOT_EMPTY");
                throw new RuntimeException("空值或者非空查询的类型只能为:EMPTY、NOT_EMPTY");
            }
            Map<String, Object[]> map = conditionMap.get();
            map.put(QueryType, filedName);
            conditionMap.set(map);
        }
    }

    /**
     * ************************************************************************
     * 传值查询
     *
     * @param QueryType  查询类型
     * @param fieldName  字段名称
     * @param filedValue 字段值
     */
    public void setValueQuery(String QueryType, String fieldName, Object filedValue) {
        if (StringUtils.isNotBlank(QueryType) && StringUtils.isNotBlank(fieldName) && !Common.isNullOrEmpty(filedValue)) {
            Object[] param = new Object[2];
            param[0] = fieldName; // 字段名
            param[1] = filedValue;// 字段值
            Map<String, Object[]> map = conditionMap.get();
            map.put(QueryType + "#" + fieldName, param);// 避免类型重复被覆盖掉就加上字段名
            conditionMap.set(map);
        }
    }

    /**
     * ************************************************************************
     * 用于生成SQL条件语句不带别名
     *
     * @param modelClass 必须继承于Model
     */
    public void modelToCondition(Model<?> modelClass) {
        modelToCondition(modelClass, null);
    }

    /**
     * ************************************************************************
     * 用于生成SQL条件语句不带别名
     *
     * @param recordClass 必须是一个Record类
     */
    public void recordToCondition(Record recordClass) {
        recordToCondition(recordClass, null);
    }

    /**
     * ************************************************************************
     * 用于生成SQL条件语句带别名
     *
     * @param modelClass 必须继承于Model
     * @param alias      别名
     */
    public void modelToCondition(Model<?> modelClass, String alias) {
        alias = StringUtils.isNotBlank(alias) ? alias + "." : "";
        if (modelClass != null) {
            // 所有的字段
            String[] fieldNames = modelClass.getAttrNames();
            // 字段名和值的map集合
            Map<String, Object> valueMap = Common.modelToMap(modelClass);
            // 构建查询条件
            buildCondition(alias, fieldNames, valueMap);
        } else {
            if (!conditionMap.get().isEmpty()) {
                buildCondition(alias, new String[]{}, new HashMap<String, Object>());
            } else {
                sql.set("");
                paramList.set(new ArrayList<Object>());
            }
        }
    }

    /**
     * ************************************************************************
     * 用于生成SQL条件语句不带别名
     *
     * @param recordClass 必须是一个Record类
     * @param alias       别名
     */
    public void recordToCondition(Record recordClass, String alias) {
        // 别名
        alias = StringUtils.isNotBlank(alias) ? alias + "." : "";
        if (recordClass != null) {
            // 所有的字段
            String[] fieldNames = recordClass.getColumnNames();
            // 字段名和值的map集合
            Map<String, Object> valueMap = Common.recordToMap(recordClass);
            // 构建查询条件
            buildCondition(alias, fieldNames, valueMap);
        } else {
            if (!conditionMap.get().isEmpty()) {
                buildCondition(alias, new String[]{}, new HashMap<String, Object>());
            } else {
                sql.set("");
                paramList.set(new ArrayList<Object>());
            }
        }
    }

    /**
     * ************************************************************************
     * 构建条件语句
     *
     * @param alias      别名
     * @param fieldNames 所有查询的字段名称
     * @param valueMap   所有的值的map
     */
    private void buildCondition(String alias, String[] fieldNames, Map<String, Object> valueMap) {
        try {
            // 构建条件前先清空变量
            sql.set("");
            paramList.set(new ArrayList<Object>());
            // 用于存放参数列表
            ArrayList<Object> paramArrayList = new ArrayList<Object>();
            StringBuilder sb = new StringBuilder();
            // 所有的字段名称
            Map<String, String> usedFieldMap = new HashMap<String, String>();
            if (!conditionMap.get().isEmpty()) {
                for (Map.Entry<String, Object[]> map : conditionMap.get().entrySet()) {
                    String queryType = map.getKey();
                    Object[] array = map.getValue();
                    if (queryType.indexOf("#") > 0) {// 传值查询
                        String fieldQueryType = queryType.split("#")[0];
                        String fieldName = array[0] != null ? array[0].toString() : "";
                        Object fieldValue = array[1];
                        // 将设置过的字段保存到数组中
                        usedFieldMap.put(fieldName, fieldName);
                        // 构建SQL语句
                        buildSQL(sb, fieldQueryType, fieldName, fieldValue, alias, paramArrayList);
                    } else {// 字段查询
                        for (Object field : array) {
                            String filedName = field != null ? field.toString() : "";
                            if (!excludeFieldMap.get().containsKey(filedName)) {
                                Object fieldValue = valueMap.get(filedName);
                                // 将设置过的字段保存到数组中
                                usedFieldMap.put(filedName, filedName);
                                // 构建查询语句
                                buildSQL(sb, queryType, filedName, fieldValue, alias, paramArrayList);
                            }
                        }
                    }
                }
            }
            // 对没有设置条件的字段进行查询类型设置
            String queryType = EQUAL;
            if (conditionMap.get().containsKey("GLOBALTYPE")) {
                String[] typeArray = (String[]) conditionMap.get().get("QueryType");
                queryType = typeArray[0];
            }
            // 对未使用过的字段进行build
            for (String field : fieldNames) {
                if (!usedFieldMap.containsKey(field)) {
                    Object fieldValue = valueMap.get(field);
                    // 构建查询语句
                    buildSQL(sb, queryType, field, fieldValue, alias, paramArrayList);
                }
            }
            // 合并传入的参数到参数对象中
            sql.set(sb.toString());
            paramList.set(paramArrayList);
            conditionMap.set(new HashMap<String, Object[]>());// 清空本次的条件map
            excludeFieldMap.set(new HashMap<String, String>());// 清空本次的排除字段
        } catch (Exception e) {
            log.error("Conditions构建SQL语句出现错误,请仔细检查!");
            e.printStackTrace();
        }
    }

    /**
     * ************************************************************************
     * 构建SQL语句
     *
     * @param sb         用于拼接SQL语句
     * @param queryType  查询类型
     * @param fieldName  字段名称
     * @param fieldValue 字段值
     * @param alias      别名
     * @return
     */
    private void buildSQL(StringBuilder sb, String queryType, String fieldName, Object fieldValue, String alias, ArrayList<Object> params) {
        // 非空的时候进行设置
        if (!Common.isNullOrEmpty(fieldValue) && !Common.isNullOrEmpty(fieldName)) {
            if (EQUAL.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " = ? ");
                params.add(fieldValue);
            } else if (NOT_EQUAL.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " <> ? ");
                params.add(fieldValue);
            } else if (LESS_THEN.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " < ? ");
                params.add(fieldValue);
            } else if (LESS_EQUAL.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " <= ? ");
                params.add(fieldValue);
            } else if (GREATER_THEN.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " > ? ");
                params.add(fieldValue);
            } else if (GREATER_EQUAL.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " >= ? ");
                params.add(fieldValue);
            } else if (FUZZY.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " like ? ");
                params.add("%" + fieldValue + "%");
            } else if (FUZZY_LEFT.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " like ? ");
                params.add("%" + fieldValue);
            } else if (FUZZY_RIGHT.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " like ? ");
                params.add(fieldValue + "%");
            }
        } else {
            if (EMPTY.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " is null ");
            } else if (NOT_EMPTY.equals(queryType)) {
                sb.append(" and " + alias + fieldName + " is not null ");
            }
        }
    }

    public String getSql() {
        return sql.get();
    }

    public List<Object> getParamList() {
        return paramList.get();
    }
}


text:
// <copyright file="_.cs" company="xBehave.net contributors">
//  Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>

namespace Xbehave
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using Xbehave.Fluent;

    /// <summary>
    /// Provides access to step definition methods.
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "_", Justification = "By design.")]
    [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "By design.")]
    [CLSCompliant(false)]
    public static class _
    {
        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep Given(string text, Action body)
        {
            return new Step("Given " + text, body, StepType.Given);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep When(string text, Action body)
        {
            return new Step("When " + text, body, StepType.When);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep Then(string text, Action body)
        {
            return new Step("Then " + text, body, StepType.Then);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep And(string text, Action body)
        {
            return new Step("And " + text, body, StepType.And);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep But(string text, Action body)
        {
            return new Step("But " + text, body, StepType.But);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep Given(string text, Action<IStepContext> body)
        {
            return new Step("Given " + text, body, StepType.Given);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep When(string text, Action<IStepContext> body)
        {
            return new Step("When " + text, body, StepType.When);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep Then(string text, Action<IStepContext> body)
        {
            return new Step("Then " + text, body, StepType.Then);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep And(string text, Action<IStepContext> body)
        {
            return new Step("And " + text, body, StepType.And);
        }

        /// <summary>
        /// Defines a step in the current scenario.
        /// </summary>
        /// <param name="text">The step text.</param>
        /// <param name="body">The action that will perform the step.</param>
        /// <returns>
        /// An instance of <see cref="IStep"/>.
        /// </returns>
        [SuppressMessage(
            "Microsoft.Globalization",
            "CA1303:Do not pass literals as localized parameters",
            MessageId = "Xbehave.new Step(System.String,System.Action)",
            Justification = "Text must match method name.")]
        public static IStep But(string text, Action<IStepContext> body)
        {
            return new Step("But " + text, body, StepType.But);
        }
    }
}


text:
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    jsonb_initializations!
  end

  test '##publicly_found' do
    refute(User.publicly_found(users(:student_1).public_link) == nil)
    assert_nil User.publicly_found(users(:student_private).public_link)
  end

  test '#identifier' do
    s = users(:student_1)
    assert_nil s.slug
    assert_equal 'public___user1_valid_com', s.public_link
    assert s.slug
  end

  describe '#valid_counselor_id' do
    before do
      @s = users(:student_1)
    end

    it 'works' do
      assert @s.valid_counselor_id?(users(:counselor_1).id)
    end
  end

  describe 'type checking' do
    it 'works for student?' do
      assert users(:student_1).student?
    end

    it 'works for counselors' do
      assert users(:counselor_1).counselor?
    end

    it 'handles empty profiles' do
      u = create :user
      refute u.student?
    end
  end

  describe '#students' do
    it 'works for counselor without students' do
      assert_equal 0, users(:counselor_empty_school).students.count
    end

    it 'works for counselors with students' do
      assert_equal 1, users(:counselor_1).students.count
    end
  end

  describe '#counselors' do
    describe 'failure' do
      it 'when there is no school' do
        assert_nil users(:noschool_student).counselors.first
      end

      it 'when there is no counselor' do
        assert_nil users(:uncounseled_student).counselors.first
      end
    end

    it 'works' do
      assert_equal users(:counselor_1).email, users(:student_1).counselors.order(created_at: :asc).first.email
    end
  end

  test '#friends' do
    # 2, in fixtures.
    assert_equal 2, users(:student_1).friends.count
  end

  test '#friendships' do
    # 2, in fixtures
    assert_equal 2, users(:student_1).friendships.count
  end

  test 'making friends' do
    assert_difference('Friendship.count', 1) do
      users(:student_1).make_friend(users(:nothing_user))
    end
  end
end


text:
<?php

namespace OpenClassrooms\FrontDesk\Services\Impl;

use OpenClassrooms\FrontDesk\Doubles\Gateways\PlanGatewayMock;
use OpenClassrooms\FrontDesk\Doubles\Models\PersonStub1;
use OpenClassrooms\FrontDesk\Doubles\Models\PlanStub1;
use OpenClassrooms\FrontDesk\Doubles\Models\PlanTestCase;

/**
 * @author Killian Herbunot <killian.herbunot@openclassrooms.com>
 */
class PlanServiceImplTest extends \PHPUnit_Framework_TestCase
{
    use PlanTestCase;

    /**
     * @var PlanServiceImpl
     */
    private $service;

    /**
     * @test
     */
    public function getPlans_ReturnPlans()
    {
        $plans = $this->service->getPlans(PersonStub1::ID);
        $this->assertEquals(0, count($plans) - count(PlanGatewayMock::$plans));

        $i = 0;
        foreach ($plans as $plan) {
            $planStub = '\OpenClassrooms\FrontDesk\Doubles\Models\PlanStub'.++$i;
            $this->assertPlan(new $planStub(), $plan);
        }
    }

    public function setUp()
    {
        $this->service = new PlanServiceImpl();
        $this->service->setPlanGateway(new PlanGatewayMock([PlanStub1::ID => new PlanStub1()]));
    }
}


text:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use app\models\DataHelper;
$avatar = DataHelper::avatar();
?>

<?= Html::encode($model->content) ?>

		<?= $model->postedBy->username?>
		<?php if(\Carbon\Carbon::createFromTimestamp($model->created_at, 'Asia/Manila')->diffInMinutes() <  60): ?>
			<?= DataHelper::carbonDateDiff($model->created_at)?>
		<?php else: ?>
			<?= DataHelper::carbonDateTime($model->created_at)  ?>
		<?php endif ?>


text:
package com.neon.intellij.plugins.gitlab.controller.editor;

import com.intellij.openapi.fileEditor.FileEditorState;
import com.intellij.openapi.fileEditor.FileEditorStateLevel;

public class GLFileEditorState implements FileEditorState {

    public static final FileEditorState DUMMY = new GLFileEditorState();

    @Override
    public boolean canBeMergedWith( FileEditorState otherState, FileEditorStateLevel level ) {
        return false;
    }
}


text:
if (!process.addAsyncListener) require('../index.js');

var test = require('tap').test;
var zlib = require('zlib');

// Convert semver string to number set
// TODO: This is *very* naive structure to check versions with,
// but it works well enough for now...
var nodeVersion = process.version.slice(1).split('.').map(Number)

var compressors = ['deflate', 'deflateRaw', 'gzip'];
var decompressors = ['inflate', 'inflateRaw', 'gunzip'];

compressors.forEach(function (method) {
  var name = 'zlib.' + method;
  var el = {
    name: name,
    children: [],
    before: 1,
    after: 1,
    error: 0
  };
  var list = [ el ];
  if (nodeVersion[0] >= 6) {
    list.push(el);
  }

  var children = [
    {
      name: name,
      // Compressors use streams internally,
      // so there's a bunch of nested stuff.
      children: [
        {
          name: name,
          children: [
            {
              name: name,
              children: list,
              before: 1,
              after: 1,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }
      ],
      before: 1,
      after: 1,
      error: 0
    }
  ]
  if (nodeVersion[0] >= 9) {
    children.unshift({
      name: name,
      children: [],
      before: 1,
      after: 1,
      error: 0
    })
  }

  test('test ' + name, function (t) {
    test_helper(t, function (listener, done) {
      listener.currentName = name;
      zlib[method](new Buffer('Goodbye World'), done);
    }, {
      name: 'root',
      children: children,
      before: 0,
      after: 0,
      error: 0
    });
  });
});

decompressors.forEach(function (method, i) {
  var preMethod = compressors[i];
  var name = 'zlib.' + method;
  var el = {
    name: name,
    children: [],
    before: 1,
    after: 1,
    error: 0
  };
  var list = [ el ];
  if (nodeVersion[0] >= 6) {
    list.push(el);
  }

  var children = [
    {
      name: name,
      // Compressors use streams internally,
      // so there's a bunch of nested stuff.
      children: [
        {
          name: name,
          children: [
            {
              name: name,
              children: list,
              before: 1,
              after: 1,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }
      ],
      before: 1,
      after: 1,
      error: 0
    }
  ]
  if (nodeVersion[0] >= 9) {
    children.unshift({
      name: name,
      children: [],
      before: 1,
      after: 1,
      error: 0
    })
  }

  test('test ' + name, function (t) {
    zlib[preMethod](new Buffer('Goodbye World'), function (err, buf) {
      t.ok(!err, 'should not have errored in preparation')
      test_helper(t, function (listener, done) {
        listener.currentName = name;
        zlib[method](buf, done);
      }, {
        name: 'root',
        children: children,
        before: 0,
        after: 0,
        error: 0
      });
    });
  });
});

function test_helper (t, run, expect) {
  // Trigger callback out-of-band from async listener
  var args;
  var interval = setInterval(function () {
    if (args) {
      clearInterval(interval);
      t.ok(!args[0], 'should not have errored');
      t.deepEqual(listener.root, expect);
      t.end();
    }
  }, 5);

  var listener = addListner();
  run(listener, function () {
    args = Array.prototype.slice.call(arguments);
  });
  process.removeAsyncListener(listener.listener);
}

function addListner() {
  var listener = process.addAsyncListener({
    create: create,
    before: before,
    after: after,
    error: error
  });

  var state = {
    listener: listener,
    currentName: 'root'
  };

  state.root = create();
  state.current = state.root;

  return state;

  function create () {
    var node = {
      name: state.currentName,
      children: [],
      before: 0,
      after: 0,
      error: 0
    };

    if(state.current) state.current.children.push(node);
    return node;
  }

  function before(ctx, node) {
    state.current = node;
    state.current.before++;
  }

  function after(ctx, node) {
    node.after++;
    state.current = null;
  }

  function error(ctx, node) {
    node.error++;
    state.current = null;
    return false;
  }
}


text:
package com.qunadai.channel.content.ui.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qunadai.channel.R;
import com.qunadai.channel.bean.User;
import com.qunadai.channel.bean.base.BaseBean;
import com.qunadai.channel.content.base.BaseActivity;
import com.qunadai.channel.content.contract.LoginContract;
import com.qunadai.channel.content.presenter.LoginPresenter;
import com.qunadai.channel.content.ui.MainActivity;
import com.qunadai.channel.utils.CodeUtil;
import com.qunadai.channel.utils.CommUtil;
import com.qunadai.channel.utils.LogU;
import com.qunadai.channel.utils.NetworkUtil;
import com.qunadai.channel.utils.PrefUtil;
import com.qunadai.channel.utils.ToastUtil;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;

/**
 * Created by wayne on 2017/5/11.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {
    private LoginPresenter loginPresenter;

    @BindView(R.id.bt_style_pwd)
    Button bt_style_pwd;
    @BindView(R.id.bt_style_sms)
    Button bt_style_sms;

    @BindView(R.id.rl_login_pwd)
    RelativeLayout rl_login_pwd;
    @BindView(R.id.rl_login_sms)
    RelativeLayout rl_login_sms;

    @BindView(R.id.et_login_phone)
    EditText et_login_phone;
    @BindView(R.id.et_login_pwd)
    EditText et_login_pwd;
    @BindView(R.id.et_login_sms)
    EditText et_login_sms;

    @BindView(R.id.bt_get_sms)
    Button bt_get_sms;

    @BindView(R.id.iv_phone_clear)
    ImageView iv_phone_clear;
    @BindView(R.id.iv_pwd_clear)
    ImageView iv_pwd_clear;
    @BindView(R.id.cb_pwd_hide)
    CheckBox cb_pwd_hide;

    @BindView(R.id.bt_login)
    Button bt_login;

    @BindView(R.id.tv_register)
    TextView tv_register;
    @BindView(R.id.tv_forget_password)
    TextView tv_forget_password;

    @BindView(R.id.rl_login_sms_pic)
    RelativeLayout rl_login_sms_pic;
    @BindView(R.id.et_login_sms_pic)
    EditText et_login_sms_pic;
    @BindView(R.id.iv_get_code)
    ImageView iv_get_code;

    //0密码,2验证码
    private int login_type;
    private static final int TYPE_PWD = 0;
    private static final int TYPE_SMS = 2;

    private boolean isRequest;
    private TimeCount time;

    @Override
    protected void updateTopViewHideAndShow() {
//        setTitleBarStatus(TITLE_ON_BACK_ON);
        setTitleText("登录");
    }

    @Override
    protected View createCenterView() {
        View view = View.inflate(this, R.layout.activity_login, null);
        return view;
    }

    @Override
    protected View createBottomView() {
        return null;
    }

    @Override
    protected void initView() {
        loginPresenter = new LoginPresenter(this);
        rl_login_sms.setVisibility(View.GONE);
        rl_login_sms_pic.setVisibility(View.GONE);
        time = new TimeCount(60000, 1000);
        bt_style_pwd.setSelected(true);
        login_type = TYPE_PWD;

        //记住的密码
//        String phone = PrefUtil.getString(this, PrefKey.PHONE, "");
//        et_login_phone.setText(phone);
    }

    View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            iv_phone_clear.setVisibility(View.GONE);
            iv_pwd_clear.setVisibility(View.GONE);

            switch (v.getId()) {
                case R.id.et_login_phone:
                    if (et_login_phone.getText().toString().trim().length() != 0) {
                        iv_phone_clear.setVisibility(View.VISIBLE);
                    }
                    break;
                case R.id.et_login_pwd:
                    if (et_login_pwd.getText().toString().trim().length() != 0) {
                        iv_pwd_clear.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
    };

    @Override
    public void initViewData() {
        //结束其他所有页面
//        AppManager.closeActivityWithout(this);

        bt_style_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换密码模式
                changeType(TYPE_PWD);
            }
        });
        bt_style_sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换短信模式
                changeType(TYPE_SMS);
            }
        });
        et_login_phone.setOnFocusChangeListener(onFocusChangeListener);
        et_login_pwd.setOnFocusChangeListener(onFocusChangeListener);
        et_login_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = et_login_phone.getText().toString().trim();
                String pwd = et_login_pwd.getText().toString().trim();

                if (phone.length() == 0) {
                    iv_phone_clear.setVisibility(View.GONE);
                } else {
                    iv_phone_clear.setVisibility(View.VISIBLE);
                }
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)) {
                    bt_login.setEnabled(false);
                } else {
                    bt_login.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_login_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = et_login_phone.getText().toString().trim();
                String pwd = et_login_pwd.getText().toString().trim();

                if (pwd.length() == 0) {
                    iv_pwd_clear.setVisibility(View.GONE);
                } else {
                    iv_pwd_clear.setVisibility(View.VISIBLE);
                }
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)) {
                    bt_login.setEnabled(false);
                } else {
                    bt_login.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_login_sms.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = et_login_phone.getText().toString().trim();
                String sms = et_login_sms.getText().toString().trim();
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(sms)) {
                    bt_login.setEnabled(false);
                } else {
                    bt_login.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        iv_phone_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_login_phone.setText("");
            }
        });
        iv_pwd_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_login_pwd.setText("");
            }
        });
        bt_get_sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送登录验证码
                String code = CodeUtil.getInstance().getCode();
                String inputCode = CommUtil.getText(et_login_sms_pic);
                if (!code.equalsIgnoreCase(inputCode)) {
                    ToastUtil.showToast(LoginActivity.this, "请填写正确的图形验证码");
                    return;
                }

                if (NetworkUtil.checkNetwork(LoginActivity.this)) {
                    if (isRequest) {
                        ToastUtil.showToast(LoginActivity.this, "请稍后");
                        return;
                    }
                    isRequest = true;
                    String phone = et_login_phone.getText().toString().trim();
                    if (phone.length() == 0) {
                        isRequest = false;
                        ToastUtil.showToast(LoginActivity.this, "请填写正确的手机号");
                        return;
                    }

//                    loginPresenter.requestLoginSms(phone);
                }

            }
        });

        cb_pwd_hide.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int show = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
                int hide = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
                et_login_pwd.setInputType(isChecked ? show : hide);
                // 使光标始终在最后位置
                Editable etable = et_login_pwd.getText();
                Selection.setSelection(etable, etable.length());
            }
        });

        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入注册环节
                Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intentRegister);
            }
        });
        tv_forget_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入忘记密码环节
                Intent intentForget = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                startActivity(intentForget);
            }
        });
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtil.checkNetwork(LoginActivity.this)) {
                    loginSystem();
                }
            }
        });

        //初始化密码是否可见
        int show = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
        int hide = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
        et_login_pwd.setInputType(cb_pwd_hide.isChecked() ? show : hide);

        String phone = et_login_phone.getText().toString().trim();
        String pwd = et_login_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)) {
            bt_login.setEnabled(false);
        } else {
            bt_login.setEnabled(true);
        }

        //图形验证码
        setPicCode();
        iv_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPicCode();

            }
        });
    }

    public void setPicCode() {
        Bitmap b = CodeUtil.getInstance().createBitmap();
        iv_get_code.setImageBitmap(b);
    }

    private void loginSystem() {
        String phone = et_login_phone.getText().toString().trim();
        String pwd = et_login_pwd.getText().toString().trim();
        String sms = et_login_sms.getText().toString().trim();
        if (phone.length() == 0) {
            ToastUtil.showToast(this, "请填写完整");
            return;
        }
        switch (login_type) {
            case TYPE_PWD:
                if (pwd.length() == 0) {
                    ToastUtil.showToast(this, "请填写完整");
                    return;
                }
                String base = phone + ":" + pwd;
                String base64 = Base64.encodeToString(base.getBytes(),Base64.DEFAULT);

                LogU.t("--"+base64);

                loginPresenter.loginByPwd(base64.replace("\n",""));
                break;
            case TYPE_SMS:
                if (sms.length() == 0) {
                    ToastUtil.showToast(this, "请填写完整");
                    return;
                }
//                loginPresenter.loginBySms(phone, sms);
                break;
        }
    }

    private void changeType(int type) {
        login_type = type;
        bt_style_pwd.setSelected(false);
        bt_style_sms.setSelected(false);
        rl_login_pwd.setVisibility(View.GONE);
        rl_login_sms.setVisibility(View.GONE);
        rl_login_sms_pic.setVisibility(View.GONE);

        String phone = et_login_phone.getText().toString().trim();
        String pwd = et_login_pwd.getText().toString().trim();
        String sms = et_login_sms.getText().toString().trim();

        switch (type) {
            case TYPE_PWD:
                bt_style_pwd.setSelected(true);
                rl_login_pwd.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)) {
                    bt_login.setEnabled(false);
                } else {
                    bt_login.setEnabled(true);
                }
                break;
            case TYPE_SMS:
                bt_style_sms.setSelected(true);
                rl_login_sms.setVisibility(View.VISIBLE);
                rl_login_sms_pic.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(sms)) {
                    bt_login.setEnabled(false);
                } else {
                    bt_login.setEnabled(true);
                }
                break;
        }
    }

    /**
     * @Override public void getLoginSms(String msg) {
     * ToastUtil.showToastLong(this, "短信已发送");
     * if (time != null) {
     * time.start();
     * }
     * bt_get_sms.setEnabled(false);
     * }
     * @Override public void getLoginSmsFail(String error) {
     * ToastUtil.showToastLong(this, error);
     * }
     * @Override public void updateView(Object serverData) {
     *

     * }
     * @Override public void updateError(String error) {
     *

     * }
     * @Override public void loginFail(String error) {
     * ToastUtil.showToastLong(this, error);
     * }
     * @Override public void requestStart() {
     * //        ProgressBarUtil.showLoadDialog(this);
     * showLoading();
     * //不用添加view的关闭键盘
     * if (manager != null) {
     * manager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
     * 0);
     * }
     * }
     * @Override public void requestEnd() {
     * isRequest = false;
     * //        ProgressBarUtil.hideLoadDialogDelay(this);
     * hideLoading();
     * }
     */

    private long mPressedTime = 0;

    @Override
    public void onBackPressed() {
        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差
            ToastUtil.showToast(this, "再按一次退出程序");
            mPressedTime = mNowTime;
        } else {
            //退出程序
            finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    public void loginDone(BaseBean<User> bean) {
        ToastUtil.showToastLong(this, "恭喜您,登录成功");
//        EventBus.getDefault().post(new EventClose("main"));

//        PrefUtil.putString(this, PrefUtil.TOKEN, bean.getContent().getUser().g);
//        PrefUtil.putString(this, PrefUtil.PHONE, CommUtil.getText(et_login_phone));
        if (login_type == TYPE_PWD) {
            //密码模式则存2个密码(真假),标记自动登录
            PrefUtil.putString(this, PrefUtil.PWD_ENCODE, CommUtil.shaEncrypt(CommUtil.getText(et_login_pwd)));
            PrefUtil.putString(this, PrefUtil.PWD, CommUtil.getText(et_login_pwd));
            PrefUtil.putBoolean(this, PrefUtil.AUTO_LOGIN, true);
        } else {
            PrefUtil.putBoolean(this, PrefUtil.AUTO_LOGIN, false);
        }

        //延迟500毫秒关闭swipe
        Observable.timer(200, TimeUnit.MILLISECONDS).subscribe(
                new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Intent intentMain = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intentMain);
                                finish();

//                                EventBus.getDefault().post(new EventLogin());
                                finish();
                            }
                        });
                    }
                }
        );
    }

    @Override
    public void loginFail(String error) {
        ToastUtil.showToastLong(this, error);
    }

    @Override
    public void requestStart() {
        showLoading();
    }

    @Override
    public void requestEnd() {
        hideLoading();
    }

    @Override
    public void tokenFail() {

    }

    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // 计时过程显示
            if (bt_get_sms != null) {
                bt_get_sms.setText(millisUntilFinished / 1000 + "s");
            }
        }

        @Override
        public void onFinish() {
            // 计时完毕时触发
            if (bt_get_sms != null) {
                bt_get_sms.setText("获取验证码");
                bt_get_sms.setEnabled(true);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GetAccountActivityResponse xmlns="http://fps.amazonaws.com/doc/2008-09-17/">
  <!--Optional:-->
  <GetAccountActivityResult>
    <!--Optional:-->
    <BatchSize>100</BatchSize>
    <!--Zero or more repetitions:-->
    <Transaction>
      <TransactionId>string</TransactionId>
      <CallerTransactionDate>2008-09-28T18:49:45</CallerTransactionDate>
      <DateReceived>2014-09-18T16:18:33</DateReceived>
      <!--Optional:-->
      <DateCompleted>2006-08-19T10:27:14-07:00</DateCompleted>
      <TransactionAmount>
        <CurrencyCode>string</CurrencyCode>
        <Value>string</Value>
      </TransactionAmount>
      <FPSOperation>string</FPSOperation>
      <TransactionStatus>string</TransactionStatus>
      <!--Optional:-->
      <StatusMessage>string</StatusMessage>
      <!--Optional:-->
      <StatusCode>string</StatusCode>
      <!--Optional:-->
      <OriginalTransactionId>string</OriginalTransactionId>
      <!--1 or more repetitions:-->
      <TransactionPart>
        <!--Optional:-->
        <InstrumentId>string</InstrumentId>
        <Role>string</Role>
        <!--Optional:-->
        <Name>string</Name>
        <!--Optional:-->
        <Reference>string</Reference>
        <!--Optional:-->
        <Description>string</Description>
        <!--Optional:-->
        <FeesPaid>
          <CurrencyCode>string</CurrencyCode>
          <Value>string</Value>
        </FeesPaid>
      </TransactionPart>
      <PaymentMethod>string</PaymentMethod>
      <!--Optional:-->
      <SenderName>string</SenderName>
      <CallerName>string</CallerName>
      <!--Optional:-->
      <RecipientName>string</RecipientName>
      <FPSFees>
        <CurrencyCode>string</CurrencyCode>
        <Value>string</Value>
      </FPSFees>
      <Balance>
        <CurrencyCode>string</CurrencyCode>
        <Value>string</Value>
      </Balance>
      <!--Optional:-->
      <SenderTokenId>string</SenderTokenId>
      <!--Optional:-->
      <RecipientTokenId>string</RecipientTokenId>
    </Transaction>
    <!--Optional:-->
    <StartTimeForNextTransaction>2009-05-16T05:42:28</StartTimeForNextTransaction>
  </GetAccountActivityResult>
  <ResponseMetadata>
    <RequestId>string</RequestId>
  </ResponseMetadata>
</GetAccountActivityResponse>


text:
package designpatternsjava.structural.flyweight;

public class Tree implements IGridItemable
{
	public Tree()
	{
		try
		{
			// ... this could take a long time ...
			Thread.sleep(3000);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void draw()
	{
		System.out.println("Rendering a Tree");
	}
}


text:
package com.sonymobile.tools.gerrit.gerritevents.dto.rest;

import java.util.Collection;
import java.util.HashSet;

//CS IGNORE LineLength FOR NEXT 6 LINES. REASON: JavaDoc.
/**
 * A file with line comments.
 * Added to {@link ReviewInput#ReviewInput(String, Collection, Collection)}
 *
 * @see Gerrit Documentation
 */
public class CommentedFile {
    private final String fileName;
    private final Collection<LineComment> comments;

    /**
     * Standard Constructor.
     *
     * @param fileName file name
     */
    public CommentedFile(String fileName) {
        this.fileName = fileName;
        this.comments = new HashSet<LineComment>();
    }

    /**
     * Standard Constructor.
     *
     * @param fileName file name
     * @param comments comments
     */
    public CommentedFile(String fileName, Collection<LineComment> comments) {
        this(fileName);
        this.comments.addAll(comments);
    }

    /**
     * File name.
     *
     * @return file name
     */
    public String getFileName() {
        return fileName;
    }

    /**
     * Add a LineComment to this file.
     *
     * @param comment the LineComment to add
     * @return true if the comment was added successfully
     */
    public boolean addLineComment(LineComment comment) {
        return comments.add(comment);
    }

    /**
     * all of them.
     *
     * @return line comments
     */
    public Collection<? extends LineComment> getLineComments() {
        return comments;
    }
}


text:
module.exports = function(data, message) {
	return {
		data : data,
		status : '0',
		message : message || 'ok'
	};
};