text:
#ifndef EDGE_ACCELERATION_H_
#define EDGE_ACCELERATION_H_

#include <teb_local_planner/g2o_types/vertex_pose.h>
#include <teb_local_planner/g2o_types/vertex_timediff.h>
#include <teb_local_planner/g2o_types/penalties.h>
#include <teb_local_planner/teb_config.h>
#include <teb_local_planner/g2o_types/base_teb_edges.h>

#include <geometry_msgs/Twist.h>

namespace teb_local_planner
{

/**
 * @class EdgeAcceleration
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration.
 *
 * The edge depends on five vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \mathbf{s}_{ip2}, \Delta T_i, \Delta T_{ip1} \f$ and minimizes:
 * \f$ \min \textrm{penaltyInterval}( [a, omegadot } ]^T ) \cdot weight \f$. \n
 * \e a is calculated using the difference quotient (twice) and the position parts of all three poses \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi]. \n
 * \e weight can be set using setInformation() \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval() \n
 * The dimension of the error / cost vector is 2: the first component represents the translational acceleration and
 * the second one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAccelerationStart
 * @see EdgeAccelerationGoal
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationStart() and EdgeAccelerationGoal() for defining boundary values!
 */
class EdgeAcceleration : public BaseTebMultiEdge<2, double>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAcceleration()
  {
    this->resize(5);
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_, "You must call setTebConfig on EdgeAcceleration()");
    const VertexPose* pose1 = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose2 = static_cast<const VertexPose*>(_vertices[1]);
    const VertexPose* pose3 = static_cast<const VertexPose*>(_vertices[2]);
    const VertexTimeDiff* dt1 = static_cast<const VertexTimeDiff*>(_vertices[3]);
    const VertexTimeDiff* dt2 = static_cast<const VertexTimeDiff*>(_vertices[4]);

    // VELOCITY & ACCELERATION
    const Eigen::Vector2d diff1 = pose2->position() - pose1->position();
    const Eigen::Vector2d diff2 = pose3->position() - pose2->position();

    double dist1 = diff1.norm();
    double dist2 = diff2.norm();
    const double angle_diff1 = g2o::normalize_theta(pose2->theta() - pose1->theta());
    const double angle_diff2 = g2o::normalize_theta(pose3->theta() - pose2->theta());

    if (cfg_->trajectory.exact_arc_length) // use exact arc length instead of Euclidean approximation
    {
        if (angle_diff1 != 0)
        {
            const double radius =  dist1/(2*sin(angle_diff1/2));
            dist1 = fabs( angle_diff1 * radius ); // actual arg length!
        }
        if (angle_diff2 != 0)
        {
            const double radius =  dist2/(2*sin(angle_diff2/2));
            dist2 = fabs( angle_diff2 * radius ); // actual arg length!
        }
    }

    double vel1 = dist1 / dt1->dt();
    double vel2 = dist2 / dt2->dt();

    // consider directions
//     vel1 *= g2o::sign(diff1[0]*cos(pose1->theta()) + diff1[1]*sin(pose1->theta()));
//     vel2 *= g2o::sign(diff2[0]*cos(pose2->theta()) + diff2[1]*sin(pose2->theta()));
    vel1 *= fast_sigmoid( 100*(diff1.x()*cos(pose1->theta()) + diff1.y()*sin(pose1->theta())) );
    vel2 *= fast_sigmoid( 100*(diff2.x()*cos(pose2->theta()) + diff2.y()*sin(pose2->theta())) );

    const double acc_lin  = (vel2 - vel1)*2 / ( dt1->dt() + dt2->dt() );

    _error[0] = penaltyBoundToInterval(acc_lin,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    const double omega1 = angle_diff1 / dt1->dt();
    const double omega2 = angle_diff2 / dt2->dt();
    const double acc_rot  = (omega2 - omega1)*2 / ( dt1->dt() + dt2->dt() );

    _error[1] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAcceleration::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAcceleration::computeError() rotational: _error[1]=%f\n",_error[1]);
  }

#ifdef USE_ANALYTIC_JACOBI
#if 0
  /*
   * @brief Jacobi matrix of the cost function specified in computeError().
   */
  void linearizeOplus()
  {
    ROS_ASSERT_MSG(cfg_, "You must call setTebConfig on EdgeAcceleration()");
    const VertexPointXY* conf1 = static_cast<const VertexPointXY*>(_vertices[0]);
    const VertexPointXY* conf2 = static_cast<const VertexPointXY*>(_vertices[1]);
    const VertexPointXY* conf3 = static_cast<const VertexPointXY*>(_vertices[2]);
    const VertexTimeDiff* deltaT1 = static_cast<const VertexTimeDiff*>(_vertices[3]);
    const VertexTimeDiff* deltaT2 = static_cast<const VertexTimeDiff*>(_vertices[4]);
    const VertexOrientation* angle1 = static_cast<const VertexOrientation*>(_vertices[5]);
    const VertexOrientation* angle2 = static_cast<const VertexOrientation*>(_vertices[6]);
    const VertexOrientation* angle3 = static_cast<const VertexOrientation*>(_vertices[7]);

    Eigen::Vector2d deltaS1 = conf2->estimate() - conf1->estimate();
    Eigen::Vector2d deltaS2 = conf3->estimate() - conf2->estimate();
    double dist1 = deltaS1.norm();
    double dist2 = deltaS2.norm();

    double sum_time = deltaT1->estimate() + deltaT2->estimate();
    double sum_time_inv = 1 / sum_time;
    double dt1_inv = 1/deltaT1->estimate();
    double dt2_inv = 1/deltaT2->estimate();
    double aux0 = 2/sum_time_inv;
    double aux1 = dist1 * deltaT1->estimate();
    double aux2 = dist2 * deltaT2->estimate();

    double vel1 = dist1 * dt1_inv;
    double vel2 = dist2 * dt2_inv;
    double omega1 = g2o::normalize_theta( angle2->estimate() - angle1->estimate() ) * dt1_inv;
    double omega2 = g2o::normalize_theta( angle3->estimate() - angle2->estimate() ) * dt2_inv;
    double acc = (vel2 - vel1) * aux0;
    double omegadot = (omega2 - omega1) * aux0;
    double aux3 = -acc/2;
    double aux4 = -omegadot/2;

    double dev_border_acc = penaltyBoundToIntervalDerivative(acc, tebConfig.robot_acceleration_max_trans,optimizationConfig.optimization_boundaries_epsilon,optimizationConfig.optimization_boundaries_scale,optimizationConfig.optimization_boundaries_order);
    double dev_border_omegadot = penaltyBoundToIntervalDerivative(omegadot, tebConfig.robot_acceleration_max_rot,optimizationConfig.optimization_boundaries_epsilon,optimizationConfig.optimization_boundaries_scale,optimizationConfig.optimization_boundaries_order);

    _jacobianOplus[0].resize(2,2); // conf1
    _jacobianOplus[1].resize(2,2); // conf2
    _jacobianOplus[2].resize(2,2); // conf3
    _jacobianOplus[3].resize(2,1); // deltaT1
    _jacobianOplus[4].resize(2,1); // deltaT2
    _jacobianOplus[5].resize(2,1); // angle1
    _jacobianOplus[6].resize(2,1); // angle2
    _jacobianOplus[7].resize(2,1); // angle3

    if (aux1==0) aux1=1e-20;
    if (aux2==0) aux2=1e-20;

    if (dev_border_acc!=0)
    {
      // TODO: double aux = aux0 * dev_border_acc;
      // double aux123 = aux / aux1;
      _jacobianOplus[0](0,0) = aux0 * deltaS1[0] / aux1 * dev_border_acc; // acc x1
      _jacobianOplus[0](0,1) = aux0 * deltaS1[1] / aux1 * dev_border_acc; // acc y1
      _jacobianOplus[1](0,0) = -aux0 * ( deltaS1[0] / aux1 + deltaS2[0] / aux2 ) * dev_border_acc; // acc x2
      _jacobianOplus[1](0,1) = -aux0 * ( deltaS1[1] / aux1 + deltaS2[1] / aux2 ) * dev_border_acc; // acc y2
      _jacobianOplus[2](0,0) = aux0 * deltaS2[0] / aux2 * dev_border_acc; // acc x3
      _jacobianOplus[2](0,1) = aux0 * deltaS2[1] / aux2 * dev_border_acc; // acc y3
      _jacobianOplus[2](0,0) = 0;
      _jacobianOplus[2](0,1) = 0;
      _jacobianOplus[3](0,0) = aux0 * (aux3 + vel1 * dt1_inv) * dev_border_acc; // acc deltaT1
      _jacobianOplus[4](0,0) = aux0 * (aux3 - vel2 * dt2_inv) * dev_border_acc; // acc deltaT2
    }
    else
    {
      _jacobianOplus[0](0,0) = 0; // acc x1
      _jacobianOplus[0](0,1) = 0; // acc y1
      _jacobianOplus[1](0,0) = 0; // acc x2
      _jacobianOplus[1](0,1) = 0; // acc y2
      _jacobianOplus[2](0,0) = 0; // acc x3
      _jacobianOplus[2](0,1) = 0; // acc y3
      _jacobianOplus[3](0,0) = 0; // acc deltaT1
      _jacobianOplus[4](0,0) = 0; // acc deltaT2
    }

    if (dev_border_omegadot!=0)
    {
      _jacobianOplus[3](1,0) = aux0 * ( aux4 + omega1 * dt1_inv ) * dev_border_omegadot; // omegadot deltaT1
      _jacobianOplus[4](1,0) = aux0 * ( aux4 - omega2 * dt2_inv ) * dev_border_omegadot; // omegadot deltaT2
      _jacobianOplus[5](1,0) = aux0 * dt1_inv * dev_border_omegadot; // omegadot angle1
      _jacobianOplus[6](1,0) = -aux0 * ( dt1_inv + dt2_inv ) * dev_border_omegadot; // omegadot angle2
      _jacobianOplus[7](1,0) = aux0 * dt2_inv * dev_border_omegadot; // omegadot angle3
    }
    else
    {
      _jacobianOplus[3](1,0) = 0; // omegadot deltaT1
      _jacobianOplus[4](1,0) = 0; // omegadot deltaT2
      _jacobianOplus[5](1,0) = 0; // omegadot angle1
      _jacobianOplus[6](1,0) = 0; // omegadot angle2
      _jacobianOplus[7](1,0) = 0; // omegadot angle3
    }

    _jacobianOplus[0](1,0) = 0; // omegadot x1
    _jacobianOplus[0](1,1) = 0; // omegadot y1
    _jacobianOplus[1](1,0) = 0; // omegadot x2
    _jacobianOplus[1](1,1) = 0; // omegadot y2
    _jacobianOplus[2](1,0) = 0; // omegadot x3
    _jacobianOplus[2](1,1) = 0; // omegadot y3
    _jacobianOplus[5](0,0) = 0; // acc angle1
    _jacobianOplus[6](0,0) = 0; // acc angle2
    _jacobianOplus[7](0,0) = 0; // acc angle3
    }
#endif
#endif

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

};

/**
 * @class EdgeAccelerationStart
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration at the beginning of the trajectory.
 *
 * The edge depends on three vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \Delta T_i \f$, an initial velocity defined by setInitialVelocity()
 * and minimizes: \n
 * \f$ \min \textrm{penaltyInterval}( [a, omegadot ]^T ) \cdot weight \f$. \n
 * \e a is calculated using the difference quotient (twice) and the position parts of the poses. \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi].  \n
 * \e weight can be set using setInformation(). \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval(). \n
 * The dimension of the error / cost vector is 2: the first component represents the translational acceleration and
 * the second one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAcceleration
 * @see EdgeAccelerationGoal
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationGoal() for defining boundary values at the end of the trajectory!
 */
class EdgeAccelerationStart : public BaseTebMultiEdge<2, const geometry_msgs::Twist*>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAccelerationStart()
  {
    _measurement = NULL;
    this->resize(3);
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_ && _measurement, "You must call setTebConfig() and setStartVelocity() on EdgeAccelerationStart()");
    const VertexPose* pose1 = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose2 = static_cast<const VertexPose*>(_vertices[1]);
    const VertexTimeDiff* dt = static_cast<const VertexTimeDiff*>(_vertices[2]);

    // VELOCITY & ACCELERATION
    const Eigen::Vector2d diff = pose2->position() - pose1->position();
    double dist = diff.norm();
    const double angle_diff = g2o::normalize_theta(pose2->theta() - pose1->theta());
    if (cfg_->trajectory.exact_arc_length && angle_diff != 0)
    {
        const double radius =  dist/(2*sin(angle_diff/2));
        dist = fabs( angle_diff * radius ); // actual arg length!
    }

    const double vel1 = _measurement->linear.x;
    double vel2 = dist / dt->dt();

    // consider directions
    //vel2 *= g2o::sign(diff[0]*cos(pose1->theta()) + diff[1]*sin(pose1->theta()));
    vel2 *= fast_sigmoid( 100*(diff.x()*cos(pose1->theta()) + diff.y()*sin(pose1->theta())) );

    const double acc_lin  = (vel2 - vel1) / dt->dt();

    _error[0] = penaltyBoundToInterval(acc_lin,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    const double omega1 = _measurement->angular.z;
    const double omega2 = angle_diff / dt->dt();
    const double acc_rot  = (omega2 - omega1) / dt->dt();

    _error[1] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAccelerationStart::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAccelerationStart::computeError() rotational: _error[1]=%f\n",_error[1]);
  }

  /**
   * @brief Set the initial velocity that is taken into account for calculating the acceleration
   * @param vel_start twist message containing the translational and rotational velocity
   */
  void setInitialVelocity(const geometry_msgs::Twist& vel_start)
  {
    _measurement = &vel_start;
  }

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

/**
 * @class EdgeAccelerationGoal
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration at the end of the trajectory.
 *
 * The edge depends on three vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \Delta T_i \f$, an initial velocity defined by setGoalVelocity()
 * and minimizes: \n
 * \f$ \min \textrm{penaltyInterval}( [a, omegadot ]^T ) \cdot weight \f$. \n
 * \e a is calculated using the difference quotient (twice) and the position parts of the poses \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi].  \n
 * \e weight can be set using setInformation() \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval() \n
 * The dimension of the error / cost vector is 2: the first component represents the translational acceleration and
 * the second one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAcceleration
 * @see EdgeAccelerationStart
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationStart() for defining boundary (initial) values at the end of the trajectory
 */
class EdgeAccelerationGoal : public BaseTebMultiEdge<2, const geometry_msgs::Twist*>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAccelerationGoal()
  {
    _measurement = NULL;
    this->resize(3);
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_ && _measurement, "You must call setTebConfig() and setGoalVelocity() on EdgeAccelerationGoal()");
    const VertexPose* pose_pre_goal = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose_goal = static_cast<const VertexPose*>(_vertices[1]);
    const VertexTimeDiff* dt = static_cast<const VertexTimeDiff*>(_vertices[2]);

    // VELOCITY & ACCELERATION

    const Eigen::Vector2d diff = pose_goal->position() - pose_pre_goal->position();
    double dist = diff.norm();
    const double angle_diff = g2o::normalize_theta(pose_goal->theta() - pose_pre_goal->theta());
    if (cfg_->trajectory.exact_arc_length  && angle_diff != 0)
    {
        double radius =  dist/(2*sin(angle_diff/2));
        dist = fabs( angle_diff * radius ); // actual arg length!
    }

    double vel1 = dist / dt->dt();
    const double vel2 = _measurement->linear.x;

    // consider directions
    //vel1 *= g2o::sign(diff[0]*cos(pose_pre_goal->theta()) + diff[1]*sin(pose_pre_goal->theta()));
    vel1 *= fast_sigmoid( 100*(diff.x()*cos(pose_pre_goal->theta()) + diff.y()*sin(pose_pre_goal->theta())) );

    const double acc_lin  = (vel2 - vel1) / dt->dt();

    _error[0] = penaltyBoundToInterval(acc_lin,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    const double omega1 = angle_diff / dt->dt();
    const double omega2 = _measurement->angular.z;
    const double acc_rot  = (omega2 - omega1) / dt->dt();

    _error[1] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAccelerationGoal::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAccelerationGoal::computeError() rotational: _error[1]=%f\n",_error[1]);
  }

  /**
   * @brief Set the goal / final velocity that is taken into account for calculating the acceleration
   * @param vel_goal twist message containing the translational and rotational velocity
   */
  void setGoalVelocity(const geometry_msgs::Twist& vel_goal)
  {
    _measurement = &vel_goal;
  }

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

/**
 * @class EdgeAccelerationHolonomic
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration.
 *
 * The edge depends on five vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \mathbf{s}_{ip2}, \Delta T_i, \Delta T_{ip1} \f$ and minimizes:
 * \f$ \min \textrm{penaltyInterval}( [ax, ay, omegadot } ]^T ) \cdot weight \f$. \n
 * \e ax is calculated using the difference quotient (twice) and the x position parts of all three poses \n
 * \e ay is calculated using the difference quotient (twice) and the y position parts of all three poses \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi]. \n
 * \e weight can be set using setInformation() \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval() \n
 * The dimension of the error / cost vector is 3: the first component represents the translational acceleration (x-dir),
 * the second one the strafing acceleration and the third one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAccelerationHolonomicStart
 * @see EdgeAccelerationHolonomicGoal
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationHolonomicStart() and EdgeAccelerationHolonomicGoal() for defining boundary values!
 */
class EdgeAccelerationHolonomic : public BaseTebMultiEdge<3, double>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAccelerationHolonomic()
  {
    this->resize(5);
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_, "You must call setTebConfig on EdgeAcceleration()");
    const VertexPose* pose1 = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose2 = static_cast<const VertexPose*>(_vertices[1]);
    const VertexPose* pose3 = static_cast<const VertexPose*>(_vertices[2]);
    const VertexTimeDiff* dt1 = static_cast<const VertexTimeDiff*>(_vertices[3]);
    const VertexTimeDiff* dt2 = static_cast<const VertexTimeDiff*>(_vertices[4]);

    // VELOCITY & ACCELERATION
    Eigen::Vector2d diff1 = pose2->position() - pose1->position();
    Eigen::Vector2d diff2 = pose3->position() - pose2->position();

    double cos_theta1 = std::cos(pose1->theta());
    double sin_theta1 = std::sin(pose1->theta());
    double cos_theta2 = std::cos(pose2->theta());
    double sin_theta2 = std::sin(pose2->theta());

    // transform pose2 into robot frame pose1 (inverse 2d rotation matrix)
    double p1_dx =  cos_theta1*diff1.x() + sin_theta1*diff1.y();
    double p1_dy = -sin_theta1*diff1.x() + cos_theta1*diff1.y();
    // transform pose3 into robot frame pose2 (inverse 2d rotation matrix)
    double p2_dx =  cos_theta2*diff2.x() + sin_theta2*diff2.y();
    double p2_dy = -sin_theta2*diff2.x() + cos_theta2*diff2.y();

    double vel1_x = p1_dx / dt1->dt();
    double vel1_y = p1_dy / dt1->dt();
    double vel2_x = p2_dx / dt2->dt();
    double vel2_y = p2_dy / dt2->dt();

    double dt12 = dt1->dt() + dt2->dt();

    double acc_x  = (vel2_x - vel1_x)*2 / dt12;
    double acc_y  = (vel2_y - vel1_y)*2 / dt12;

    _error[0] = penaltyBoundToInterval(acc_x,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);
    _error[1] = penaltyBoundToInterval(acc_y,cfg_->robot.acc_lim_y,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    double omega1 = g2o::normalize_theta(pose2->theta() - pose1->theta()) / dt1->dt();
    double omega2 = g2o::normalize_theta(pose3->theta() - pose2->theta()) / dt2->dt();
    double acc_rot  = (omega2 - omega1)*2 / dt12;

    _error[2] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAcceleration::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAcceleration::computeError() strafing: _error[1]=%f\n",_error[1]);
    ROS_ASSERT_MSG(std::isfinite(_error[2]), "EdgeAcceleration::computeError() rotational: _error[2]=%f\n",_error[2]);
  }

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

};

/**
 * @class EdgeAccelerationHolonomicStart
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration at the beginning of the trajectory.
 *
 * The edge depends on three vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \Delta T_i \f$, an initial velocity defined by setInitialVelocity()
 * and minimizes: \n
 * \f$ \min \textrm{penaltyInterval}( [ax, ay, omegadot ]^T ) \cdot weight \f$. \n
 * \e ax is calculated using the difference quotient (twice) and the x-position parts of the poses. \n
 * \e ay is calculated using the difference quotient (twice) and the y-position parts of the poses. \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi].  \n
 * \e weight can be set using setInformation(). \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval(). \n
 * The dimension of the error / cost vector is 3: the first component represents the translational acceleration,
 * the second one the strafing acceleration and the third one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAccelerationHolonomic
 * @see EdgeAccelerationHolonomicGoal
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationHolonomicGoal() for defining boundary values at the end of the trajectory!
 */
class EdgeAccelerationHolonomicStart : public BaseTebMultiEdge<3, const geometry_msgs::Twist*>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAccelerationHolonomicStart()
  {
    this->resize(3);
    _measurement = NULL;
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_ && _measurement, "You must call setTebConfig() and setStartVelocity() on EdgeAccelerationStart()");
    const VertexPose* pose1 = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose2 = static_cast<const VertexPose*>(_vertices[1]);
    const VertexTimeDiff* dt = static_cast<const VertexTimeDiff*>(_vertices[2]);

    // VELOCITY & ACCELERATION
    Eigen::Vector2d diff = pose2->position() - pose1->position();

    double cos_theta1 = std::cos(pose1->theta());
    double sin_theta1 = std::sin(pose1->theta());

    // transform pose2 into robot frame pose1 (inverse 2d rotation matrix)
    double p1_dx =  cos_theta1*diff.x() + sin_theta1*diff.y();
    double p1_dy = -sin_theta1*diff.x() + cos_theta1*diff.y();

    double vel1_x = _measurement->linear.x;
    double vel1_y = _measurement->linear.y;
    double vel2_x = p1_dx / dt->dt();
    double vel2_y = p1_dy / dt->dt();

    double acc_lin_x  = (vel2_x - vel1_x) / dt->dt();
    double acc_lin_y  = (vel2_y - vel1_y) / dt->dt();

    _error[0] = penaltyBoundToInterval(acc_lin_x,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);
    _error[1] = penaltyBoundToInterval(acc_lin_y,cfg_->robot.acc_lim_y,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    double omega1 = _measurement->angular.z;
    double omega2 = g2o::normalize_theta(pose2->theta() - pose1->theta()) / dt->dt();
    double acc_rot  = (omega2 - omega1) / dt->dt();

    _error[2] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAccelerationStart::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAccelerationStart::computeError() strafing: _error[1]=%f\n",_error[1]);
    ROS_ASSERT_MSG(std::isfinite(_error[2]), "EdgeAccelerationStart::computeError() rotational: _error[2]=%f\n",_error[2]);
  }

  /**
   * @brief Set the initial velocity that is taken into account for calculating the acceleration
   * @param vel_start twist message containing the translational and rotational velocity
   */
  void setInitialVelocity(const geometry_msgs::Twist& vel_start)
  {
    _measurement = &vel_start;
  }

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

/**
 * @class EdgeAccelerationHolonomicGoal
 * @brief Edge defining the cost function for limiting the translational and rotational acceleration at the end of the trajectory.
 *
 * The edge depends on three vertices \f$ \mathbf{s}_i, \mathbf{s}_{ip1}, \Delta T_i \f$, an initial velocity defined by setGoalVelocity()
 * and minimizes: \n
 * \f$ \min \textrm{penaltyInterval}( [ax, ay, omegadot ]^T ) \cdot weight \f$. \n
 * \e ax is calculated using the difference quotient (twice) and the x-position parts of the poses \n
 * \e ay is calculated using the difference quotient (twice) and the y-position parts of the poses \n
 * \e omegadot is calculated using the difference quotient of the yaw angles followed by a normalization to [-pi, pi].  \n
 * \e weight can be set using setInformation() \n
 * \e penaltyInterval denotes the penalty function, see penaltyBoundToInterval() \n
 * The dimension of the error / cost vector is 3: the first component represents the translational acceleration,
 * the second one is the strafing velocity and the third one the rotational acceleration.
 * @see TebOptimalPlanner::AddEdgesAcceleration
 * @see EdgeAccelerationHolonomic
 * @see EdgeAccelerationHolonomicStart
 * @remarks Do not forget to call setTebConfig()
 * @remarks Refer to EdgeAccelerationHolonomicStart() for defining boundary (initial) values at the end of the trajectory
 */
class EdgeAccelerationHolonomicGoal : public BaseTebMultiEdge<3, const geometry_msgs::Twist*>
{
public:

  /**
   * @brief Construct edge.
   */
  EdgeAccelerationHolonomicGoal()
  {
    _measurement = NULL;
    this->resize(3);
  }

  /**
   * @brief Actual cost function
   */
  void computeError()
  {
    ROS_ASSERT_MSG(cfg_ && _measurement, "You must call setTebConfig() and setGoalVelocity() on EdgeAccelerationGoal()");
    const VertexPose* pose_pre_goal = static_cast<const VertexPose*>(_vertices[0]);
    const VertexPose* pose_goal = static_cast<const VertexPose*>(_vertices[1]);
    const VertexTimeDiff* dt = static_cast<const VertexTimeDiff*>(_vertices[2]);

    // VELOCITY & ACCELERATION

    Eigen::Vector2d diff = pose_goal->position() - pose_pre_goal->position();

    double cos_theta1 = std::cos(pose_pre_goal->theta());
    double sin_theta1 = std::sin(pose_pre_goal->theta());

    // transform pose2 into robot frame pose1 (inverse 2d rotation matrix)
    double p1_dx =  cos_theta1*diff.x() + sin_theta1*diff.y();
    double p1_dy = -sin_theta1*diff.x() + cos_theta1*diff.y();

    double vel1_x = p1_dx / dt->dt();
    double vel1_y = p1_dy / dt->dt();
    double vel2_x = _measurement->linear.x;
    double vel2_y = _measurement->linear.y;

    double acc_lin_x  = (vel2_x - vel1_x) / dt->dt();
    double acc_lin_y  = (vel2_y - vel1_y) / dt->dt();

    _error[0] = penaltyBoundToInterval(acc_lin_x,cfg_->robot.acc_lim_x,cfg_->optim.penalty_epsilon);
    _error[1] = penaltyBoundToInterval(acc_lin_y,cfg_->robot.acc_lim_y,cfg_->optim.penalty_epsilon);

    // ANGULAR ACCELERATION
    double omega1 = g2o::normalize_theta(pose_goal->theta() - pose_pre_goal->theta()) / dt->dt();
    double omega2 = _measurement->angular.z;
    double acc_rot  = (omega2 - omega1) / dt->dt();

    _error[2] = penaltyBoundToInterval(acc_rot,cfg_->robot.acc_lim_theta,cfg_->optim.penalty_epsilon);

    ROS_ASSERT_MSG(std::isfinite(_error[0]), "EdgeAccelerationGoal::computeError() translational: _error[0]=%f\n",_error[0]);
    ROS_ASSERT_MSG(std::isfinite(_error[1]), "EdgeAccelerationGoal::computeError() strafing: _error[1]=%f\n",_error[1]);
    ROS_ASSERT_MSG(std::isfinite(_error[2]), "EdgeAccelerationGoal::computeError() rotational: _error[2]=%f\n",_error[2]);
  }

  /**
   * @brief Set the goal / final velocity that is taken into account for calculating the acceleration
   * @param vel_goal twist message containing the translational and rotational velocity
   */
  void setGoalVelocity(const geometry_msgs::Twist& vel_goal)
  {
    _measurement = &vel_goal;
  }

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

}; // end namespace

#endif /* EDGE_ACCELERATION_H_ */


text:
package org.chuchu.sc.service.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"org.chuchu.sc.dao", "org.chuchu.sc.config", "org.chuchu.sc.service"})
public class TestConfig {

}

redpajama_set_name: RedPajamaGithub


text:
package com.google.gerrit.extensions.api.changes;

import java.util.Set;

public class StarsInput {
  public Set<String> add;
  public Set<String> remove;

  public StarsInput() {
  }

  public StarsInput(Set<String> add) {
    this.add = add;
  }

  public StarsInput(Set<String> add, Set<String> remove) {
    this.add = add;
    this.remove = remove;
  }
}


text:
ekeric.github.io
================


text:
import unittest

import ansiblelint.utils as utils

class TestUtils(unittest.TestCase):

    def test_tokenize_blank(self):
        (cmd, args, kwargs) = utils.tokenize("")
        self.assertEqual(cmd, '')
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})

    def test_tokenize_single_word(self):
        (cmd, args, kwargs) = utils.tokenize("vars:")
        self.assertEqual(cmd, "vars")

    def test_tokenize_string_module_and_arg(self):
        (cmd, args, kwargs) = utils.tokenize("hello: a=1")
        self.assertEqual(cmd, "hello")
        self.assertEqual(kwargs, {"a": "1"})

    def test_tokenize_strips_action(self):
        (cmd, args, kwargs) = utils.tokenize("action: hello a=1")
        self.assertEqual(cmd, "hello")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"a": "1"})

    def test_tokenize_more_than_one_arg(self):
        (cmd, args, kwargs) = utils.tokenize("action: whatever bobbins x=y z=x c=3")
        self.assertEqual(cmd, "whatever")
        self.assertEqual(args[0], "bobbins")
        self.assertEqual(args[1], "x=y")
        self.assertEqual(args[2], "z=x")
        self.assertEqual(args[3], "c=3")

    def test_tokenize_command_with_args(self):
        cmd, args, kwargs = utils.tokenize("action: command chdir=wxy creates=zyx tar xzf zyx.tgz")
        self.assertEqual(cmd, "command")
        self.assertEqual(args[0], "tar")
        self.assertEqual(args[1], "xzf")
        self.assertEqual(args[2], "zyx.tgz")
        self.assertEqual(kwargs, {'chdir': 'wxy', 'creates': 'zyx'})

    def test_normalize_simple_command(self):
        task1 = dict(name="hello", action="command chdir=abc echo hello world")
        task2 = dict(name="hello", command="chdir=abc echo hello world")
        self.assertEqual(utils.normalize_task(task1, 'tasks.yml'), utils.normalize_task(task2, 'tasks.yml'))

    def test_normalize_complex_command(self):
        task1 = dict(name="hello", action={'module': 'ec2',
                                           'region': 'us-east1',
                                           'etc': 'whatever'})
        task2 = dict(name="hello", ec2={'region': 'us-east1',
                                        'etc': 'whatever'})
        task3 = dict(name="hello", ec2="region=us-east1 etc=whatever")
        task4 = dict(name="hello", action="ec2 region=us-east1 etc=whatever")
        self.assertEqual(utils.normalize_task(task1, 'tasks.yml'), utils.normalize_task(task2, 'tasks.yml'))
        self.assertEqual(utils.normalize_task(task2, 'tasks.yml'), utils.normalize_task(task3, 'tasks.yml'))
        self.assertEqual(utils.normalize_task(task3, 'tasks.yml'), utils.normalize_task(task4, 'tasks.yml'))

    def test_normalize_args(self):
        task1 = dict(git={'version': 'abc'}, args={'repo': 'blah', 'dest': 'xyz'})
        task2 = dict(git={'version': 'abc', 'repo': 'blah', 'dest': 'xyz'})

        task3 = dict(git='version=abc repo=blah dest=xyz')
        task4 = dict(git=None, args={'repo': 'blah', 'dest': 'xyz', 'version': 'abc'})
        self.assertEqual(utils.normalize_task(task1, 'tasks.yml'), utils.normalize_task(task2, 'tasks.yml'))
        self.assertEqual(utils.normalize_task(task1, 'tasks.yml'), utils.normalize_task(task3, 'tasks.yml'))
        self.assertEqual(utils.normalize_task(task1, 'tasks.yml'), utils.normalize_task(task4, 'tasks.yml'))

    def test_extract_from_list(self):
        block = dict(
                block = [dict(tasks=[dict(name="hello",command="whoami")])],
                test_none = None,
                test_string = 'foo'
        )
        blocks = [block]

        test_list = utils.extract_from_list(blocks, ['block'])
        test_none = utils.extract_from_list(blocks, ['test_none'])

        self.assertEqual(list(block['block']), test_list)
        self.assertEqual(list(), test_none)
        with self.assertRaises(RuntimeError):
            utils.extract_from_list(blocks, ['test_string'])

    def test_simple_template(self):
        v = "{{ playbook_dir }}"
        result = utils.template('/a/b/c', v, dict(playbook_dir='/a/b/c'))
        self.assertEqual(result, "/a/b/c")

    def test_missing_filter(self):
        v = "{{ 'hello' | doesnotexist }}"
        result = utils.template('/a/b/c', v, dict(playbook_dir='/a/b/c'))
        self.assertEqual(result, "{{ 'hello' | doesnotexist }}")

    def test_existing_filter_on_unknown_var(self):
        v = "{{ hello | to_json }}"
        result = utils.template('/a/b/c', v, dict(playbook_dir='/a/b/c'))
        self.assertEqual(result, "{{ hello | to_json }}")

    def test_task_to_str_unicode(self):
        task = dict(fail=dict(msg=u"unicode é ô à"))
        result = utils.task_to_str(utils.normalize_task(task, 'filename.yml'))
        self.assertEqual(result, u"fail msg=unicode é ô à")


text:
import sys
import unittest
import pyauparser

class TestLexer(unittest.TestCase):

    def setUp(self):
        self.grammar_operator = pyauparser.Grammar.load_file("data/operator.egt")
        self.grammar_group = pyauparser.Grammar.load_file("Data/group.egt")

    def test_operator(self):
        src = "1+2*(3/4)"
        dst = ""
        lexer = pyauparser.Lexer(self.grammar_operator)
        lexer.load_string(src)
        while True:
            token = lexer.read_token()
            if   token.symbol == self.grammar_operator.symbol_Error:
                raise Exception()
            elif token.symbol == self.grammar_operator.symbol_EOF:
                break
            dst += token.lexeme
        self.assertEqual(src, dst)

    def test_comment(self):
        lexer = pyauparser.Lexer(self.grammar_group)
        lexer.load_string(
            """
                a // Comment
                /* Block /* Comment "*/ b /* " */
                (* Block (* Comment2 *) " *) c
                [* " *] " [* *] *] d
            """)

        tokens = lexer.read_token_all()
        terminals = [t.lexeme for t in tokens if t.symbol.type == pyauparser.SymbolType.TERMINAL]
        self.assertEqual(terminals, [u'a', u'b', u'c', u'd'])

    def test_html(self):
        lexer = pyauparser.Lexer(self.grammar_group)
        lexer.load_string(
            """
                a=none,
                b=
                <html>
                   <head>
                     <title>Some page</title>
                   </head>
                   </body>
                     This is a tad easier than concatenating a series of strings!
                   </body>
                </html>
            """)

        tokens = lexer.read_token_all()
        terminals = [t.lexeme for t in tokens if t.symbol.type == pyauparser.SymbolType.TERMINAL]
        self.assertEqual(terminals[:-1], [u'a', u'=', u'none', u',', u'b', u'='])
        self.assertEqual(terminals[-1][:6], "<html>")
        self.assertEqual(terminals[-1][-7:], "</html>")

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


text:
package pl.edu.agh.marims.screenstreamer.lib.intent;

import android.content.Intent;
import android.net.Uri;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class IntentReader {
    public static String printIntentParams(Map<String, String> intentParams) {
        StringBuilder builder = new StringBuilder();
        builder.append("Intent params:\n");
        for (String key : intentParams.keySet()) {
            builder.append(key + ": " + intentParams.get(key) + "\n");
        }
        return builder.toString();
    }

    /**
     * Important!
     * Remember to declare a special intent in your app manifest file, it should look like this:
     *

     * <intent-filter>
     * <action android:name="android.intent.action.VIEW"/>
     * <category android:name="android.intent.category.DEFAULT"/>
     * <category android:name="android.intent.category.BROWSABLE"/>
     * <data android:host="runAppWith" android:scheme="marims"/>
     * </intent-filter>
     *

     * Given declaration allows Android System to run your app via URI
     * (e.g. marims://runAppWith?param1=value1&param2=value2)
     *
     * @param intent - should be obtained from app context
     * @return intentParams - parsed intent query parameters
     */
    public static Map<String, String> readIntentParams(Intent intent) {
        Map<String, String> intentParams = new HashMap<String, String>();
        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            Uri uri = intent.getData();
            Set<String> queryParameterNames = uri.getQueryParameterNames();
            for (String parameter : queryParameterNames) {
                intentParams.put(parameter, uri.getQueryParameter(parameter));
            }
        }
        return intentParams;
    }
}


text:
<resources>
    <string name="app_name">GSLayout 排版效果 Demo</string>
    <string name="nav_title_pure_text">纯文本</string>
    <string name="nav_title_rich_text">富文本</string>
    <string name="nav_title_poster">海报</string>
    <string name="helping_line">辅助线</string>
    <string name="vertical_layout">竖排版</string>
    <string name="punctuation_compress">标点压缩</string>
    <string name="system_font">系统字体</string>
    <string name="source_han_sans_font">思源黑体</string>
    <string name="source_han_serif_font">思源宋体</string>
    <string name="font_size_smallest">最小</string>
    <string name="font_size_small">小</string>
    <string name="font_size_middle">中</string>
    <string name="font_size_large">大</string>
    <string name="font_size_largest">最大</string>
    <string name="config_1">配置1</string>
    <string name="config_2">配置2</string>
    <string name="config_3">配置3</string>
</resources>


text:
;( function( $, window, undefined ) {

	'use strict';

	// global
	var Modernizr = window.Modernizr;

	$.Windy = function( options, element ) {

		this.$el = $( element );
		this._init( options );

	};

	// the options
	$.Windy.defaults = {
		// if we want to specify a selector that triggers the next() function. example: '#wi-nav-next'.
		nextEl : '',
		// if we want to specify a selector that triggers the prev() function.
		prevEl : '',
		// rotation and translation boundaries for the items transitions
		boundaries : {
			rotateX : { min : 40 , max : 90 },
			rotateY : { min : -15 , max : 15 },
			rotateZ : { min : -10 , max : 10 },
			translateX : { min : -200 , max : 200 },
			translateY : { min : -400 , max : -200 },
			translateZ : { min : 250 , max : 550 }
		}
	};

	$.Windy.prototype = {

		_init : function( options ) {

			// options
			this.options = $.extend( true, {}, $.Windy.defaults, options );

			// https://github.com/twitter/bootstrap/issues/2870
			this.transEndEventNames = {
				'WebkitTransition' : 'webkitTransitionEnd',
				'MozTransition' : 'transitionend',
				'OTransition' : 'oTransitionEnd',
				'msTransition' : 'MSTransitionEnd',
				'transition' : 'transitionend'
			};
			this.transEndEventName = this.transEndEventNames[ Modernizr.prefixed( 'transition' ) ];

			this.$items = this.$el.children( 'li' );
			this.itemsCount = this.$items.length;

			this.resetTransformStr = 'translateX( 0px ) translateY( 0px ) translateZ( 0px ) rotateX( 0deg ) rotateY( 0deg ) rotateZ( 0deg )';

			this.supportTransitions = Modernizr.csstransitions;
			this.support3d = Modernizr.csstransforms3d;

			// show first item
			this.current = 0;
			this.$items.eq( this.current ).show();

			this._initEvents();

		},
		_getRandTransform : function() {

			return {
				rx : Math.floor( Math.random() * ( this.options.boundaries.rotateX.max - this.options.boundaries.rotateX.min + 1 ) + this.options.boundaries.rotateX.min ),
				ry : Math.floor( Math.random() * ( this.options.boundaries.rotateY.max - this.options.boundaries.rotateY.min + 1 ) + this.options.boundaries.rotateY.min ),
				rz : Math.floor( Math.random() * ( this.options.boundaries.rotateZ.max - this.options.boundaries.rotateZ.min + 1 ) + this.options.boundaries.rotateZ.min ),
				tx : Math.floor( Math.random() * ( this.options.boundaries.translateX.max - this.options.boundaries.translateX.min + 1 ) + this.options.boundaries.translateX.min ),
				ty : Math.floor( Math.random() * ( this.options.boundaries.translateY.max - this.options.boundaries.translateY.min + 1 ) + this.options.boundaries.translateY.min ),
				tz : Math.floor( Math.random() * ( this.options.boundaries.translateZ.max - this.options.boundaries.translateZ.min + 1 ) + this.options.boundaries.translateZ.min )
			};

		},
		_initEvents : function() {

			var self = this;

			this.$items.on( this.transEndEventName, function( event ) {

				self._onTransEnd( $( this ) );

			} );

			if( this.options.nextEl !== '' ) {

				$( this.options.nextEl ).on( 'click.windy', function() {

					self.next();
					return false;

				} );

			}

			if( this.options.prevEl !== '' ) {

				$( this.options.prevEl ).on( 'click.windy', function() {

					self.prev();
					return false;

				} );

			}

		},
		_onTransEnd : function( el ) {

			el.removeClass( 'wi-move' );

			if( el.data( 'dir' ) === 'right' ) {

				var styleStart = {
					zIndex : 1,
					opacity : 1
				};

				if( this.support3d ) {

					styleStart.transform = this.resetTransformStr;

				}
				else if( this.supportTransitions ) {

					styleStart.left = 0;
					styleStart.top = 0;

				}

				el.hide().css( styleStart );

			}

		},
		// public method: shows item with index idx
		navigate : function( idx ) {

			var self = this,
				// current item
				$current = this.$items.eq( this.current ),
				// next item to be shown
				$next = this.$items.eq( idx ),
				// random transformation configuration
				randTranform = this._getRandTransform(),
				// the z-index is higher for the first items so that the ordering is correct if more items are moving at the same time
				styleEnd = {
					zIndex : this.itemsCount + 1 - idx,
					opacity : 0
				},
				styleStart = {
					opacity : 1
				};

			if( this.support3d ) {

				styleStart.transform = self.resetTransformStr;
				styleEnd.transform = 'translateX(' + randTranform.tx + 'px) translateY(' + randTranform.ty + 'px) translateZ(' + randTranform.tz + 'px) rotateX(' + randTranform.rx + 'deg) rotateY(' + randTranform.ry + 'deg) rotateZ(' + randTranform.rz + 'deg)';

			}
			else if( this.supportTransitions ) {

				styleStart.left = 0;
				styleStart.top = 0;
				styleEnd.left = randTranform.tx;
				styleEnd.top = randTranform.ty;

			}

			// if navigating to the right..
			if( idx > this.current ) {

				// if last step was to go to the left..
				if( this.dir === 'left') {

					// reset all z-indexes and hide items except the current
					this.$items.not( $current ).css( 'z-index', 1 ).hide();

				}

				this.dir = 'right';

				$current.addClass( 'wi-move' )
						.data( 'dir', 'right' )
						.css( styleEnd );

				if( $next.hasClass( 'wi-move' ) ) {

					$next.removeClass( 'wi-move' );

				}

				// apply styleStart just to make sure..
				$next.css( styleStart ).show();

				if( !this.supportTransitions ) {

					this._onTransEnd( $current );

				}

			}
			else if( idx < this.current ) {

				this.dir = 'left';

				$next.data( 'dir', 'left' ).css( styleEnd ).show();

				setTimeout( function() {

					$next.addClass( 'wi-move' )
						 .data( 'dir', 'left' )
						 .css( styleStart );

					if( !self.supportTransitions ) {

						self._onTransEnd( $next );

					}

				}, 20 );

			}

			this.current = idx;

		},
		// public method: returns total number of items
		getItemsCount : function() {

			return this.itemsCount;

		},
		// public method: shows next item
		next : function() {

			if( this.current < this.itemsCount - 1 ) {

				var idx = this.current + 1;
				this.navigate( idx );

			}

		},
		// public method: shows previous item
		prev : function() {

			if( this.current > 0 ) {

				var idx = this.current - 1;
				this.navigate( idx );

			}

		}

	};

	var logError = function( message ) {

		if ( window.console ) {

			window.console.error( message );

		}

	};

	$.fn.windy = function( options ) {

		var instance = $.data( this, 'windy' );

		if ( typeof options === 'string' ) {

			var args = Array.prototype.slice.call( arguments, 1 );

			this.each(function() {

				if ( !instance ) {

					logError( "cannot call methods on windy prior to initialization; " +
					"attempted to call method '" + options + "'" );
					return;

				}

				if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {

					logError( "no such method '" + options + "' for windy instance" );
					return;

				}

				instance[ options ].apply( instance, args );

			});

		}
		else {

			this.each(function() {

				if ( instance ) {

					instance._init();

				}
				else {

					instance = $.data( this, 'windy', new $.Windy( options, this ) );

				}

			});

		}

		return instance;

	};

} )( jQuery, window );


text:
package org.apereo.cas.web.flow;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.webflow.engine.Flow;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link DefaultLoginWebflowConfigurerTests}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@Tag("Webflow")
public class DefaultLoginWebflowConfigurerTests extends BaseWebflowConfigurerTests {
    @Test
    public void verifyOperation() {
        assertFalse(casWebflowExecutionPlan.getWebflowConfigurers().isEmpty());
        val flow = (Flow) this.loginFlowDefinitionRegistry.getFlowDefinition(CasWebflowConfigurer.FLOW_ID_LOGIN);
        assertNotNull(flow);
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_CREATE_TICKET_GRANTING_TICKET));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_SEND_TICKET_GRANTING_TICKET));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_GENERATE_SERVICE_TICKET));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_HANDLE_AUTHN_FAILURE));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_POST_VIEW));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_REDIRECT));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_SERVICE_AUTHZ_CHECK));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_VIEW_REDIR_UNAUTHZ_URL));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_VIEW_SERVICE_ERROR));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_GATEWAY_REQUEST_CHECK));
        assertTrue(flow.containsState(CasWebflowConstants.STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS));
    }
}


text:
package net.arcation.allegiance.listeners;

import net.arcation.allegiance.Allegiance;
import net.arcation.allegiance.data.PlayerData;
import net.arcation.allegiance.targets.BlockTarget;
import net.arcation.allegiance.targets.BlockTargetType;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;

import java.util.*;

/**
 * Created by Mr_Little_Kitty on 3/2/2017.
 */
public class BlockTargetListeners implements Listener
{
	private Allegiance allegiance;

	//TODO---Currently not possible to have more than one target per block type
	//You cant have different targets for different wool colors etc
	private EnumMap<BlockTargetType,Map<Material,BlockTarget>> targetMap;

	public BlockTargetListeners(Allegiance allegiance)
	{
		this.allegiance = allegiance;
		Bukkit.getPluginManager().registerEvents(this,allegiance);
		targetMap = new EnumMap<BlockTargetType, Map<Material, BlockTarget>>(BlockTargetType.class);
	}

	public void addBlockTarget(BlockTargetType type, BlockTarget target)
	{
		//Woah lambdas are cool
		Map<Material, BlockTarget> map = targetMap.computeIfAbsent(type, k -> new HashMap<>());
		map.put(target.getMaterial(),target);
	}

	@EventHandler(priority = EventPriority.MONITOR)
	public void onPlace(BlockPlaceEvent event)
	{
		checkEvent(BlockTargetType.PLACE,event.getBlockPlaced(),event.getPlayer().getUniqueId());
	}

	@EventHandler(priority = EventPriority.MONITOR)
	public void onBreak(BlockBreakEvent event)
	{
		checkEvent(BlockTargetType.BREAK,event.getBlock(),event.getPlayer().getUniqueId());
	}

	private void checkEvent(BlockTargetType type, Block block, UUID uuid)
	{
		Map<Material,BlockTarget> map = targetMap.get(type);
		if(map != null)
		{
			BlockTarget target = map.get(block.getType()); //Check if there is a target for this specific block
			if(target != null)
			{
				PlayerData data = allegiance.getPlayer(uuid);
				if(data.increaseTarget(target,1))
					allegiance.announcePlayerAllegiance(Bukkit.getPlayer(uuid));
			}

			target = map.get(Material.AIR); //Check if there is an "all" target and increment if there is
			if(target != null)
			{
				PlayerData data = allegiance.getPlayer(uuid);
				if(data.increaseTarget(target,1))
					allegiance.announcePlayerAllegiance(Bukkit.getPlayer(uuid));
			}
		}
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:weightSum="100"
    tools:context=".ConnectionActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Device is"
        android:id="@+id/textView"
        android:layout_weight="10"
        android:gravity="center"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Offline"
        android:id="@+id/textViewDeviceConnectivity"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="28sp"
        android:layout_weight="20"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/color_off" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_weight="10"
        android:gravity="center"
        android:weightSum="10">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Mobile data"
            android:id="@+id/textView3"
            android:layout_weight="5"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="OFF"
            android:id="@+id/textViewMobileData"
            android:textStyle="bold"
            android:layout_weight="5"
            android:gravity="right"
            android:textColor="@color/color_off" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="10"
        android:gravity="center"
        android:weightSum="10">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="WiFi"
            android:id="@+id/textView7"
            android:layout_weight="5"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="OFF"
            android:id="@+id/textViewWifi"
            android:textStyle="bold"
            android:layout_weight="5"
            android:gravity="right"
            android:textColor="@color/color_off" />
    </LinearLayout>

</LinearLayout>


text:
using System;
using System.Web.UI;
using GSoft.Dynamite.Examples.Utilities;

namespace GSoft.Dynamite.Examples.Parts.ControlTemplates
{
    /// <summary>
    /// Includes the script links for the project's Javascript
    /// </summary>
    public partial class ProjectScripts : UserControl
    {
        /// <summary>
        /// Fires when the page loads
        /// </summary>
        /// <param name="sender">Originator of event</param>
        /// <param name="e">Event arguments</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Add version tag to JS link
            this.ProjectScriptLink.Name = this.ProjectScriptLink.Name + "?v=" + VersionContext.CurrentVersionTag;
        }
    }
}


text:
require 'minitest_helper'

unless ENV['TV_MONGO_SERVER']
  ENV['TV_MONGO_SERVER'] = "127.0.0.1:27017"
end

if defined?(::BSON::VERSION) and (BSON::VERSION < "2.0")
  describe "Mongo" do
    before do
      clear_all_traces

      @mongo_server = ENV['TV_MONGO_SERVER'].split(':')[0]
      @mongo_port   = ENV['TV_MONGO_SERVER'].split(':')[1]

      @connection = Mongo::Connection.new(@mongo_server, @mongo_port, :slave_ok => true)
      @db = @connection.db("test-#{ENV['RACK_ENV']}")

      @collections = @db.collection_names
      @db.create_collection("testCollection") unless @collections.include? "testCollection"

      # These are standard entry/exit KVs that are passed up with all mongo operations
      @entry_kvs = {
        'Layer' => 'mongo',
        'Label' => 'entry',
        'Flavor' => 'mongodb',
        'Database' => 'test-test',
        'RemoteHost' => @mongo_server,
        'RemotePort' => @mongo_port }

      @exit_kvs = { 'Layer' => 'mongo', 'Label' => 'exit' }
      @collect_backtraces = TraceView::Config[:mongo][:collect_backtraces]
    end

    after do
      TraceView::Config[:mongo][:collect_backtraces] = @collect_backtraces
    end

    it 'Stock Mongo should be loaded, defined and ready' do
      defined?(::Mongo).wont_match nil
      defined?(::Mongo::DB).wont_match nil
      defined?(::Mongo::Cursor).wont_match nil
      defined?(::Mongo::Collection).wont_match nil
    end

    it 'Mongo should have traceview methods defined' do
      TraceView::Inst::Mongo::DB_OPS.each do |m|
        ::Mongo::DB.method_defined?("#{m}_with_traceview").must_equal true
      end
      TraceView::Inst::Mongo::CURSOR_OPS.each do |m|
        ::Mongo::Cursor.method_defined?("#{m}_with_traceview").must_equal true
      end
      TraceView::Inst::Mongo::COLL_WRITE_OPS.each do |m|
        ::Mongo::Collection.method_defined?("#{m}_with_traceview").must_equal true
      end
      TraceView::Inst::Mongo::COLL_QUERY_OPS.each do |m|
        ::Mongo::Collection.method_defined?("#{m}_with_traceview").must_equal true
      end
      TraceView::Inst::Mongo::COLL_INDEX_OPS.each do |m|
        ::Mongo::Collection.method_defined?("#{m}_with_traceview").must_equal true
      end
      ::Mongo::Collection.method_defined?(:traceview_collect).must_equal true
    end

    it "should trace create_collection" do
      TraceView::API.start_trace('mongo_test', '', {}) do
        @db.create_collection("create_and_drop_collection_test")
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['QueryOp'].must_equal "create_collection"
      traces[1]['New_Collection_Name'].must_equal "create_and_drop_collection_test"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
    end

    it "should trace drop_collection" do
      # Create a collection so we have one to drop
      @db.create_collection("create_and_drop_collection_test")

      TraceView::API.start_trace('mongo_test', '', {}) do
        @db.drop_collection("create_and_drop_collection_test")
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['QueryOp'].must_equal "drop_collection"
      traces[1]['Collection'].must_equal "create_and_drop_collection_test"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
    end

    it "should trace count" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.count(:query => {:name => "MyName"})
      end

      traces = get_all_traces
      traces.count.must_equal 6

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[3]['QueryOp'].must_equal "count"
    end

    it "should trace find_and_modify" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.find_and_modify({ :query => { :name => "MyName" }, :update => { :count => 203 }})
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "find_and_modify"
      traces[1]['Update_Document'].must_equal "{:count=>203}"
    end

    it "should trace insert" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        doc = {"name" => "MyName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
        coll.insert(doc)
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "insert"
      # Don't test exact hash value since to_json hash ordering varies between 1.8.7 and 1.9+
      traces[1].has_key?('Query').must_equal true
    end

    it "should trace map_reduce" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        map    = "function() { emit(this.name, 1); }"
        reduce = "function(k, vals) { var sum = 0; for(var i in vals) sum += vals[i]; return sum; }"
        coll.map_reduce(map, reduce, { :out => "mr_results", :limit => 100, :read => :primary })
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "map_reduce"
      traces[1]['Map_Function'].must_equal "function() { emit(this.name, 1); }"
      traces[1]['Reduce_Function'].must_equal "function(k, vals) { var sum = 0; for(var i in vals) sum += vals[i]; return sum; }"
      traces[1]['Limit'].must_equal "100"
    end

    it "should trace remove" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.remove(:name => "SaveOp")
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "remove"
      traces[1]['Query'].must_equal "{\"name\":\"SaveOp\"}"
    end

    it "should trace rename" do
      coll = @db.collection("testCollection")
      new_name = (0...10).map{ ('a'..'z').to_a[rand(26)] }.join

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.rename(new_name)
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "rename"
      traces[1]['New_Collection_Name'].must_equal new_name

      # Clean up after test and set collection name back to original
      coll.rename("testCollection")
    end

    it "should trace update" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        # Two types of update calls
        coll.update({"_id" => 1}, { "$set" => {"name" => "MongoDB Ruby"}}, :multi => true)

        doc = {"name" => "MyOtherName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
        coll.update({"_id" => 1}, doc)
      end

      traces = get_all_traces
      traces.count.must_equal 6

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "update"
      traces[1]['Query'].must_equal "{\"_id\":1}"

      validate_event_keys(traces[3], @entry_kvs)
      validate_event_keys(traces[4], @exit_kvs)

      traces[3].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[3]['QueryOp'].must_equal "update"
      traces[3]['Query'].must_equal "{\"_id\":1}"
    end

    it "should trace distinct" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.distinct("count")
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "distinct"
    end

    it "should trace find" do
      coll = @db.collection("testCollection")
      result = nil

      # Insert a doc to assure we get a result
      doc = {"name" => "MyName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
      coll.insert(doc)

      # If given an optional block +find+ will yield a Cursor to that block,
      # close the cursor, and then return nil. This guarantees that partially
      # evaluated cursors will be closed. If given no block +find+ returns a
      # cursor.
      # https://github.com/mongodb/mongo-ruby-driver/blob/1.10.1/lib/mongo/collection.rb#L178

      TraceView::API.start_trace('mongo_test', '', {}) do
        result = coll.find(:name => "MyName", :limit => 1)
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      result.wont_match nil
      result.is_a?(Mongo::Cursor).must_equal true
      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "find"
      traces[1].has_key?('Query').must_equal true
      traces[1]['Limit'].must_equal "1"
    end

    it "should trace find (with block)" do
      coll = @db.collection("testCollection")
      result = []

      # Insert a doc to assure we get a result
      doc = {"name" => "MyName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
      coll.insert(doc)

      # If given an optional block +find+ will yield a Cursor to that block,
      # close the cursor, and then return nil. This guarantees that partially
      # evaluated cursors will be closed. If given no block +find+ returns a
      # cursor.
      # https://github.com/mongodb/mongo-ruby-driver/blob/1.10.1/lib/mongo/collection.rb#L178

      TraceView::API.start_trace('mongo_test', '', {}) do
        blk = lambda { |x| x }
        result = coll.find(:name => "MyName", :limit => 10, &blk)
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      result.must_equal nil
      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "find"
      traces[1].has_key?('Query').must_equal true
    end

    it "should trace group" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.group( :key =>  :type,
                    :cond => { :count => 1 },
                    :initial =>  { :count => 0 },
                    :reduce => 'function(obj,prev) { prev.count += obj.c; }')
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "group"
      # Don't test exact hash value since to_json hash ordering varies between 1.8.7 and 1.9+
      traces[1].has_key?('Query').must_equal true
    end

    it "should trace create, ensure and drop index" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.create_index("i")
        coll.ensure_index("i")
        coll.drop_index("i_1")
      end

      traces = get_all_traces
      traces.count.must_equal 8

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "create_index"

      validate_event_keys(traces[3], @entry_kvs)
      validate_event_keys(traces[4], @exit_kvs)

      traces[3]['Collection'].must_equal "testCollection"
      traces[3].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[3]['QueryOp'].must_equal "ensure_index"

      validate_event_keys(traces[5], @entry_kvs)
      validate_event_keys(traces[6], @exit_kvs)

      traces[5]['Collection'].must_equal "testCollection"
      traces[5].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[5]['QueryOp'].must_equal "drop_index"
    end

    it "should trace drop_indexes" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.drop_indexes
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "drop_indexes"
    end

    it "should trace index_information" do
      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        coll.index_information
      end

      traces = get_all_traces
      traces.count.must_equal 4

      validate_outer_layers(traces, 'mongo_test')
      validate_event_keys(traces[1], @entry_kvs)
      validate_event_keys(traces[2], @exit_kvs)

      traces[1]['Collection'].must_equal "testCollection"
      traces[1].has_key?('Backtrace').must_equal TraceView::Config[:mongo][:collect_backtraces]
      traces[1]['QueryOp'].must_equal "index_information"
    end

    it "should obey :collect_backtraces setting when true" do
      TraceView::Config[:mongo][:collect_backtraces] = true

      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        doc = {"name" => "MyName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
        coll.insert(doc)
      end

      traces = get_all_traces
      layer_has_key(traces, 'mongo', 'Backtrace')
    end

    it "should obey :collect_backtraces setting when false" do
      TraceView::Config[:mongo][:collect_backtraces] = false

      coll = @db.collection("testCollection")

      TraceView::API.start_trace('mongo_test', '', {}) do
        doc = {"name" => "MyName", "type" => "MyType", "count" => 1, "info" => {"x" => 203, "y" => '102'}}
        coll.insert(doc)
      end

      traces = get_all_traces
      layer_doesnt_have_key(traces, 'mongo', 'Backtrace')
    end
  end
end


text:
import angular from 'angular';
import _ from 'lodash';

describe('karma tests with chai', function() {
    it('should expose the Chai assert method', function() {
        assert.ok('everything', 'everything is ok');
    });

    it('should expose the Chai expect method', function() {
        expect('foo').to.not.equal('bar');
    });
});

describe('just checking that libraries work', function() {

    it('works for lodash', function() {
        expect(_.size([1, 2, 3])).to.equal(3);
    });

    it('works for angular', function() {
        expect(angular).to.exist;
    });
});


text:
<?php

namespace frontend\controllers\adver;

use Yii;
use yii\base\Action;
use common\models\adver\Adver;
use common\models\gallery\Gallery;
use common\models\attachment\Attachment;
use yii\helpers\Json;
use yii\helpers\Html;

class InfoWindow extends Action {

	public function run($ids) {

		$cacheKey = __NAMESPACE__ . __CLASS__ . 'infowindow' . $ids;
		$ids = explode('-', $ids);
		$makeCacheParam = [];
		foreach ($ids as $id) {
			$makeCacheParam[':p' . $id] = $id;
		}
		$makeCacheParam[':status'] = Adver::STATUS_ACTIVE;
		$cacheWhere = implode(',', array_keys($makeCacheParam));
		$cache = Yii::$app->getCache();

		if (!$model = $cache->get($cacheKey)) {
			$model = Adver::find()
					->select([
						'id',
						'category_id',
						'country_id',
						'province_id',
						'city_id',
						'city_id',
						'user_id',
						'title',
						'address',
						'lang'
					])
					->with([
						/* 'attachment' => function($query){
						  $query->select([
						  'id',
						  'adver_id',
						  'name',
						  'title'
						  ]);
						  }, */
						'gallery' => function($query) {
							$query->select([
								'id',
								'adver_id',
								'name',
								'title'
							]);
						},
						'category' => function($query) {
							$query->select([
								'id',
								'name',
							]);
						},
						'country' => function($query) {
							$query->select([
								'id',
								'name',
							]);
						},
						'province' => function($query) {
							$query->select([
								'id',
								'name',
							]);
						},
						'city' => function($query) {
							$query->select([
								'id',
								'name',
							]);
						},
					])
						->andWhere(['id' => $ids])
						->andWhere(['status' => Adver::STATUS_ACTIVE])
						->asArray()->all();

				$cache->set($cacheKey, $model, 2592000, new \yii\caching\DbDependency([
					'sql' => "SELECT MAX([[updated_at]]) FROM {{%adver}} WHERE [[id]] IN ({$cacheWhere})",
					'params' => $makeCacheParam
				]));
			}

			$newModel = [];
			foreach ($model as $key => $value) {
				$address = '';
				if (isset($model[$key]['country']['name']) && $model[$key]['country']['name'] != '')
					$address .= $model[$key]['country']['name'] . ', ';
				if (isset($model[$key]['province']['name']) && $model[$key]['province']['name'] != '')
					$address .= $model[$key]['province']['name'] . ', ';
				if (isset($model[$key]['city']['name']) && $model[$key]['city']['name'] != '')
					$address .= $model[$key]['city']['name'] . ', ';
				$address = rtrim($address, ', ');
				$newModel[$key]['full_address'] = Html::encode($address);
				$newModel[$key]['address'] = Html::encode($model[$key]['address']);
				$newModel[$key]['title'] = Html::encode($model[$key]['title']);
				$newModel[$key]['category'] = Html::encode($model[$key]['category']['name']);
				$newModel[$key]['url'] = Adver::generateLink($model[$key]['id'], $model[$key]['title'], $model[$key]['category']['name'], $model[$key]['country']['name'], $model[$key]['province']['name'], $model[$key]['city']['name'], $model[$key]['address'], $model[$key]['lang']);

				$newGallery = [];
				foreach ($value['gallery'] as $gallery) {
					$newGallery[] = [
						'url' => Gallery::getImageUrlFromOutside($gallery['name'], $gallery['adver_id'], 160, 105),
						'title' => Html::encode($gallery['title']),
						'adver_id' => $gallery['adver_id'],
					];
				}
				$newModel[$key]['gallery'] = $newGallery;
			}

			return Json::encode($newModel);
	}
}


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: oneview_fcoe_network_facts
short_description: Retrieve the facts about one or more of the OneView FCoE Networks
description:
    - Retrieve the facts about one or more of the FCoE Networks from OneView.
version_added: "2.4"
requirements:
    - hpOneView >= 2.0.1
author:
    - Felipe Bulsoni (@fgbulsoni)
    - Thiago Miotto (@tmiotto)
    - Adriane Cardozo (@adriane-cardozo)
options:
    name:
      description:
        - FCoE Network name.
extends_documentation_fragment:
    - oneview
    - oneview.factsparams
'''

EXAMPLES = '''
- name: Gather facts about all FCoE Networks
  oneview_fcoe_network_facts:
    config: /etc/oneview/oneview_config.json
  delegate_to: localhost

- debug: var=fcoe_networks

- name: Gather paginated, filtered and sorted facts about FCoE Networks
  oneview_fcoe_network_facts:
    config: /etc/oneview/oneview_config.json
    params:
      start: 0
      count: 3
      sort: 'name:descending'
      filter: 'vlanId=2'
  delegate_to: localhost

- debug: var=fcoe_networks

- name: Gather facts about a FCoE Network by name
  oneview_fcoe_network_facts:
    config: /etc/oneview/oneview_config.json
    name: Test FCoE Network Facts
  delegate_to: localhost

- debug: var=fcoe_networks
'''

RETURN = '''
fcoe_networks:
    description: Has all the OneView facts about the FCoE Networks.
    returned: Always, but can be null.
    type: dict
'''

from ansible.module_utils.oneview import OneViewModuleBase

class FcoeNetworkFactsModule(OneViewModuleBase):
    def __init__(self):
        argument_spec = dict(
            name=dict(type='str'),
            params=dict(type='dict'),
        )

        super(FcoeNetworkFactsModule, self).__init__(additional_arg_spec=argument_spec)

    def execute_module(self):

        if self.module.params['name']:
            fcoe_networks = self.oneview_client.fcoe_networks.get_by('name', self.module.params['name'])
        else:
            fcoe_networks = self.oneview_client.fcoe_networks.get_all(**self.facts_params)

        return dict(changed=False,
                    ansible_facts=dict(fcoe_networks=fcoe_networks))

def main():
    FcoeNetworkFactsModule().run()

if __name__ == '__main__':
    main()


text:
sub checkNotifyRule {
	my ($notifyRule) = @_;
	if (length($notifyRule) == 0) {return("Please enter a Notify Rule");}
}

sub securityCheckTemplateName {
	my ($adminName, $templateName) = @_;
	if (length($templateName) == 0) {die('Error: missing required value for $templateName');}
	if(!(-e "$perfhome/var/db/users/$adminName/alertTemplates/$templateName.ser")) {die('Error: invalid value for $templateName: no template file');}
}

1;


text:
<!doctype html>

  <meta charset='utf-8'>
  <title>seisplotjs.seedcodec 2.0.1 | Documentation</title>
  <meta name='description' content='Javascript library for parsing, manipulating and displaying seismic data.'>
  <meta name='viewport' content='width=device-width,initial-scale=1'>
  <link href='assets/bass.css' rel='stylesheet'>
  <link href='assets/style.css' rel='stylesheet'>
  <link href='assets/github.css' rel='stylesheet'>
  <link href='assets/split.css' rel='stylesheet'>

seisplotjs.seedcodec

2.0.1

          <input
            placeholder='Filter'
            id='filter-input'
            class='col12 block input'
            spellcheck='false'
            autocapitalize='off'
            autocorrect='off'
            type='text' />

                  ASCII

                  SHORT

                  INT24

                  INTEGER

                  FLOAT

                  DOUBLE

                  STEIM1

                  STEIM2

                  CDSN

                  SRO

                  DWWSSN

                  CodecException

                  UnsupportedCompressionType

                  isFloatCompression

                  EncodedDataSegment
                  ▸

Instance members

                        #compressionType

                        #dataView

                        #numSamples

                        #littleEndian

                        #isFloatCompression

                        #decode

                  decompress

                  decodeSteim1

                  decodeSteim2

            Need help reading this?

      ASCII

      src/seedcodec.js

ascii

ASCII

      Type:
      number

      SHORT

      src/seedcodec.js

16 bit integer, or java short

SHORT

      Type:
      number

      INT24

      src/seedcodec.js

24 bit integer

INT24

      Type:
      number

      INTEGER

      src/seedcodec.js

32 bit integer, or java int

INTEGER

      Type:
      number

      FLOAT

      src/seedcodec.js

ieee float

FLOAT

      Type:
      number

      DOUBLE

      src/seedcodec.js

ieee double

DOUBLE

      Type:
      number

      STEIM1

      src/seedcodec.js

Steim1 compression

STEIM1

      Type:
      number

      STEIM2

      src/seedcodec.js

Steim2 compression

STEIM2

      Type:
      number

      CDSN

      src/seedcodec.js

CDSN 16 bit gain ranged

CDSN

      Type:
      number

      SRO

      src/seedcodec.js

(A)SRO

SRO

      Type:
      number

      DWWSSN

      src/seedcodec.js

DWWSSN 16 bit

DWWSSN

      Type:
      number

      CodecException

      src/seedcodec.js

new CodecException(message: string)

      Extends

        Error

Parameters

            message (string)

      UnsupportedCompressionType

      src/seedcodec.js

new UnsupportedCompressionType(message: string)

      Extends

        Error

Parameters

            message (string)

      isFloatCompression

      src/seedcodec.js

isFloatCompression(compressionType: number): boolean

Parameters

            compressionType (number)

Returns

      boolean

      EncodedDataSegment

      src/seedcodec.js

A holder for compressed data independent of the file format.

new EncodedDataSegment(compressionType: number, dataView: DataView, numSamples: number, littleEndian: boolean)

Parameters

            compressionType (number)

            dataView (DataView)

            numSamples (number)

            littleEndian (boolean)

Instance Members

            ▸
            compressionType

      src/seedcodec.js

compressionType

      Type:
      number

            ▸
            dataView

      src/seedcodec.js

dataView

      Type:
      DataView

            ▸
            numSamples

      src/seedcodec.js

numSamples

      Type:
      number

            ▸
            littleEndian

      src/seedcodec.js

littleEndian

      Type:
      boolean

            ▸
            isFloatCompression()

      src/seedcodec.js

isFloatCompression(): boolean

Returns

      boolean

            ▸
            decode()

      src/seedcodec.js

decode(): (Int32Array | Float32Array | Float64Array)

Returns

      (Int32Array | Float32Array | Float64Array)

      decompress

      src/seedcodec.js

Decompress the samples from the provided DataView and
return an array of the decompressed values.
Only 16 bit short, 32 bit int, 32 bit float and 64 bit double
along with Steim1 and Steim2 are supported.

decompress(compressionType: number, dataView: DataView, numSamples: number, littleEndian: boolean): (Int32Array | Float32Array | Float64Array)

Parameters

            compressionType (number)
	    compression format as defined in SEED blockette 1000

            dataView (DataView)
	    input DataView to be decoded

            numSamples (number)
	    the number of samples that can be decoded from array

b

            littleEndian (boolean)
	    if true, dataView is little-endian (intel byte order)

b

.

Returns

      (Int32Array | Float32Array | Float64Array):
        array of length

numSamples

.

Throws

any: CodecException fail to decompress.

any: UnsupportedCompressionType unsupported compression type

      decodeSteim1

      src/seedcodec.js

Decode the indicated number of samples from the provided byte array and
return an integer array of the decompressed values.  Being differencing
compression, there may be an offset carried over from a previous data
record.  This offset value can be placed in bias, otherwise leave
the value as 0.

decodeSteim1(dataView: DataView, numSamples: number, littleEndian: boolean, bias: number): Int32Array

Parameters

            dataView (DataView)
	    input DataView to be decoded

            numSamples (number)
	    the number of samples that can be decoded from array

b

            littleEndian (boolean)
	    if true, dataView is little-endian (intel byte order)

b

.

            bias (number)
	    the first difference value will be computed from this value.
If set to 0, the method will attempt to use the X(0) constant instead.

Returns

      Int32Array:
        int array of length

numSamples

.

Throws

any: CodecException - encoded data length is not multiple of 64
bytes.

      decodeSteim2

      src/seedcodec.js

Decode the indicated number of samples from the provided byte array and
return an integer array of the decompressed values.  Being differencing
compression, there may be an offset carried over from a previous data
record.  This offset value can be placed in bias, otherwise leave
the value as 0.

decodeSteim2(dataView: DataView, numSamples: number, swapBytes: boolean, bias: number): Int32Array

Parameters

            dataView (DataView)
	    input byte array to be decoded

            numSamples (number)
	    the number of samples that can be decoded from array

            swapBytes (boolean)
	    if true, swap reverse the endian-ness of the elements of
dataview

            bias (number)
	    the first difference value will be computed from this value.
If set to 0, the method will attempt to use the X(0) constant instead.

Returns

      Int32Array:
        int array of length

numSamples

.

Throws

any: SteimException - encoded data length is not multiple of 64
bytes.


text:
layout: post
title:  "Let's get this started"
date:   2017-02-04 10:27:00 -0500
categories: keto
author: josh
---
The first I started Keto was January 1, 2016. I needed a change, I was tired of
feeling like a fat, unhealthy role model for my two girls, and I had a boy on
the way as well. I'd tried many different diets over the years, as I've been
overweight as long as I can remember. None of them really worked for me. I was
always hungry, the food tasted terrible, and I just couldn't keep with it for
long.

One day, probably around October 2015, I was browsing around
[Reddit](https://www.reddit.com), hit the [/r/loseit](https://www.reddit.com/r/loseit)
subreddit, then found [/r/keto](https://www.reddit.com/r/keto) through there.
The idea that I could eat bacon, eggs, steak, chicken, butter, etc., have more
consistent energy levels, stop the pain in my joints and back, and a bunch of
other health benefits including losing weight, I was hooked.

I started reading more of the science, and it's certainly easier to find studies
supporting a low-carb, high-fat lifestyle than any that prove that low-fat diets
are healthier. Either it's confirmation bias, or those studies just don't really
exist.

I ate the Keto diet from Jan 1 until around mid-late April, when my son was born.
In that time period, I lost 47 lbs, gained a lot of confidence, had a clearer
head, my attitude had improved, and I got stronger. I was lifting weights with
friends, running 3-6 miles at a time (never thought that would happen!), and
bike rides became incredibly relaxing. My blood test results got better, blood
pressure dropped to normal levels, skin cleared up, and again, just lots of
benefits.

Unfortunately, I let myself slip after the baby was born, as it was "easier" to
not think about what I was eating. I gained back most of the weight, and stopped
working out or running. I wasn't sleeping as well, stress was getting to me more,
and I just felt less happy.

Ultimately, I've started Keto again on January 1, 2017. I already feel benefits
from it, and I haven't even started the exercise portion of it yet. I've also
got a couple friends interested in it, and they will also be writing about their
exeperiences. Hopefully, others will read what we're doing, and come to the
conclusion themselves that it's time to try Keto.


text:
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2

DESCRIPTOR = _descriptor.FileDescriptor(
  name='uac/FeatureFlags.proto',
  package='ai.verta.uac',
  syntax='proto3',
  serialized_options=b'P\001Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uac',
  serialized_pb=b'\n\x16uac/FeatureFlags.proto\x12\x0c\x61i.verta.uac\x1a\x1cgoogle/api/annotations.proto\"\xcb\x01\n\x13\x46\x65\x61tureFlagsRequest\x1a\xb3\x01\n\x08Response\x12S\n\rfeature_flags\x18\x01 \x03(\x0b\x32<.ai.verta.uac.FeatureFlagsRequest.Response.FeatureFlagsEntry\x1aR\n\x11\x46\x65\x61tureFlagsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12,\n\x05value\x18\x02 \x01(\x0b\x32\x1d.ai.verta.uac.FeatureFlagItem:\x02\x38\x01\"3\n\x0f\x46\x65\x61tureFlagItem\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t2\x92\x01\n\x13\x46\x65\x61tureFlagsService\x12{\n\x0fgetFeatureFlags\x12!.ai.verta.uac.FeatureFlagsRequest\x1a*.ai.verta.uac.FeatureFlagsRequest.Response\"\x19\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/feature-flagsB>P\x01Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uacb\x06proto3'
  ,
  dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])

_FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY = _descriptor.Descriptor(
  name='FeatureFlagsEntry',
  full_name='ai.verta.uac.FeatureFlagsRequest.Response.FeatureFlagsEntry',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='key', full_name='ai.verta.uac.FeatureFlagsRequest.Response.FeatureFlagsEntry.key', index=0,
      number=1, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=b"".decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
    _descriptor.FieldDescriptor(
      name='value', full_name='ai.verta.uac.FeatureFlagsRequest.Response.FeatureFlagsEntry.value', index=1,
      number=2, type=11, cpp_type=10, label=1,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  serialized_options=b'8\001',
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=192,
  serialized_end=274,
)

_FEATUREFLAGSREQUEST_RESPONSE = _descriptor.Descriptor(
  name='Response',
  full_name='ai.verta.uac.FeatureFlagsRequest.Response',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='feature_flags', full_name='ai.verta.uac.FeatureFlagsRequest.Response.feature_flags', index=0,
      number=1, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
  ],
  extensions=[
  ],
  nested_types=[_FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY, ],
  enum_types=[
  ],
  serialized_options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=95,
  serialized_end=274,
)

_FEATUREFLAGSREQUEST = _descriptor.Descriptor(
  name='FeatureFlagsRequest',
  full_name='ai.verta.uac.FeatureFlagsRequest',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
  ],
  extensions=[
  ],
  nested_types=[_FEATUREFLAGSREQUEST_RESPONSE, ],
  enum_types=[
  ],
  serialized_options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=71,
  serialized_end=274,
)

_FEATUREFLAGITEM = _descriptor.Descriptor(
  name='FeatureFlagItem',
  full_name='ai.verta.uac.FeatureFlagItem',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='enabled', full_name='ai.verta.uac.FeatureFlagItem.enabled', index=0,
      number=1, type=8, cpp_type=7, label=1,
      has_default_value=False, default_value=False,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
    _descriptor.FieldDescriptor(
      name='content', full_name='ai.verta.uac.FeatureFlagItem.content', index=1,
      number=2, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=b"".decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  serialized_options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=276,
  serialized_end=327,
)

_FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY.fields_by_name['value'].message_type = _FEATUREFLAGITEM
_FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY.containing_type = _FEATUREFLAGSREQUEST_RESPONSE
_FEATUREFLAGSREQUEST_RESPONSE.fields_by_name['feature_flags'].message_type = _FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY
_FEATUREFLAGSREQUEST_RESPONSE.containing_type = _FEATUREFLAGSREQUEST
DESCRIPTOR.message_types_by_name['FeatureFlagsRequest'] = _FEATUREFLAGSREQUEST
DESCRIPTOR.message_types_by_name['FeatureFlagItem'] = _FEATUREFLAGITEM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

FeatureFlagsRequest = _reflection.GeneratedProtocolMessageType('FeatureFlagsRequest', (_message.Message,), {

  'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), {

    'FeatureFlagsEntry' : _reflection.GeneratedProtocolMessageType('FeatureFlagsEntry', (_message.Message,), {
      'DESCRIPTOR' : _FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY,
      '__module__' : 'uac.FeatureFlags_pb2'
      # @@protoc_insertion_point(class_scope:ai.verta.uac.FeatureFlagsRequest.Response.FeatureFlagsEntry)
      })
    ,
    'DESCRIPTOR' : _FEATUREFLAGSREQUEST_RESPONSE,
    '__module__' : 'uac.FeatureFlags_pb2'
    # @@protoc_insertion_point(class_scope:ai.verta.uac.FeatureFlagsRequest.Response)
    })
  ,
  'DESCRIPTOR' : _FEATUREFLAGSREQUEST,
  '__module__' : 'uac.FeatureFlags_pb2'
  # @@protoc_insertion_point(class_scope:ai.verta.uac.FeatureFlagsRequest)
  })
_sym_db.RegisterMessage(FeatureFlagsRequest)
_sym_db.RegisterMessage(FeatureFlagsRequest.Response)
_sym_db.RegisterMessage(FeatureFlagsRequest.Response.FeatureFlagsEntry)

FeatureFlagItem = _reflection.GeneratedProtocolMessageType('FeatureFlagItem', (_message.Message,), {
  'DESCRIPTOR' : _FEATUREFLAGITEM,
  '__module__' : 'uac.FeatureFlags_pb2'
  # @@protoc_insertion_point(class_scope:ai.verta.uac.FeatureFlagItem)
  })
_sym_db.RegisterMessage(FeatureFlagItem)

DESCRIPTOR._options = None
_FEATUREFLAGSREQUEST_RESPONSE_FEATUREFLAGSENTRY._options = None

_FEATUREFLAGSSERVICE = _descriptor.ServiceDescriptor(
  name='FeatureFlagsService',
  full_name='ai.verta.uac.FeatureFlagsService',
  file=DESCRIPTOR,
  index=0,
  serialized_options=None,
  serialized_start=330,
  serialized_end=476,
  methods=[
  _descriptor.MethodDescriptor(
    name='getFeatureFlags',
    full_name='ai.verta.uac.FeatureFlagsService.getFeatureFlags',
    index=0,
    containing_service=None,
    input_type=_FEATUREFLAGSREQUEST,
    output_type=_FEATUREFLAGSREQUEST_RESPONSE,
    serialized_options=b'\202\323\344\223\002\023\022\021/v1/feature-flags',
  ),
])
_sym_db.RegisterServiceDescriptor(_FEATUREFLAGSSERVICE)

DESCRIPTOR.services_by_name['FeatureFlagsService'] = _FEATUREFLAGSSERVICE

# @@protoc_insertion_point(module_scope)


text:
<?php
# Que template se usara ?
$capa = $this->session->userdata('usuario');
#echo "
";
#print_r($capa);
#echo "
";
if(isset($capa['template'])){
    $template = $capa['template'];
    $data['template'] = $capa['template'];

}else if ($capa=="VIGILANCIA"){
    $template = 'vigilancia';
    $data['template'] = 'vigilancia';
}
else{
    $template = 'avante';
    $data['template'] = 'avante';
}

if(!$this->session->userdata('usuario') ){
    #http_redirect();
    #echo "No hay sesión";
    $emp = ($template == 'avante')?'Avante':'Alka';
    $pagina_login = base_url() . 'usuario/login' . $emp;
    redirect($pagina_login);
}
?>
<!DOCTYPE html>

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

        <title>Intranet</title>
        <meta name="author" content="">
        <?php $this->load->view('templates/head-css.php', $data); ?>

            <?php
            if($template == 'avante'){
                // Para tomar solo el nombre y apellido
                $capaSonarh = $this->session->userdata('sonarh')[0];
                if (isset($capaSonarh->Nombre)) {
                    $data['nombre_apellido'] = ucfirst(strtolower(explode(" ", $capaSonarh->Nombre)[0])) . ' ' . ucfirst(strtolower($capaSonarh->Paterno));
                } else {
                    $data['nombre_apellido'] = ucfirst(strtolower(explode(" ", $capaSonarh->nombre_jefe)[0]));
                }
                $nombre = explode(" ", $capa['displayname']);

                $data['nombre'] = ucwords($capa['displayname']);
                $this->load->view('templates/menu-avante.php', $data);
            }else if($template == 'alka'){
                $data['nombre'] = ucwords($capa['Nombre']);
                $this->load->view('templates/menu-alka.php', $data);
            }
             else if($template == 'vigilancia'){
                $data['nombre'] = ucwords("VIGILANCIA AVANTE");
                $this->load->view('templates/menu-vigilancia.php', $data);
            }
            ?>


text:
#ifndef MAIN_H
#define MAIN_H
#include <vector>
#include <string>
#include <stdio.h>
#include "fff.h"
#include "Energies/energy.h"
#include "Modelling/Model.h"
#include "pKa.h"
#include "Utilities/string_tools.h"
#include "FFFcontrol.h"

#endif