text:
/*
    Vector3DS class
    © Keith O'Conor 2004
    keith.oconor @ {cs.tcd.ie, gmail.com}
*/

#ifndef VECTOR_H
#define VECTOR_H

#include <cmath>
#include <iostream>

class Vector3DS{
public:
	float x;
	float y;
	float z;

	/*
	Vector3DS();
	Vector3DS(float a, float b, float c);
	Vector3DS(Vector3DS& copy);

	Vector3DS& operator=(const Vector3DS &other);
	int		operator== (const Vector3DS &other);
	int		operator!= (const Vector3DS &other);
	Vector3DS	operator+(const Vector3DS &other);
	Vector3DS	operator-(const Vector3DS &other);
	Vector3DS	operator*(const float &value);
	Vector3DS	operator/(const float &value);
	Vector3DS& operator+=(const Vector3DS &other);
	Vector3DS& operator-=(const Vector3DS &other);
	Vector3DS& operator*=(const float& other);
	Vector3DS& operator/=(const float& other);
	float	operator[](unsigned i);

	float	length();
	float	lengthSq();
	float	dotProduct(const Vector3DS &other);
	Vector3DS	crossProduct(const Vector3DS &other);
	void	normalize();
	float	distance(const Vector3DS &other);
	float	distanceSq(const Vector3DS &other);
	void	set(float newX, float newY, float newZ);
	void	zero();
	*/

	  /////////////////
	 // Constructors
	/////////////////

	inline Vector3DS():x(0),y(0),z(0){}
	inline Vector3DS(const float a, const float b, const float c):x(a),y(b),z(c){}
	inline Vector3DS(const Vector3DS& copy):x(copy.x),y(copy.y),z(copy.z){}

	  //////////////
	 // Operators
	//////////////

	inline Vector3DS& operator= (const Vector3DS &other){
		x=other.x;y=other.y;z=other.z;
		return *this;
	}

	inline int operator== (const Vector3DS &other) const{
		return (x==other.x && y==other.y && z==other.z);
	}
	inline int operator!= (const Vector3DS &other) const{
		return (x!=other.x || y!=other.y || z!=other.z);
	}

	inline Vector3DS operator+ (const Vector3DS &other) const{
		return Vector3DS(x+other.x, y+other.y, z+other.z);
	}

	inline Vector3DS operator- (const Vector3DS &other) const{
		return Vector3DS(x-other.x, y-other.y,	z-other.z);
	}

	inline Vector3DS operator* (const float &value) const{
		return Vector3DS(x*value, y*value,	z*value);
	}

	inline Vector3DS operator/ (const float &value) const{
		return Vector3DS(x/value, y/value,	z/value);
	}

	inline Vector3DS& operator+= (const Vector3DS &other){
		x+=other.x;
		y+=other.y;
		z+=other.z;
		return *this;
	}
	inline Vector3DS& operator-= (const Vector3DS &other){
		x-=other.x;
		y-=other.y;
		z-=other.z;
		return *this;
	}

	inline Vector3DS& operator*= (const float &value){
		x*=value;
		y*=value;
		z*=value;
		return *this;
	}

	inline Vector3DS& operator/= (const float &value){
		x/=value;
		y/=value;
		z/=value;
		return *this;
	}

	inline float operator[] (unsigned i) const{
		switch(i){
		case 0:return x;
		case 1:return y;
		case 2:return z;
		default:
			terminate();
			break;
		}
	}

	  /////////////////////
	 // Other operations
	/////////////////////

	inline float length() const{
		float len=(x*x)+(y*y)+(z*z);
		return (float)sqrt(len);
	}

	inline float lengthSq() const{
		return (x*x)+(y*y)+(z*z);
	}

	inline float dotProduct(const Vector3DS &other) const{
		//this[dot]other
		return (x*other.x) + (y*other.y) + (z*other.z);
	}

	inline Vector3DS crossProduct(const Vector3DS &other) const{
		//(x1,y1,z1)◊(x2,y2,z2) = (y1z2-y2z1, x2z1-x1z2, x1y2-x2y1).
		return Vector3DS(
			(y*other.z) - (z*other.y),
			(z*other.x) - (x*other.z),
			(x*other.y) - (y*other.x)
		);
	}

	inline void normalize(){
		float len=length();
		if(len==0)return;
		len=1.0f/len;
		x*=len;
		y*=len;
		z*=len;
	}

	inline float distance(const Vector3DS &other) const{
		return (Vector3DS(other.x-x,other.y-y,other.z-z)).length();
	}

	inline float distanceSq(const Vector3DS &other) const{
		return (Vector3DS(other.x-x,other.y-y,other.z-z)).lengthSq();
	}

	inline void set(float newX, float newY, float newZ){
		x=newX;y=newY;z=newZ;
	}

	inline void zero(){
		x=y=z=0;
	}

};

typedef Vector3DS Vertex;

const Vector3DS vZero=Vector3DS(0,0,0);

  /////////////////////////////
 // Global stream operators
//////////////////////////////
inline std::ostream& operator<<(std::ostream &str, const Vector3DS &v){
	str<<v.x<<", "<<v.y<<", "<<v.z;
	return str;
}

#endif //VECTOR_H


text:
package com.moarperipherals.network;

/**
 * @author theoriginalbit
 * @since 15/11/14
 */
@SuppressWarnings("unused")
public class MessageFxOreScanner extends MessageGeneric {

    public MessageFxOreScanner() {
        // required empty constructor
    }

    public MessageFxOreScanner(int dimensionId, double xPos, double yPos, double zPos) {
        intData = new int[]{dimensionId};
        doubleData = new double[]{xPos, yPos, zPos};
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class PrerequisiteAnswerTest < ActiveSupport::TestCase
  before do
    @answer = PrerequisiteAnswer.new registration: registrations(:dexter),
        prerequisite: prerequisites(:unanswered), took_course: true
  end

  let(:answer) { prerequisite_answers(:dexter_math) }

  it 'validates the setup prerequisite answer' do
    assert @answer.valid?
  end

  it 'requires a registration' do
    @answer.registration = nil
    assert @answer.invalid?
  end

  it 'requires a prerequisite' do
    @answer.prerequisite = nil
    assert @answer.invalid?
  end

  it 'forbids a registrant from having multiple answers for a prerequisite' do
    @answer.prerequisite = prerequisites(:math)
    assert @answer.invalid?
  end

  describe '#registration_course_matches_prerequisite' do
    it 'requires the prerequisite to belong to the registered course' do
      answer.prerequisite = prerequisites(:not_main)
      assert answer.invalid?
    end
  end

  it 'must state whether the course has been taken' do
    @answer.took_course = nil
    assert @answer.invalid?
  end

  it 'rejects lengthy waiver answers' do
    @answer.waiver_answer = 'w' * 4.kilobytes
    assert @answer.invalid?
  end

  it 'requires a waiver answer if :took_course is false' do
    @answer.took_course = false
    @answer.waiver_answer = nil
    assert @answer.invalid?
  end

  describe '#waiver_answer=' do
    it 'converts empty strings to nil' do
      @answer.waiver_answer = ''
      assert_nil @answer.waiver_answer
    end

    it 'does not alter non-empty strings' do
      @answer.waiver_answer = 'wow'
      assert_equal 'wow', @answer.waiver_answer
    end
  end
end


text:
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}

module ViewModels.ThreadViewModel where
import Data.Text
import Data.Data

import qualified ViewModels.ShortUserViewModel as SUVM
import qualified ViewModels.YearMenuItemViewModel as YMIVM
import qualified ViewModels.PostViewModel as PVM

data ThreadViewModel = ThreadViewModel {
  shortUserViewModel ::  SUVM.ShortUserViewModel,
  menuItems :: [YMIVM.YearMenuItemViewModel],
  prevThreadURL :: Maybe Text,
  nextThreadURL :: Maybe Text,
  origin :: Text,
  zipUrl :: Maybe Text,
  posts :: [PVM.PostViewModel]
  } deriving (Data, Typeable)


text:
package com.lcw.one.codegen.rest;

import com.lcw.one.codegen.entity.CodeGenTableFieldEO;
import com.lcw.one.codegen.service.CodeGenTableFieldEOService;
import com.lcw.one.util.http.ResponseMessage;
import com.lcw.one.util.http.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/${restPath}/codeGen/tableEO")
@Api(description = "表字段")
public class CodeGenTableFieldEORestController {

    @Autowired
    private CodeGenTableFieldEOService codeGenTableFieldEOService;

    @ApiOperation(value = "表字段列表")
    @GetMapping("/{tableId}/field")
    public ResponseMessage<List<CodeGenTableFieldEO>> list(@PathVariable String tableId) {
        return Result.success(codeGenTableFieldEOService.listByTableId(tableId));
    }

    @ApiOperation(value = "表字段修改")
    @PutMapping("/{tableId}/field")
    public ResponseMessage update(@PathVariable String tableId, @RequestBody List<CodeGenTableFieldEO> codeGenTableFieldEO) {
        codeGenTableFieldEOService.update(codeGenTableFieldEO);
        return Result.success();
    }

}


text:
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/Twist.h>
#include <std_msgs/Float64.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <robotnik_msgs/set_mode.h>
#include <robotnik_msgs/get_mode.h>
#include <robotnik_msgs/set_odometry.h>
#include <robotnik_msgs/ptz.h>

//#include "self_test/self_test.h"
#include "diagnostic_msgs/DiagnosticStatus.h"
#include "diagnostic_updater/diagnostic_updater.h"
#include "diagnostic_updater/update_functions.h"
#include "diagnostic_updater/DiagnosticStatusWrapper.h"
#include "diagnostic_updater/publisher.h"

#define PI 3.1415926535
#define GUARDIAN_MIN_COMMAND_REC_FREQ   5.0
#define GUARDIAN_MAX_COMMAND_REC_FREQ   150.0

#define SKID_STEERING                1
#define MECANUM_STEERING             2

#define GUARDIAN_WHEEL_DIAMETER	0.37      // Default wheel diameter
#define GUARDIAN_D_TRACKS_M    	0.612 // 1.0       // default equivalent W distance (difference is due to slippage of skid steering)
#define GUARDIAN_WHEELBASE         0.6 //0.446     // default real L distance forward to rear axis
#define GUARDIAN_TRACKWIDTH        0.612 //0.408     // default real W distance from left wheels to right wheels

using namespace std;

class GuardianControllerClass {

public:

  ros::NodeHandle node_handle_;
  ros::NodeHandle private_node_handle_;
  double desired_freq_;

  // Diagnostics
  diagnostic_updater::Updater diagnostic_;			// General status diagnostic updater
  diagnostic_updater::FrequencyStatus freq_diag_;		         // Component frequency diagnostics
  diagnostic_updater::HeaderlessTopicDiagnostic *subs_command_freq; // Topic reception frequency diagnostics
  ros::Time last_command_time_;					// Last moment when the component received a command
  diagnostic_updater::FunctionDiagnosticTask command_freq_;

  // Robot model
  std::string robot_model_;

  // Velocity and position references to low level controllers
  ros::Publisher ref_vel_flw_;
  ros::Publisher ref_vel_frw_;
  ros::Publisher ref_vel_blw_;
  ros::Publisher ref_vel_brw_;
  ros::Publisher ref_pos_flw_;
  ros::Publisher ref_pos_frw_;
  ros::Publisher ref_pos_blw_;
  ros::Publisher ref_pos_brw_;
  ros::Publisher ref_pos_pan_;
  ros::Publisher ref_pos_tilt_;

  // Joint states published by the joint_state_controller of the Controller Manager
  ros::Subscriber joint_state_sub_;

  // High level robot command
  //ros::Subscriber cmd_sub_; // cmd_vel

  // High level robot command
  ros::Subscriber ptz_sub_; // command_ptz

  //ros::Subscriber gyro_sub_;

  // Services
  ros::ServiceServer srv_SetOdometry_;
  ros::ServiceServer srv_SetMode_;
  ros::ServiceServer srv_GetMode_;

  // Topics - skid - velocity
 /* std::string frw_vel_topic_;
  std::string flw_vel_topic_;
  std::string brw_vel_topic_;
  std::string blw_vel_topic_;
  */
  // Joint names - skid - velocity
  std::string joint_front_right_wheel;
  std::string joint_front_left_wheel;
  std::string joint_back_left_wheel;
  std::string joint_back_right_wheel;
/*
  // Joint names - ptz - position
  std::string joint_camera_pan;
  std::string joint_camera_tilt;

  // Topics - ptz
  std::string pan_pos_topic_;
  std::string tilt_pos_topic_;
  std::string cmd_topic;*/

  std::string tilt_pos_topic_;
  std::string odom_topic_;
  std::string cmd_ptz_topic_;
  std::string jointstates_topic_;
  std::string imu_topic_;

  // Selected operation mode
  int kinematic_modes_;
  int active_kinematic_mode_;

  // Indexes to joint_states
  int frw_vel_, flw_vel_, blw_vel_, brw_vel_;
  int pan_pos_, tilt_pos_;

  // Robot Speeds
  double linearSpeedXMps_;
  double linearSpeedYMps_;
  double angularSpeedRads_;

  // Robot Positions
  double robot_pose_px_;
  double robot_pose_py_;
  double robot_pose_pa_;
  double robot_pose_vx_;
  double robot_pose_vy_;

  // Robot Joint States
  sensor_msgs::JointState joint_state_;

  // Command reference
 // geometry_msgs::Twist base_vel_msg_;

  // External speed references
  double v_ref_x_;
  double v_ref_y_;
  double w_ref_;
  double v_ref_z_;
 // double pos_ref_pan_;
  double pos_ref_tilt_;

  // Flag to indicate if joint_state has been read
  bool read_state_;

  // Robot configuration parameters
  double guardian_wheel_diameter_;
  double guardian_d_tracks_m_;
  double guardian_wheelbase_;
  double guardian_trackwidth_;

  // IMU values
  double ang_vel_x_;
  double ang_vel_y_;
  double ang_vel_z_;

  double lin_acc_x_;
  double lin_acc_y_;
  double lin_acc_z_;

  double orientation_x_;
  double orientation_y_;
  double orientation_z_;
  double orientation_w_;

  // Parameter that defines if odom is published or not
  bool publish_odom_;

  // Parameter that defines if odom tf is published or not
  bool publish_odom_tf_;

  ros::Subscriber imu_sub_;

  // Publisher for odom topic
  ros::Publisher odom_pub_;

  // Broadcaster for odom tf
  tf::TransformBroadcaster odom_broadcaster;

/*!	\fn GuardianControllerClass::GuardianControllerClass()
 * 	\brief Public constructor
*/
GuardianControllerClass(ros::NodeHandle h) : diagnostic_(),
  node_handle_(h), private_node_handle_("~"),
  desired_freq_(100),
  freq_diag_(diagnostic_updater::FrequencyStatusParam(&desired_freq_, &desired_freq_, 0.05)   ),
  command_freq_("Command frequency check", boost::bind(&GuardianControllerClass::check_command_subscriber, this, _1))
  {

  // /guardian/joint_blw_velocity_controller/joint
  ROS_INFO("guardian_robot_control_node - Init ");

  // 4-Axis Skid Steer Rover
  // 8-Axis Omni-drive as 4-Axis Mecanum drive
  kinematic_modes_ = 1;

  ros::NodeHandle guardian_robot_control_node_handle(node_handle_, "guardian_robot_control");

  // Get robot model from the parameters
  if (!private_node_handle_.getParam("model", robot_model_)) {
	  ROS_ERROR("Robot model not defined.");
	  exit(-1);
	  }
  else ROS_INFO("Robot Model : %s", robot_model_.c_str());

  // Skid configuration - topics
  /*private_node_handle_.param<std::string>("frw_vel_topic", frw_vel_topic_, "/guardian/joint_frw_velocity_controller/command");
  private_node_handle_.param<std::string>("flw_vel_topic", flw_vel_topic_, "/guardian/joint_flw_velocity_controller/command");
  private_node_handle_.param<std::string>("blw_vel_topic", blw_vel_topic_, "/guardian/joint_blw_velocity_controller/command");
  private_node_handle_.param<std::string>("brw_vel_topic", brw_vel_topic_, "/guardian/joint_brw_velocity_controller/command");
*/
  // Skid configuration - Joint names
  private_node_handle_.param<std::string>("joint_front_right_wheel", joint_front_right_wheel, "joint_front_right_wheel");
  private_node_handle_.param<std::string>("joint_front_left_wheel", joint_front_left_wheel, "joint_front_left_wheel");
  private_node_handle_.param<std::string>("joint_back_left_wheel", joint_back_left_wheel, "joint_back_left_wheel");
  private_node_handle_.param<std::string>("joint_back_right_wheel", joint_back_right_wheel, "joint_back_right_wheel");

  // PTZ topics
  /*private_node_handle_.param<std::string>("pan_pos_topic", pan_pos_topic_, "/guardian/joint_pan_position_controller/command");
  private_node_handle_.param<std::string>("tilt_pos_topic", tilt_pos_topic_, "/guardian/joint_tilt_position_controller/command");
  private_node_handle_.param<std::string>("joint_camera_pan", joint_camera_pan, "joint_camera_pan");
  private_node_handle_.param<std::string>("joint_camera_tilt", joint_camera_tilt, "joint_camera_tilt");*/

  private_node_handle_.param<std::string>("tilt_pos_topic", tilt_pos_topic_, "/guardian/joint_tilt_position_controller/command");
  private_node_handle_.param<std::string>("odom_topic",odom_topic_, "/guardian/odom");
  private_node_handle_.param<std::string>("cmd_ptz_topic", cmd_ptz_topic_, "/guardian_robot_control/command_ptz");
  private_node_handle_.param<std::string>("jointstates_topic", jointstates_topic_, "/guardian/joint_states");
  private_node_handle_.param<std::string>("imu_topic", imu_topic_ , "/guardian/imu");

  //velocity command topic
  //private_node_handle_.param<std::string>("cmd_topic", cmd_topic, "command");

  // Robot parameters
  if (!private_node_handle_.getParam("guardian_wheel_diameter", guardian_wheel_diameter_))
    guardian_wheel_diameter_ = GUARDIAN_WHEEL_DIAMETER;
  if (!private_node_handle_.getParam("guardian_d_tracks_m", guardian_d_tracks_m_))
    guardian_d_tracks_m_ = GUARDIAN_D_TRACKS_M;
  ROS_INFO("guardian_wheel_diameter_ = %5.2f", guardian_wheel_diameter_);
  ROS_INFO("guardian_d_tracks_m_ = %5.2f", guardian_d_tracks_m_);

  private_node_handle_.param("publish_odom", publish_odom_, true);
  private_node_handle_.param("publish_odom_tf", publish_odom_tf_, true);
  if (publish_odom_tf_) ROS_INFO("PUBLISHING odom->base_footprin tf");
  else ROS_INFO("NOT PUBLISHING odom->base_footprint tf");

  // Robot Speeds
  linearSpeedXMps_   = 0.0;
  linearSpeedYMps_   = 0.0;
  angularSpeedRads_  = 0.0;

  // Robot Positions
  robot_pose_px_ = 0.0;
  robot_pose_py_ = 0.0;
  robot_pose_pa_ = 0.0;
  robot_pose_vx_ = 0.0;
  robot_pose_vy_ = 0.0;

  // External speed references
  v_ref_x_ = 0.0;
  v_ref_y_ = 0.0;
  w_ref_ = 0.0;
  v_ref_z_ = 0.0;
  //pos_ref_pan_ = 0.0;
  pos_ref_tilt_= 0.0;

  // Imu variables
  ang_vel_x_ = 0.0; ang_vel_y_ = 0.0; ang_vel_z_ = 0.0;
  lin_acc_x_ = 0.0; lin_acc_y_ = 0.0; lin_acc_z_ = 0.0;
  orientation_x_ = 0.0; orientation_y_ = 0.0; orientation_z_ = 0.0; orientation_w_ = 0.0;

  // Active kinematic mode
  active_kinematic_mode_ = SKID_STEERING;

  // Advertise services
  srv_SetMode_ = guardian_robot_control_node_handle.advertiseService("set_mode", &GuardianControllerClass::srvCallback_SetMode, this);
  srv_GetMode_ = guardian_robot_control_node_handle.advertiseService("get_mode", &GuardianControllerClass::srvCallback_GetMode, this);
  srv_SetOdometry_ = guardian_robot_control_node_handle.advertiseService("set_odometry",  &GuardianControllerClass::srvCallback_SetOdometry, this);

  // Subscribe to joint states topic
  joint_state_sub_ = guardian_robot_control_node_handle.subscribe<sensor_msgs::JointState>(jointstates_topic_, 1, &GuardianControllerClass::jointStateCallback, this);

  // Subscribe to imu data
  imu_sub_ = guardian_robot_control_node_handle.subscribe(imu_topic_, 1, &GuardianControllerClass::imuCallback, this);

  // Advertise reference topics for the controllers
  /*ref_vel_frw_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>( frw_vel_topic_, 50);
  ref_vel_flw_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>( flw_vel_topic_, 50);
  ref_vel_blw_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>( blw_vel_topic_, 50);
  ref_vel_brw_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>( brw_vel_topic_, 50);

  ref_pos_pan_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>( pan_pos_topic_, 50);*/
  ref_pos_tilt_ = guardian_robot_control_node_handle.advertise<std_msgs::Float64>(tilt_pos_topic_, 50);

  // Subscribe to command topic
  //cmd_sub_ = guardian_robot_control_node_handle.subscribe<geometry_msgs::Twist>(cmd_topic, 1, &GuardianControllerClass::commandCallback, this);

  // Subscribe to ptz command topic
  ptz_sub_ = guardian_robot_control_node_handle.subscribe<robotnik_msgs::ptz>(cmd_ptz_topic_, 1, &GuardianControllerClass::command_ptzCallback, this);
  // /guardian_robot_control/command_ptz

  // TODO odom topic as parameter
  // Publish odometry
  odom_pub_ = guardian_robot_control_node_handle.advertise<nav_msgs::Odometry>(odom_topic_, 1000);

  // Component frequency diagnostics
  diagnostic_.setHardwareID("guardian_robot_control - simulation");
  diagnostic_.add( freq_diag_ );
  diagnostic_.add( command_freq_ );

  // Topics freq control
  // For /guardian_robot_control/command
  double min_freq = GUARDIAN_MIN_COMMAND_REC_FREQ; // If you update these values, the
  double max_freq = GUARDIAN_MAX_COMMAND_REC_FREQ; // HeaderlessTopicDiagnostic will use the new values.
  subs_command_freq = new diagnostic_updater::HeaderlessTopicDiagnostic("/guardian_robot_control/command", diagnostic_,
	                    diagnostic_updater::FrequencyStatusParam(&min_freq, &max_freq, 0.1, 10));
  subs_command_freq->addTask(&command_freq_); // Adding an additional task to the control

  // Flag to indicate joint_state has been read
  read_state_ = false;
}

/// Controller startup in realtime
int starting()
{

  ROS_INFO("GuardianControllerClass::starting");

  //name: ['joint_back_left_wheel', 'joint_back_right_wheel', 'joint_front_left_wheel', 'joint_front_right_wheel']
  //position: [-0.04246698357387224, 0.053199274627900195, -0.04246671523622059, 0.03126368464965523]
  //velocity: [-0.0006956167983269147, 0.0004581098383479411, -0.0013794952191663358, 0.00045523862784977847]

  // Initialize joint indexes according to joint names
  if (read_state_) {
    vector<string> joint_names = joint_state_.name;
    frw_vel_ = find (joint_names.begin(),joint_names.end(), string(joint_front_right_wheel)) - joint_names.begin();
    flw_vel_ = find (joint_names.begin(),joint_names.end(), string(joint_front_left_wheel)) - joint_names.begin();
    blw_vel_ = find (joint_names.begin(),joint_names.end(), string(joint_back_left_wheel)) - joint_names.begin();
    brw_vel_ = find (joint_names.begin(),joint_names.end(), string(joint_back_right_wheel)) - joint_names.begin();
	// For publishing the ptz joint state
    //pan_pos_ = find(joint_names.begin(), joint_names.end(), string(joint_camera_pan)) - joint_names.begin();
    //tilt_pos_ = find(joint_names.begin(), joint_names.end(), string(joint_camera_tilt)) - joint_names.begin();
    return 0;
    }
  else return -1;
}

/// Controller update loop
void UpdateControl()
{
  // Depending on the robot configuration
  if (active_kinematic_mode_ == SKID_STEERING) {

  	  double v_left_mps, v_right_mps;

	  // Calculate its own velocities for realize the motor control
      v_left_mps = ((joint_state_.velocity[blw_vel_] + joint_state_.velocity[flw_vel_]) / 2.0) * (guardian_wheel_diameter_ / 2.0);
      v_right_mps = ((joint_state_.velocity[brw_vel_] + joint_state_.velocity[frw_vel_]) / 2.0) * (guardian_wheel_diameter_ / 2.0);
	  // sign according to urdf (if wheel model is not symetric, should be inverted)

	  linearSpeedXMps_ = (v_right_mps + v_left_mps) / 2.0;                   // m/s
	  angularSpeedRads_ = (v_right_mps - v_left_mps) / guardian_d_tracks_m_; // rad/s

	  /*ROS_INFO("BL: %5.3f , FL: %5.3f ", joint_state_.velocity[blw_vel_], joint_state_.velocity[flw_vel_]);
	  ROS_INFO("BR: %5.3f , FR: %5.3f ", joint_state_.velocity[brw_vel_], joint_state_.velocity[frw_vel_]);

	  ROS_INFO("vleft=%5.2f   vright=%5.2f    linearSpeedXMps=%5.2f, linearSpeedYMps=%5.2f, angularSpeedRads=%5.4f", v_left_mps, v_right_mps,
			linearSpeedXMps_, linearSpeedYMps_, angularSpeedRads_);*/

	  // Current controllers close this loop allowing (v,w) references.
	  /*double epv=0.0;
	  double epw=0.0;
	  static double epvant =0.0;
	  static double epwant =0.0;

	  // Adjusted for soft indoor office soil
	  //double kpv=2.5; double kdv=0.0;
	  //double kpw=2.5;  double kdw=0.0;
	  // In order to use this controller with the move_base stack note that move_base sets the min rotation ref to 0.4 independantly of the yaml configurations!!!
	  double kpv=2.5; double kdv=0.0;
	  double kpw=25.0; double kdw=15.0;

	  // State feedback error
	  epv = v_ref_x_ - linearSpeedXMps_;
	  epw = w_ref_ - angularSpeedRads_;
	  // ROS_INFO("v_ref_x_=%5.2f, linearSpeedXMps_=%5.2f w_ref_=%5.2f angularSpeedRads_=%5.2f", v_ref_x_, linearSpeedXMps_, w_ref_, angularSpeedRads_);

	  // Compute state control actions
	  double uv= kpv * epv + kdv * (epv - epvant);
	  double uw= kpw * epw + kdw * (epw - epwant);
	  epvant = epv;
	  epwant = epw;

	  // Inverse kinematics
	  double dUl = uv - 0.5 * guardian_d_tracks_m_ * uw;
          // sign according to urdf (if wheel model is not symetric, should be inverted)
   	  double dUr = -(uv + 0.5 * guardian_d_tracks_m_ * uw);

	  // Motor control actions
	  double limit = 100.0;
	  */
	  //ROS_INFO("epv=%5.2f, epw=%5.2f ***  dUl=%5.2f  dUr=%5.2f", epv, epw, dUl, dUr);

	  //
     /* std_msgs::Float64 frw_ref_msg;
      std_msgs::Float64 flw_ref_msg;
      std_msgs::Float64 blw_ref_msg;
      std_msgs::Float64 brw_ref_msg;

      double k1 = 0.5;

      frw_ref_msg.data = saturation( -k1 * dUr, -limit, limit);
      flw_ref_msg.data = saturation( k1 * dUl, -limit, limit);
      blw_ref_msg.data = saturation( k1 * dUl, -limit, limit);
      brw_ref_msg.data = saturation( -k1 * dUr, -limit, limit);

      ref_vel_frw_.publish( frw_ref_msg );
      ref_vel_flw_.publish( flw_ref_msg );
      ref_vel_blw_.publish( blw_ref_msg );
      ref_vel_brw_.publish( brw_ref_msg );*/
	  }

     // PTZ
	 //std_msgs::Float64 pan_ref_pos_msg, tilt_ref_pos_msg;
	 std_msgs::Float64 tilt_ref_pos_msg;
    /* pan_ref_pos_msg.data = pos_ref_pan_;            //saturation( pos_ref_pan_, 0.0, 0.5);
     ref_pos_pan_.publish( pan_ref_pos_msg );*/
     tilt_ref_pos_msg.data = pos_ref_tilt_;          //saturation( pos_ref_tilt_, 0.0, 0.5);
     ref_pos_tilt_.publish( tilt_ref_pos_msg );
}

// Update robot odometry depending on kinematic configuration
void UpdateOdometry() {
	// Depending on the robot configuration
	if (active_kinematic_mode_ == SKID_STEERING) {
		// Compute Velocity (linearSpeedXMps_ computed in control
		robot_pose_vx_ = linearSpeedXMps_ * cos(robot_pose_pa_);
		robot_pose_vy_ = linearSpeedXMps_ * sin(robot_pose_pa_);
	}

	// Compute Position
	double fSamplePeriod = 1.0 / desired_freq_;
	robot_pose_pa_ += ang_vel_z_ * fSamplePeriod;  // this velocity comes from IMU callback
	robot_pose_px_ += robot_pose_vx_ * fSamplePeriod;
	robot_pose_py_ += robot_pose_vy_ * fSamplePeriod;

	tf::Quaternion orientation = tf::createQuaternionFromYaw(robot_pose_pa_);
	orientation_x_ = orientation.x();
	orientation_y_ = orientation.y();
	orientation_z_ = orientation.z();
	orientation_w_ = orientation.w();
	// ROS_INFO("Odom estimated x=%5.2f  y=%5.2f a=%5.2f", robot_pose_px_, robot_pose_py_, robot_pose_pa_);
}

void PublishOdometryTF()
{
	// send the transform over /tf
	// activate / deactivate with param
	// this tf in needed when not using robot_pose_ekf
	geometry_msgs::TransformStamped odom_trans;
	odom_trans.header.stamp = ros::Time::now();
	odom_trans.header.frame_id = "odom";
	odom_trans.child_frame_id = "base_footprint";

	odom_trans.transform.translation.x = robot_pose_px_;
	odom_trans.transform.translation.y = robot_pose_py_;
	odom_trans.transform.translation.z = 0.0;

	odom_trans.transform.rotation.x = orientation_x_;
	odom_trans.transform.rotation.y = orientation_y_;
	odom_trans.transform.rotation.z = orientation_z_;
	odom_trans.transform.rotation.w = orientation_w_;

	odom_broadcaster.sendTransform(odom_trans);
}

// Publish robot odometry tf and topic depending
void PublishOdometry()
{
    //next, we'll publish the odometry message over ROS
    nav_msgs::Odometry odom;
    odom.header.stamp = ros::Time::now();
    odom.header.frame_id = "odom";

    //set the position
	// Position
    odom.pose.pose.position.x = robot_pose_px_;
    odom.pose.pose.position.y = robot_pose_py_;
    odom.pose.pose.position.z = 0.0;
	// Orientation
    odom.pose.pose.orientation.x = orientation_x_;
	odom.pose.pose.orientation.y = orientation_y_;
	odom.pose.pose.orientation.z = orientation_z_;
	odom.pose.pose.orientation.w = orientation_w_;
	// Pose covariance
    for(int i = 0; i < 6; i++)
      		odom.pose.covariance[i*6+i] = 0.1;  // test 0.001

    //set the velocity
    odom.child_frame_id = "base_footprint";
	// Linear velocities
    odom.twist.twist.linear.x = robot_pose_vx_; //linearSpeedXMps_
    odom.twist.twist.linear.y = robot_pose_vy_; //0.0; ////deveria ser 0 no ref base_footprint...
	odom.twist.twist.linear.z = 0.0;
    // Angular velocities
    odom.twist.twist.angular.x = ang_vel_x_;
    odom.twist.twist.angular.y = ang_vel_y_;
    odom.twist.twist.angular.z = ang_vel_z_ ;
	// Twist covariance
	for(int i = 0; i < 6; i++)
     		odom.twist.covariance[6*i+i] = 0.1;  // test 0.001

    //publish the message
    odom_pub_.publish(odom);
}

/// Controller stopping
void stopping()
{}

/*
 *	\brief Checks that the robot is receiving at a correct frequency the command messages. Diagnostics
 *
 */
void check_command_subscriber(diagnostic_updater::DiagnosticStatusWrapper &stat)
{
	ros::Time current_time = ros::Time::now();

	double diff = (current_time - last_command_time_).toSec();

	if(diff > 1.0){
		stat.summary(diagnostic_msgs::DiagnosticStatus::WARN, "Topic is not receiving commands");
		//ROS_INFO("check_command_subscriber: %lf seconds without commands", diff);
		// TODO: Set Speed References to 0
	}else{
		stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Topic receiving commands");
	}
}

// Set the base velocity command
void setCommand(const geometry_msgs::Twist &cmd_vel)
{
   v_ref_x_ = saturation(cmd_vel.linear.x, -10.0, 10.0);
   v_ref_y_ = saturation(cmd_vel.linear.y, -10.0, 10.0);
   w_ref_ = saturation(cmd_vel.angular.z, -10.0, 10.0); // -10.0 10.0
   v_ref_z_ = saturation(cmd_vel.linear.z, -10.0, 10.0);
}

// CALLBACKS
// Service SetMode
bool srvCallback_SetMode(robotnik_msgs::set_mode::Request& request, robotnik_msgs::set_mode::Response& response)
{
  // Only SKID STEERING mode
  /*
  ROS_INFO("GuardianControllerClass::srvCallback_SetMode request.mode= %d", request.mode);
  if (request.mode == 1) {
	active_kinematic_mode_ = request.mode;
	return true;
	}
  if (request.mode == 2) {
	if (kinematic_modes_ == 2) {
		active_kinematic_mode_ = request.mode;
		return true;
		}
	else return false;
	}
	*/
  return false;
}

// Service GetMode
bool srvCallback_GetMode(robotnik_msgs::get_mode::Request& request, robotnik_msgs::get_mode::Response& response)
{
  response.mode = active_kinematic_mode_;
  return true;
}

// Service SetOdometry
bool srvCallback_SetOdometry(robotnik_msgs::set_odometry::Request &request, robotnik_msgs::set_odometry::Response &response )
{
	/*ROS_INFO("guardian_odometry::set_odometry: request -> x = %f, y = %f, a = %f", request.x, request.y, request.orientation);
	robot_pose_px_ = request.x;
	robot_pose_py_ = request.y;
	robot_pose_pa_ = request.orientation;*/

	response.ret = true;
	return true;
}

// Topic command
void jointStateCallback(const sensor_msgs::JointStateConstPtr& msg)
{
  joint_state_ = *msg;
  read_state_ = true;
}

// Topic command
/*void commandCallback(const geometry_msgs::TwistConstPtr& msg)
{

  // Safety check
  last_command_time_ = ros::Time::now();
  subs_command_freq->tick();			// For diagnostics

  base_vel_msg_ = *msg;
  this->setCommand(base_vel_msg_);
}*/

// Topic ptz command
void command_ptzCallback(const robotnik_msgs::ptzConstPtr& msg)
{

	//reversed signal because when msg is positive the joint is going backwards - CHECK WHY
  //pos_ref_pan_ += msg->pan / 180.0 * PI;
  pos_ref_tilt_ -= msg->tilt / 180.0 * PI;

  double limit = 1.57; //90 degrees

  if (pos_ref_tilt_ >= limit)
  {    pos_ref_tilt_ = limit;
       std::cout<<"*Limit DOWN reached (-90 deg)"<<std::endl;
  }

  if (pos_ref_tilt_ <= -1*limit)
  {      pos_ref_tilt_ = -1*limit;
         std::cout<<"*Limit UP reached (+90 deg) "<<std::endl;
  }

}

// Imu callback
void imuCallback( const sensor_msgs::Imu& imu_msg){
//	orientation_x_ = imu_msg.orientation.x;
//	orientation_y_ = imu_msg.orientation.y;
//	orientation_z_ = imu_msg.orientation.z;
//	orientation_w_ = imu_msg.orientation.w;

	ang_vel_x_ = imu_msg.angular_velocity.x;
	ang_vel_y_ = imu_msg.angular_velocity.y;
	ang_vel_z_ = imu_msg.angular_velocity.z;

	lin_acc_x_ = imu_msg.linear_acceleration.x;
	lin_acc_y_ = imu_msg.linear_acceleration.y;
	lin_acc_z_ = imu_msg.linear_acceleration.z;
}

double saturation(double u, double min, double max)
{
 if (u>max) u=max;
 if (u<min) u=min;
 return u;
}

double radnorm( double value )
{
  while (value > PI) value -= PI;
  while (value < -PI) value += PI;
  return value;
}

double radnorm2( double value )
{
  while (value > 2.0*PI) value -= 2.0*PI;
  while (value < -2.0*PI) value += 2.0*PI;
  return value;
}

bool spin()
{
    ROS_INFO("guardian_robot_control::spin()");
    ros::Rate r(desired_freq_);  // 50.0

    while (!ros::isShuttingDown()) // Using ros::isShuttingDown to avoid restarting the node during a shutdown.
    {
      if (starting() == 0)
      {
	    while(ros::ok() && node_handle_.ok()) {
          UpdateControl();

          if (publish_odom_) {
        	  UpdateOdometry();
          	  PublishOdometry();
          }

          if (publish_odom_tf_) {
        	  PublishOdometryTF();
          }

          diagnostic_.update();
          ros::spinOnce();
	      r.sleep();
          }
	      ROS_INFO("END OF ros::ok() !!!");
      } else {
       // No need for diagnostic here since a broadcast occurs in start
       // when there is an error.
       usleep(1000000);
       ros::spinOnce();
      }
   }

   ROS_INFO("guardian_robot_control::spin() - end");
   return true;
}

}; // Class GuardianControllerClass

int main(int argc, char** argv)
{
	ros::init(argc, argv, "guardian_robot_control");

	ros::NodeHandle n;
  	GuardianControllerClass sxlrc(n);

  	// ros::ServiceServer service = n.advertiseService("set_odometry", &guardian_node::set_odometry, &sxlc);
    sxlrc.spin();

	return (0);

}


text:
<?xml version="1.0" ?>
<course course="modulestore_basic" course_image="basic.jpg" display_name="Modulestore Basic" enrollment_start="2017-04-12T04:00:00Z" org="edX" start="2017-09-12T00:00:00Z" url_name="Basic">
  <chapter display_name="Chapter 1: Basics" url_name="Chapter_1_Basics">
    <sequential format="Learning Sequence" graded="true" display_name="Overview" url_name="Overview">
      <vertical display_name="Week 1 overview" url_name="Week_1_overview">
        <html display_name="Week 1 overview" filename="Week_1_overview" url_name="Week_1_overview"/>
      </vertical>
      <vertical display_name="Expectations" url_name="Expectations">
        <html filename="Expectations" url_name="Expectations_HTML" display_name="Expectations Overview"/>
      </vertical>
    </sequential>
  </chapter>
</course>


text:
using System;
using MbUnit.Core.Framework;
using MbUnit.Framework;
using MbUnit.Core.Remoting;
using MbUnit.Core.Filters;
using MbUnit.Core.Reports.Serialization;

namespace NUnit.Tests.Core
{
    [TestFixture]
    public class FixtureSetupTearDownTest
    {
        private static int setUpCount = 0;
        private static int tearDownCount = 0;
        private static int derivedSetUpCount=0;
        private static int derivedTearDownCount;

        [TestFixture]
        internal class SetUpAndTearDownFixture
        {
            [TestFixtureSetUp]
            public virtual void Init()
            {
                FixtureSetupTearDownTest.setUpCount++;
            }

            [TestFixtureTearDown]
            public virtual void Destroy()
            {
                FixtureSetupTearDownTest.tearDownCount++;
            }

            [Test]
            public void Success() { }

            [Test]
            public void EvenMoreSuccess() { }
        }

        internal class InheritSetUpAndTearDown : SetUpAndTearDownFixture
        {
            [Test]
            public void AnotherTest() { }

            [Test]
            public void YetAnotherTest() { }
        }

        internal class DefineInheritSetUpAndTearDown : SetUpAndTearDownFixture
        {
            [TestFixtureSetUp]
            public override void Init()
            {
                derivedSetUpCount++;
            }

            [TestFixtureTearDown]
            public override void Destroy()
            {
                derivedTearDownCount++;
            }

            [Test]
            public void AnotherTest() { }

            [Test]
            public void YetAnotherTest() { }
        }

        [TestFixture]
        internal class MisbehavingFixtureSetUp
        {
            public bool blowUp = true;

            [TestFixtureSetUp]
            public void willBlowUp()
            {
                if (blowUp)
                    throw new Exception("This was thrown from fixture setup");
            }

            [Test]
            public void nothingToTest()
            {}
        }

        [SetUp]
        public void SetUp()
        {
            setUpCount = 0;
            tearDownCount = 0;
            derivedSetUpCount=0;
            derivedTearDownCount=0;
        }

        protected ReportResult Run(Type fixtureType)
        {
            using (TypeTestDomain domain = new TypeTestDomain(fixtureType))
            {
                domain.Load();
                domain.TestEngine.RunPipes();
                ReportResult result = domain.TestEngine.Report.Result;

                return result;
            }
        }

        [Test]
        public void MakeSureSetUpAndTearDownAreCalled()
        {
            ReportResult result = Run(typeof(SetUpAndTearDownFixture));
            Assert.AreEqual(1, setUpCount);
            Assert.AreEqual(1, tearDownCount);
            Assert.AreEqual(2, result.Counter.RunCount);
            Assert.AreEqual(2, result.Counter.SuccessCount);
        }

        [Test]
        public void CheckInheritedSetUpAndTearDownAreCalled()
        {
            ReportResult result = Run(typeof(SetUpAndTearDownFixture));
            Assert.AreEqual(1, setUpCount);
            Assert.AreEqual(1, tearDownCount);
        }

        [Test]
        public void CheckInheritedSetUpAndTearDownAreNotCalled()
        {
            ReportResult result = Run(typeof(DefineInheritSetUpAndTearDown));
            Assert.AreEqual(0, setUpCount);
            Assert.AreEqual(0, tearDownCount);
            Assert.AreEqual(1, derivedSetUpCount);
            Assert.AreEqual(1, derivedTearDownCount);
        }

        [Test]
        public void HandleErrorInFixtureSetup()
        {
            ReportResult result = Run(typeof(MisbehavingFixtureSetUp));
        }
/*
        [Test]
        public void RerunFixtureAfterSetUpFixed()
        {
            MisbehavingFixtureSetUp testFixture = new MisbehavingFixtureSetUp();
            TestSuite suite = new TestSuite("ASuite");
            suite.Add(testFixture);
            TestSuiteResult result = (TestSuiteResult)suite.Run(NullListener.NULL);

            // should have one suite and one fixture
            ResultSummarizer summ = new ResultSummarizer(result);
            Assert.AreEqual(1, summ.ResultCount);
            Assert.AreEqual(0, summ.TestsNotRun);
            Assert.AreEqual(0, summ.SuitesNotRun);
            TestResult failedResult = ((TestResult)result.Results[0]);
            Assert.IsTrue(failedResult.Executed, "Suite should have executed");

            //fix the blow up in setup
            testFixture.blowUp = false;
            result = (TestSuiteResult)suite.Run(NullListener.NULL);

            // should have one suite and one fixture
            summ = new ResultSummarizer(result);
            Assert.AreEqual(1, summ.ResultCount);
            Assert.AreEqual(0, summ.TestsNotRun);
            Assert.AreEqual(0, summ.SuitesNotRun);
        }

        internal class IgnoreInFixtureSetUp
        {
            [TestFixtureSetUp]
            public void SetUpCallsIgnore()
            {
                Assert.Ignore("TestFixtureSetUp called Ignore");
            }

            [Test]
            public void nothingToTest()
            {
            }
        }

        [Test]
        public void HandleIgnoreInFixtureSetup()
        {
            IgnoreInFixtureSetUp testFixture = new IgnoreInFixtureSetUp();
            TestSuite suite = new TestSuite("ASuite");
            suite.Add(testFixture);
            TestSuiteResult result = (TestSuiteResult)suite.Run(NullListener.NULL);

            // should have one suite and one fixture
            ResultSummarizer summ = new ResultSummarizer(result);
            Assert.AreEqual(0, summ.ResultCount);
            Assert.AreEqual(1, summ.TestsNotRun);
            Assert.AreEqual(1, summ.SuitesNotRun);
            TestSuiteResult ignoredResult = ((TestSuiteResult)result.Results[0]);
            Assert.IsFalse(ignoredResult.Executed, "Suite should not have executed");
            Assert.AreEqual("TestFixtureSetUp called Ignore", ignoredResult.Message);
            Assert.IsNotNull(ignoredResult.StackTrace, "StackTrace should not be null");

            TestResult testResult = ((TestResult)ignoredResult.Results[0]);
            Assert.IsFalse(testResult.Executed, "Testcase should not have executed");
            Assert.AreEqual("TestFixtureSetUp called Ignore", testResult.Message);
        }

        internal class MisbehavingFixtureTearDown
        {
            public bool blowUp = true;

            [TestFixtureTearDown]
            public void willBlowUp()
            {
                if (blowUp)
                    throw new Exception("This was thrown from fixture teardown");
            }

            [Test]
            public void nothingToTest()
            {
            }
        }

        [Test]
        public void HandleErrorInFixtureTearDown()
        {
            MisbehavingFixtureTearDown testFixture = new MisbehavingFixtureTearDown();
            TestSuite suite = new TestSuite("ASuite");
            suite.Add(testFixture);
            TestSuiteResult result = (TestSuiteResult)suite.Run(NullListener.NULL);
            Assert.AreEqual(1, result.Results.Count);
            TestResult failedResult = ((TestResult)result.Results[0]);
            Assert.IsTrue(failedResult.Executed, "Suite should have executed");
            Assert.IsTrue(failedResult.IsFailure, "Suite should have failed");

            Assert.AreEqual("This was thrown from fixture teardown", failedResult.Message);
            Assert.IsNotNull(failedResult.StackTrace, "StackTrace should not be null");

            // should have one suite and one fixture
            ResultSummarizer summ = new ResultSummarizer(result);
            Assert.AreEqual(1, summ.ResultCount);
            Assert.AreEqual(0, summ.TestsNotRun);
            Assert.AreEqual(0, summ.SuitesNotRun);
        }

        [Test]
        public void RerunFixtureAfterTearDownFixed()
        {
            MisbehavingFixtureTearDown testFixture = new MisbehavingFixtureTearDown();
            TestSuite suite = new TestSuite("ASuite");
            suite.Add(testFixture);
            TestSuiteResult result = (TestSuiteResult)suite.Run(NullListener.NULL);
            Assert.AreEqual(1, result.Results.Count);

            // should have one suite and one fixture
            ResultSummarizer summ = new ResultSummarizer(result);
            Assert.AreEqual(1, summ.ResultCount);
            Assert.AreEqual(0, summ.TestsNotRun);
            Assert.AreEqual(0, summ.SuitesNotRun);

            testFixture.blowUp = false;
            result = (TestSuiteResult)suite.Run(NullListener.NULL);
            summ = new ResultSummarizer(result);
            Assert.AreEqual(1, summ.ResultCount);
            Assert.AreEqual(0, summ.TestsNotRun);
            Assert.AreEqual(0, summ.SuitesNotRun);
        }

        internal class SetUpAndTearDownWithTestInName
        {
            internal int setUpCount = 0;
            internal int tearDownCount = 0;

            [TestFixtureSetUp]
            public virtual void TestFixtureSetUp()
            {
                setUpCount++;
            }

            [TestFixtureTearDown]
            public virtual void TestFixtureTearDown()
            {
                tearDownCount++;
            }

            [Test]
            public void Success() { }

            [Test]
            public void EvenMoreSuccess() { }
        }

        [Test]
        public void HandleSetUpAndTearDownWithTestInName()
        {
            SetUpAndTearDownWithTestInName testFixture = new SetUpAndTearDownWithTestInName();
            TestSuite suite = new TestSuite("SetUpAndTearDownSuite");
            suite.Add(testFixture);
            suite.Run(NullListener.NULL);

            Assert.AreEqual(1, testFixture.setUpCount);
            Assert.AreEqual(1, testFixture.tearDownCount);
            Assert.AreEqual(2, suite.CountTestCases());
            Assert.AreEqual(2, ((TestSuite)suite.Tests[0]).Tests.Count);
        }

        [Test]
        public void RunningSingleMethodCallsSetUpAndTearDown()
        {
            SetUpAndTearDownFixture testFixture = new SetUpAndTearDownFixture();
            TestSuite suite = new TestSuite("SetUpAndTearDownSuite");
            suite.Add(testFixture);
            TestSuite fixtureSuite = (TestSuite)suite.Tests[0];
            NUnit.Core.TestCase testCase = (NUnit.Core.TestCase)fixtureSuite.Tests[0];

            suite.Run(NullListener.NULL);

            Assert.AreEqual(1, testFixture.setUpCount);
            Assert.AreEqual(1, testFixture.tearDownCount);
        }

        [Ignore("Do Not Run This")]
        internal class IgnoredFixture
        {
            public bool setupCalled = false;
            public bool teardownCalled = false;

            [TestFixtureSetUp]
            public virtual void ShouldNotRun()
            {
                setupCalled = true;
            }

            [TestFixtureTearDown]
            public virtual void NeitherShouldThis()
            {
                teardownCalled = true;
            }

            [Test]
            public void Success() { }

            [Test]
            public void EvenMoreSuccess() { }
        }

        [Test]
        public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown()
        {
            IgnoredFixture testFixture = new IgnoredFixture();
            TestSuite suite = new TestSuite("IgnoredFixtureSuite");
            suite.Add(testFixture);
            TestSuite fixtureSuite = (TestSuite)suite.Tests[0];
            NUnit.Core.TestCase testCase = (NUnit.Core.TestCase)fixtureSuite.Tests[0];

            fixtureSuite.Run(NullListener.NULL);
            Assert.IsFalse(testFixture.setupCalled, "TestFixtureSetUp called running fixture");
            Assert.IsFalse(testFixture.teardownCalled, "TestFixtureTearDown called running fixture");

            suite.Run(NullListener.NULL);
            Assert.IsFalse(testFixture.setupCalled, "TestFixtureSetUp called running enclosing suite");
            Assert.IsFalse(testFixture.teardownCalled, "TestFixtureTearDown called running enclosing suite");

            testCase.Run(NullListener.NULL);
            Assert.IsFalse(testFixture.setupCalled, "TestFixtureSetUp called running a test case");
            Assert.IsFalse(testFixture.teardownCalled, "TestFixtureTearDown called running a test case");
        }

        internal class FixtureWithNoTests
        {
            internal bool setupCalled = false;
            internal bool teardownCalled = false;

            [TestFixtureSetUp]
            public virtual void Init()
            {
                setupCalled = true;
            }

            [TestFixtureTearDown]
            public virtual void Destroy()
            {
                teardownCalled = true;
            }
        }

        [Test]
        public void FixtureWithNoTestsShouldNotCallFixtureSetUpOrTearDown()
        {
            FixtureWithNoTests testFixture = new FixtureWithNoTests();
            TestSuite suite = new TestSuite("NoTestsFixtureSuite");
            suite.Add(testFixture);
            TestSuite fixtureSuite = (TestSuite)suite.Tests[0];

            fixtureSuite.Run(NullListener.NULL);
            Assert.IsFalse(testFixture.setupCalled, "TestFixtureSetUp called running fixture");
            Assert.IsFalse(testFixture.teardownCalled, "TestFixtureTearDown called running fixture");

            suite.Run(NullListener.NULL);
            Assert.IsFalse(testFixture.setupCalled, "TestFixtureSetUp called running enclosing suite");
            Assert.IsFalse(testFixture.teardownCalled, "TestFixtureTearDown called running enclosing suite");
        }
        */
    }
}


text:
#ifndef DOT_SCENELOADER_H
#define DOT_SCENELOADER_H

// Includes
#include <OgreString.h>
#include <OgreVector3.h>
#include <OgreQuaternion.h>
#include <OgreResourceGroupManager.h>
#include <vector>

#include "rapidxml.hpp"

    // Forward declarations
    namespace Ogre
    {
        class SceneManager;
        class SceneNode;
        class TerrainGroup;
        class TerrainGlobalOptions;
    }

    namespace Forests
    {
        class PagedGeometry;
        class TreeLoader3D;
        class GrassLoader;
        class GrassLayer;
    }

    class nodeProperty
    {
    public:
        Ogre::String nodeName;
        Ogre::String propertyNm;
        Ogre::String valueName;
        Ogre::String typeName;

        nodeProperty(const Ogre::String &node, const Ogre::String &propertyName, const Ogre::String &value, const Ogre::String &type)
            : nodeName(node), propertyNm(propertyName), valueName(value), typeName(type) {}
    };

    class DotSceneLoader
    {
    public:
        Ogre::TerrainGlobalOptions *mTerrainGlobalOptions;

        DotSceneLoader();
        virtual      ~DotSceneLoader();

        void         parseDotScene(const Ogre::String &SceneName, const Ogre::String &groupName, Ogre::SceneManager *yourSceneMgr, Ogre::SceneNode *pAttachNode = NULL, const Ogre::String &sPrependNode = "");
        Ogre::String getProperty(const Ogre::String &ndNm, const Ogre::String &prop);

        Ogre::String getResourceLocationBaseDir(){ return resLocationsBaseDir; };
        void         setResourceLocationBaseDir( Ogre::String newBaseDir ){ resLocationsBaseDir = newBaseDir; };

        Ogre::TerrainGroup* getTerrainGroup() { return mTerrainGroup; }

        std::vector<nodeProperty>               nodeProperties;
        std::vector<Ogre::String>               staticObjects;
        std::vector<Ogre::String>               dynamicObjects;
        std::vector<Forests::PagedGeometry *>   mPGHandles;
        std::vector<Forests::TreeLoader3D *>    mTreeHandles;
        Forests::GrassLoader*                   mGrassLoaderHandle;   /** Handle to Forests::GrassLoader object */
        std::vector<Ogre::ParticleSystem *>     particleSystemList;	// contains all the Particle Systems created

    protected:
        void processScene(rapidxml::xml_node<>* XMLRoot);

        void processNodes(rapidxml::xml_node<>* XMLNode);
        void processExternals(rapidxml::xml_node<>* XMLNode);
        void processEnvironment(rapidxml::xml_node<>* XMLNode);
        void processResourceLocations(rapidxml::xml_node<>* XMLNode);
        void processTerrain(rapidxml::xml_node<>* XMLNode);
        void processTerrainPage(rapidxml::xml_node<>* XMLNode);
        void processGrassLayers(rapidxml::xml_node<>* XMLNode);
        void processBlendmaps(rapidxml::xml_node<>* XMLNode);
        void processUserDataReference(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent = 0);
        void processUserDataReference(rapidxml::xml_node<>* XMLNode, Ogre::Entity *pEntity);
        void processOctree(rapidxml::xml_node<>* XMLNode);
        void processLight(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent = 0);
        void processCamera(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent = 0);

        void processNode(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent = 0);
        void processLookTarget(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processTrackTarget(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processEntity(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processSubEntity(rapidxml::xml_node<>* XMLNode, Ogre::Entity *pEntity);
        void processParticleSystem(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processBillboardSet(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processPlane(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);
        void processPagedGeometry(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent);

        void processFog(rapidxml::xml_node<>* XMLNode);
        void processSkyBox(rapidxml::xml_node<>* XMLNode);
        void processSkyDome(rapidxml::xml_node<>* XMLNode);
        void processSkyPlane(rapidxml::xml_node<>* XMLNode);
        void processClipping(rapidxml::xml_node<>* XMLNode);

        void processLightRange(rapidxml::xml_node<>* XMLNode, Ogre::Light *pLight);
        void processLightAttenuation(rapidxml::xml_node<>* XMLNode, Ogre::Light *pLight);

        Ogre::String getAttrib(rapidxml::xml_node<>* XMLNode, const Ogre::String &parameter, const Ogre::String &defaultValue = "");
        Ogre::Real getAttribReal(rapidxml::xml_node<>* XMLNode, const Ogre::String &parameter, Ogre::Real defaultValue = 0);
        bool getAttribBool(rapidxml::xml_node<>* XMLNode, const Ogre::String &parameter, bool defaultValue = false);

        Ogre::Vector3 parseVector3(rapidxml::xml_node<>* XMLNode);
        Ogre::Quaternion parseQuaternion(rapidxml::xml_node<>* XMLNode);
        Ogre::ColourValue parseColour(rapidxml::xml_node<>* XMLNode);

        Ogre::SceneManager *mSceneMgr;
        Ogre::SceneNode *mAttachNode;
        Ogre::String m_sGroupName;
        Ogre::String m_sPrependNode;
        Ogre::TerrainGroup* mTerrainGroup;
        Ogre::Vector3 mTerrainPosition;
        Ogre::Vector3 mLightDirection;

        // paged geometry related values
        int mPGPageSize;
        int mPGDetailDistance;
        // resource locations basedir
        Ogre::String resLocationsBaseDir;
    };

#endif // DOT_SCENELOADER_H


text:
'''
Created on 12. 10. 2016

@author: neneko
'''

from lxml import etree

try:
    from StringIO import StringIO
except ImportError:
    from io import BytesIO as StringIO

import hashlib
import uuid
from eet_ns import *
from string import Template
import base64
from utils import find_node

envelope_template = Template('''<${soap}:Envelope xmlns:${soap}="${soap_url}">
<${soap_env}:Header xmlns:${soap_env}="${soap_env_url}">
            <${wsse}:Security xmlns:${wsse}="${wsse_url}" xmlns:${wsu}="${wsu_url}" ${soap}:mustUnderstand="1">
               <${wsse}:BinarySecurityToken ${wsu}:Id="${cert_id}" EncodingType="${encoding_base64_url}" ValueType="${value_x509_url}">${sec_token}</${wsse}:BinarySecurityToken>
               <${ds}:Signature xmlns:${ds}="${ds_url}" Id="${sig_id}">
                  <${ds}:SignedInfo xmlns:${ds}="${ds_url}">
                     <${ds}:CanonicalizationMethod Algorithm="${ec_url}">
                        <${ec}:InclusiveNamespaces xmlns:${ec}="${ec_url}" PrefixList="${soap}"/>
                     </${ds}:CanonicalizationMethod>
                     <${ds}:SignatureMethod Algorithm="${algo_sha256}"/>
                     <${ds}:Reference URI="#${body_id}">
                        <${ds}:Transforms>
                           <${ds}:Transform Algorithm="${ec_url}">
                              <${ec}:InclusiveNamespaces xmlns:${ec}="${ec_url}" PrefixList=""/>
                           </${ds}:Transform>
                        </${ds}:Transforms>
                        <${ds}:DigestMethod Algorithm="${algo_digest_sha256}"/>
                        <${ds}:DigestValue></${ds}:DigestValue>
                     </${ds}:Reference>
                  </${ds}:SignedInfo>
                  <${ds}:SignatureValue></${ds}:SignatureValue>
                  <${ds}:KeyInfo Id="${key_id}">
                     <${wsse}:SecurityTokenReference ${wsu}:Id="${sec_token_id}">
                        <${wsse}:Reference URI="#${cert_id}" ValueType="${value_x509_url}"/>
                     </${wsse}:SecurityTokenReference>
                  </${ds}:KeyInfo>
               </${ds}:Signature>
            </${wsse}:Security>
         </${soap_env}:Header>
         <${soap}:Body wsu:Id="${body_id}" xmlns:${wsu}="${wsu_url}" xmlns:${soap}="${soap_url}"></${soap}:Body>
</${soap}:Envelope>''')

namespaces_dict = {
    'soap': NS_SOAP,
    'soap_url': NS_SOAP_URL,
    'soap_env': NS_SOAP_ENV,
    'soap_env_url': NS_SOAP_ENV_URL,
    'wsse': NS_WSSE,
    'wsse_url': NS_WSSE_URL,
    'wsu': NS_WSU,
    'wsu_url': NS_WSU_URL,
    'ds': NS_DS,
    'ds_url': NS_DS_URL,
    'ec': NS_EC,
    'ec_url': NS_EC_URL,
    'eet_url': NS_EET_URL,
    'algo_sha256': ALGORITHM_SHA256,
    'algo_digest_sha256': ALGORITHM_DIGEST_SHA256,
    'value_x509_url': VALUE_X509_URL,
    'encoding_base64_url': ENCODING_BASE64_URL

}

def get_normalized_subtree(node, includive_prefixes=[]):
    tree = etree.ElementTree(node)
    ss = StringIO()
    tree.write_c14n(
        ss, exclusive=True, inclusive_ns_prefixes=includive_prefixes)
    return ss.getvalue()

def calculate_node_digest(node):
    data = get_normalized_subtree(node, ['soap'])
    return hashlib.sha256(data).digest()

def soap_wsse(payload_node, signing):
    '''Stores payload_node into a SOAP envelope and calculates the wsse signature

    Keyword arguments:
    payload_node - top node for the payload (lxml.Element)
    signing - signing object (eet.Signing)
    '''
    # Prepare parser
    parser = etree.XMLParser(remove_blank_text=True, ns_clean=False)
    # Prepare IDs for header
    body_id = 'id-'+uuid.uuid4().hex
    cert_id = 'X509-'+uuid.uuid4().hex
    sig_id = 'SIG-' + uuid.uuid4().hex
    key_id = 'KI-'+ uuid.uuid4().hex
    sec_token_id='STR-'+ uuid.uuid4().hex

    values = dict(namespaces_dict)
    values.update({'body_id': body_id, 'cert_id': cert_id, 'sig_id': sig_id, 'key_id':
                   key_id, 'sec_token_id': sec_token_id, 'sec_token': base64.b64encode(signing.get_cert_binary()).decode('utf8')})

    # Create SOAP envelope
    envelope = etree.XML(envelope_template.substitute(values), parser=parser)

    # Find soap:Body
    body = find_node(envelope, 'Body', NS_SOAP_URL)
    # Fill in Trzby into soap:Body
    body.append(payload_node)
    # Calculate digest of soap:Body
    body_digest = calculate_node_digest(body)

    # Find ds:DigestValue and store the computed digest
    digest_node = find_node(envelope, 'DigestValue', NS_DS_URL)
    digest_node.text = base64.b64encode(body_digest)

    # Find ds:SignedInfo node and get normalized text of it
    signature_node = find_node(envelope, 'SignedInfo', NS_DS_URL)
    normalized_signing = get_normalized_subtree(signature_node, ['soap'])

    # FInd ds:SignatureValue and store there signature of ds:SignedInfo
    signature_value_node = find_node(envelope, 'SignatureValue', NS_DS_URL)
    signature_value_node.text = base64.b64encode(
        signing.sign_text(normalized_signing, 'sha256'))

    return envelope


text:
import { Entity } from "../../../../../../../src/decorator/entity/Entity"
import { Column } from "../../../../../../../src/decorator/columns/Column"
import { PrimaryColumn } from "../../../../../../../src/decorator/columns/PrimaryColumn"
import { JoinTable } from "../../../../../../../src/decorator/relations/JoinTable"
import { OneToMany } from "../../../../../../../src/decorator/relations/OneToMany"
import { ManyToOne } from "../../../../../../../src/decorator/relations/ManyToOne"
import { Post } from "./Post"
import { Image } from "./Image"

@Entity()
export class Category {
    @PrimaryColumn()
    id: number

    @PrimaryColumn()
    code: number

    @Column()
    name: string

    @Column()
    isRemoved: boolean = false

    @OneToMany((type) => Post, (post) => post.category)
    posts: Post[]

    @ManyToOne((type) => Image, (image) => image.categories)
    @JoinTable()
    image: Image

    postIds: number[]

    imageId: number[]
}


text:
Overdose is a Dependency Injection framework that provides an Inversion of Control container to describe, load and inject Objects. The container enables decoupling of modules and the dependencies of a module to be injected.

Read a more elaborate introduction in the [introduction
documentation](https://github.com/mattijs/overdose/tree/master/docs/01-introduction.md).

## Install

Installation goes through [npm](https://npmjs.org):
```
$ npm install [--production] overdose
```
Overdose does not have any dependencies except for running the tests.

## Test

Tests are written using [tap](https://github.com/isaacs/node-tap) and can be run with npm if all dev-dependencies are installed:
```
$ npm install overdose
$ npm test
```
If you want to run individual tests use this, where name is substituted for the test name:
```
$ node test/{NAME}.test.js
```

## License

This module is licensed under the MIT License. See the `LICENSE` file for more details.

# Documentation

Listing all the documentation here is way too much and it would become useless. Only a short version of the API is listed here and extended documentation and examples can be found in [the docs folder](https://github.com/mattijs/overdose/tree/master/docs).

## Container API

The Dependency Injection container. For the complete API see the
[container](https://github.com/mattijs/overdose/tree/master/docs/03-container.md) chapter.

### constructor

Construct a new Container. The constructor takes no arguments.

### register(definition, service)

Register an existing service with the container. The definition should contain at least a `name` key and can optionally contain a list of dependencies.

### load(name, definition)

Load a service from a module into the container. The definition should at least contain a `name` and `module` key and can optionally contain a list of dependencies.

### provide(definition, provider)

Load a service into the container using a provider function. The definition should at least contain a `name` key and can optionally contain a list of dependencies.

### get(name)

Get a service from the container. Throws an Error when the service is not registered.

### has(name)

Check if the container has a service registered under a name.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>se.mah.elis.adaptor.fooprovider</groupId>
  <artifactId>mock-energy-data-provider</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>bundle</packaging>
  <name>Mock energy data provider</name>
  <dependencies>
  	<dependency>
  		<groupId>org.osgi</groupId>
  		<artifactId>org.osgi.core</artifactId>
  		<version>4.3.1</version>
  	</dependency>
  	<dependency>
  		<groupId>org.osgi</groupId>
  		<artifactId>org.osgi.compendium</artifactId>
  		<version>4.3.1</version>
  	</dependency>
  	<dependency>
  		<groupId>org.apache.felix</groupId>
  		<artifactId>org.apache.felix.scr.annotations</artifactId>
  		<version>1.9.6</version>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.services.users</groupId>
  		<artifactId>user-service</artifactId>
  		<version>2.0.0-SNAPSHOT</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.adaptor.device.api</groupId>
  		<artifactId>device-api</artifactId>
  		<version>1.0.0-SNAPSHOT</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.data</groupId>
  		<artifactId>elis-data-definitions</artifactId>
  		<version>2.0.0-SNAPSHOT</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.exceptions</groupId>
  		<artifactId>elis-exceptions</artifactId>
  		<version>1.0.0</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>joda-time</groupId>
  		<artifactId>joda-time</artifactId>
  		<version>2.3</version>
  	</dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>    <!-- (2) START -->
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.4.0</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
          	<Bundle-ActivationPolicy>lazy</Bundle-ActivationPolicy>
            <Export-Package>${project.groupId}</Export-Package>
          </instructions>
        </configuration>
      </plugin>    <!-- (2) END -->
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-scr-plugin</artifactId>
        <version>1.14.0</version>
        <executions>
          <execution>
            <id>generate-scr-scrdescriptor</id>
            <goals>
              <goal>scr</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <parent>
  	<groupId>se.mah.elis</groupId>
  	<artifactId>super-pom</artifactId>
  	<version>1.0.0</version>
  	<relativePath>../super</relativePath>
  </parent>
</project>


text:
/*global Reply*/
/**

  A Gambit is a Trigger + Reply or Reply Set
  - We define a Reply as a subDocument in Mongo.

**/

// var regexreply = require("../parse/regexreply");

module.exports = function (mongoose, facts) {
  var Utils = require("../utils");
  var regexreply = require("../../node_modules/ss-parser/lib/regexreply");
  var debug = require("debug")("Gambit");
  var async = require("async");
  var norm = require("node-normalizer");
  var findOrCreate = require("mongoose-findorcreate");
  var Common = require("./common");
  var gNormalizer;

  norm.loadData(function () {
    gNormalizer = norm;
    debug("Normaizer Loaded.");
  });

  /**

    I trigger is the matching rule behind a piece of input. It lives in a topic or several topics.
    A trigger also contains one or more replies.

  **/

  var gambitSchema = new mongoose.Schema({
    id: {type: String, index: true, default: Utils.genId()},

    // This is the input string that generates a rule,
    // In the event we want to export this, we will use this value.
    // Make this filed conditionally required if trigger is supplied
    input: {type: String},

    // The Trigger is a partly baked regex.
    trigger: {type: String, index: true},

    // If the trigger is a Question Match
    isQuestion: {type: Boolean, default: false},

    // If the trigger is a Answer Type Match
    qType: {type: String, default: ""},
    qSubType: {type: String, default: ""},

    // The filter function for the the expression
    filter: {type: String, default: ""},

    // An array of replies.
    replies: [{ type: String, ref: "Reply"}],

    // Save a reference to the parent Reply, so we can walk back up the tree
    parent: { type: String, ref: 'Reply' },

    // This will redirect anything that matches elsewhere.
    // If you want to have a conditional rediect use reply redirects
    // TODO, change the type to a ID and reference another gambit directly
    // this will save us a lookup down the road (and improve performace.)
    redirect: {type: String, default: ""}
  });

  gambitSchema.pre("save", function (next) {
    var self = this;

    // FIXME: This only works when the replies are populated which is not always the case.
    // self.replies = _.uniq(self.replies, function(item, key, id) {
    //   return item.id;
    // });

    // If input was supplied, we want to use it to generate the trigger
    if (self.input) {
      var input = gNormalizer.clean(self.input);
      // We want to convert the input into a trigger.
      regexreply.parse(Utils.quotemeta(input, true), facts, function (trigger) {
        self.trigger = trigger;
        next();
      });
    } else {
      // Otherwise we populate the trigger normally
      next();
    }
  });

  gambitSchema.methods.addReply = function (replyData, callback) {
    var self = this;
    if (!replyData) {
      return callback("No data");
    }

    var reply = new Reply(replyData);
    reply.save(function (err) {
      if (err) {
        return callback(err);
      }
      self.replies.addToSet(reply._id);
      self.save(function (err) {
        callback(err, reply);
      });
    });
  };

  gambitSchema.methods.doesMatch = function (message, callback) {
    Common.doesMatch(this.trigger, message, null, callback);
  };

  gambitSchema.methods.clearReplies = function (callback) {
    var self = this;

    var clearReply = function (replyId, cb) {
      self.replies.pull({ _id: replyId });
      Reply.remove({ _id: replyId }, function (err) {
        if (err) {
          console.log(err);
        }

        debug('removed reply ' + replyId);

        cb(null, replyId);
      });
    };

    async.map(self.replies, clearReply, function (err, clearedReplies) {
      self.save(function (err2) {
        callback(err2, clearedReplies);
      });
    });
  };

  gambitSchema.methods.getRootTopic = function (cb) {
    var self = this;
    if (!self.parent) {
      Topic.findOne({ gambits: { $in: [ self._id ] } }).exec(function (err, doc) {
        cb(err, doc.name);
      });
    } else {
      Common.walkGambitParent(self._id, function (err, gambits) {
        if (gambits.length !== 0) {
          Topic.findOne({ gambits: { $in: [ gambits.pop() ] } }).exec(function (err, topic) {
            cb(null, topic.name);
          });
        } else {
          cb(null, "random");
        }
      });
    }
  };

  gambitSchema.plugin(findOrCreate);

  try {
    return mongoose.model("Gambit", gambitSchema);
  } catch(e) {
    return mongoose.model("Gambit");
  }
};


text:
package uk.co.visalia.brightpearl.apiclient.client.multimessage;

/**
 * For internal use only. Multimessage response bodies are contained within a content element, and this type is used
 * to receive the escaped JSON response it contains.
 */
public final class MultiMessageResponseItemBody {

    private String content;

    public String getContent() {
        return content;
    }
}


text:
from django.shortcuts import get_object_or_404
from django.template import Context, loader as template_loader
from django.conf import settings

from rest_framework import decorators, permissions, viewsets, status
from rest_framework.renderers import JSONPRenderer, JSONRenderer, BrowsableAPIRenderer
from rest_framework.response import Response

from projects.models import Project

@decorators.api_view(['GET'])
@decorators.permission_classes((permissions.AllowAny,))
@decorators.renderer_classes((JSONRenderer, JSONPRenderer, BrowsableAPIRenderer))
def footer_html(request):
    project_slug = request.GET.get('project', None)
    version_slug = request.GET.get('version', None)
    page_slug = request.GET.get('page', None)
    theme = request.GET.get('theme', False)
    docroot = request.GET.get('docroot', '')
    subproject = request.GET.get('subproject', False)
    source_suffix = request.GET.get('source_suffix', '.rst')

    new_theme = (theme == "sphinx_rtd_theme")
    using_theme = (theme == "default")
    project = get_object_or_404(Project, slug=project_slug)
    version = project.versions.get(slug=version_slug)
    main_project = project.main_language_project or project

    context = Context({
        'project': project,
        'downloads': version.get_downloads(pretty=True),
        'current_version': version.slug,
        'versions': project.ordered_active_versions(),
        'main_project': main_project,
        'translations': main_project.translations.all(),
        'current_language': project.language,
        'using_theme': using_theme,
        'new_theme': new_theme,
        'settings': settings,
        'subproject': subproject,
        'github_url': version.get_github_url(docroot, page_slug, source_suffix),
        'bitbucket_url': version.get_bitbucket_url(docroot, page_slug, source_suffix),
    })

    html = template_loader.get_template('restapi/footer.html').render(context)
    return Response({
        'html': html,
        'version_active': version.active,
        'version_supported': version.supported,
    })


text:
package gw.plugin.ij.lang.psi.impl.statements.typedef;

import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.StubBasedPsiElement;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.util.IncorrectOperationException;
import gw.lang.parser.IExpression;
import gw.plugin.ij.lang.parser.GosuCompositeElement;
import gw.plugin.ij.lang.psi.api.statements.typedef.IGosuReferenceList;
import gw.plugin.ij.lang.psi.api.types.IGosuCodeReferenceElement;
import gw.plugin.ij.lang.psi.impl.GosuBaseElementImpl;
import gw.plugin.ij.lang.psi.impl.GosuClassReferenceType;
import gw.plugin.ij.lang.psi.stubs.GosuReferenceListStub;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;

public abstract class GosuReferenceListImpl extends GosuBaseElementImpl<IExpression, GosuReferenceListStub>
    implements StubBasedPsiElement<GosuReferenceListStub>, IGosuReferenceList {
  @Nullable
  private PsiClassType[] cachedTypes;

  public GosuReferenceListImpl(@NotNull GosuCompositeElement node) {
    super(node);
  }

  public GosuReferenceListImpl(@NotNull final GosuReferenceListStub stub, @NotNull IStubElementType elementType) {
    super(stub, elementType);
  }

  @NotNull
  public IGosuCodeReferenceElement[] getReferenceElements() {
    return findChildrenByClass(IGosuCodeReferenceElement.class);
  }

  @NotNull
  public PsiClassType[] getReferenceTypes() {
    final GosuReferenceListStub stub = getStub();
    if (stub != null) {
      return stub.getReferencedTypes();
    }

    if (cachedTypes == null || !isValid()) {
      final ArrayList<PsiClassType> types = new ArrayList<>();
      for (IGosuCodeReferenceElement ref : getReferenceElements()) {
        types.add(new GosuClassReferenceType(ref));
      }
      cachedTypes = types.toArray(new PsiClassType[types.size()]);
    }
    return cachedTypes;
  }

  @Override
  public void subtreeChanged() {
    cachedTypes = null;
  }

  @NotNull
  @Override
  public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
    throw new UnsupportedOperationException();
//    if( element instanceof IGosuCodeReferenceElement && findChildByClass( IGosuCodeReferenceElement.class ) != null )
//    {
//      PsiElement lastChild = getLastChild();
//      lastChild = PsiUtil.skipWhitespaces( lastChild, false );
//      if( !lastChild.getNode().getElementType().equals( GosuTokenTypes.mCOMMA ) )
//      {
//        getNode().addLeaf( GosuTokenTypes.mCOMMA, ",", null );
//      }
//      return super.add( element );
//    }
//    else
//    {
//      return super.add( element );
//    }
  }
}


text:
namespace Rouge
{
    partial class MainForm
    {
        /// <summary>
        /// 必要なデザイナー変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 使用中のリソースをすべてクリーンアップします。
        /// </summary>
        /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows フォーム デザイナーで生成されたコード

        /// <summary>
        /// デザイナー サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディターで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.label3 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.button6 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(14, 137);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(32, 12);
            this.label3.TabIndex = 10;
            this.label3.Text = "wait...";
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(14, 102);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(355, 32);
            this.button3.TabIndex = 9;
            this.button3.Text = "Generate";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(318, 41);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(51, 23);
            this.button2.TabIndex = 5;
            this.button2.Text = "...";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(38, 43);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(274, 19);
            this.textBox2.TabIndex = 4;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(5, 46);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(27, 12);
            this.label2.TabIndex = 3;
            this.label2.Text = "dest";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(318, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(51, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "...";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(14, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(18, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "dir";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(38, 14);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(274, 19);
            this.textBox1.TabIndex = 1;
            //
            // button4
            //
            this.button4.Location = new System.Drawing.Point(16, 170);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(183, 23);
            this.button4.TabIndex = 11;
            this.button4.Text = "Generate keys...";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            //
            // button5
            //
            this.button5.Location = new System.Drawing.Point(318, 70);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(51, 23);
            this.button5.TabIndex = 8;
            this.button5.Text = "...";
            this.button5.UseVisualStyleBackColor = true;
            this.button5.Click += new System.EventHandler(this.button5_Click);
            //
            // textBox3
            //
            this.textBox3.Location = new System.Drawing.Point(38, 72);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(274, 19);
            this.textBox3.TabIndex = 7;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(5, 75);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(29, 12);
            this.label4.TabIndex = 6;
            this.label4.Text = "pkey";
            //
            // button6
            //
            this.button6.Location = new System.Drawing.Point(205, 170);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(164, 23);
            this.button6.TabIndex = 12;
            this.button6.Text = "Sign to file...";
            this.button6.UseVisualStyleBackColor = true;
            this.button6.Click += new System.EventHandler(this.button6_Click);
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(381, 205);
            this.Controls.Add(this.button6);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "MainForm";
            this.Text = "Krile Patch Generator";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Button button6;

    }
}


text:
var router = require('express').Router(),
    fs = require('fs'),
    path = require('path'),
    formidable = require('formidable'),
    Profile = require("./../models/profile");

// to handle profile pic upload
router.post('/profilePic', function(req,res,next) {
  var form = new formidable.IncomingForm(),
      userId = null,
      sendResponse = function(err,tempUrl) {
        if ( err ) {
          res.send( JSON.stringify( {error:err}) );
        }else{
          // updating user-profile in MogoDB
          Profile.findOneAndUpdate( {'userId': userId}, {imageLink:tempUrl}, {upsert:false}, function(err, doc){
            if (err)
              return res.send(500, { error: 'MONGOERROR' });
            res.send( JSON.stringify( {error:null, tempUrl: doc.imageLink}) );
          });
        }
      };

  // make 'public/temp' directory if it doesn't exist
  try {
    fs.mkdirSync('public/temp');
  } catch(e) {
    if ( e.code != 'EEXIST' ) {
      throw e;
    }
  }
  // Send response only when file is saved to sever. (Hence the async callback)
  (function(callback) {
    var isImageType,
        tempUrl,
        overwritePic = function(oldFilePath, tempFilePath, renamePath) {
          var fileName = path.basename(oldFilePath);
          console.log('Overwriting the pic uploaded: ' + fileName);
          fs.unlink(oldFilePath, function (err) {
            if (err) {
              console.log(err);
              return callback( 'CANTDELETE', null );
            } else {
              // Rename the file to match the filename that the user uploaded
              fs.rename(tempFilePath, 'public/' + renamePath, function (err) {
                if (err) {
                  console.log(err);
                  return callback( 'PERMISSIONERROR', null );
                }else{
                  console.log('No rename error');
                  tempUrl = renamePath;
                  callback( null, tempUrl );
                }
              });
            }
          });
        },
        deleteTempFile = function(filePath) {
          console.log('Deleting file...');
          fs.unlink(filePath, function (err) {
            if (err)
              return console.log(err);
          });
        };
    form.uploadDir = process.cwd() + '/public/temp';
    form.on( 'field', function( name, value ) {
      userId = value;
    });
    form.on('file', function(field, file) {
      isImageType = /image\/(jpeg|gif|png)/.test(file.type);
      if ( !isImageType ) {
        deleteTempFile(file.path); // Uploaded file is not an image, so delete it
        callback('NOTIMAGE',null);
      }else {
        var newName = userId + '_' + file.name,// append username to the file to avoid name collisions
            destFile = path.dirname(file.path) + '/' + newName;
            tempUrl = 'images/userProfileImages/' + newName;
        try {
          var stats = fs.statSync(destFile);
          if ( stats.isFile() ) {
            return overwritePic(destFile, file.path, tempUrl);// overwrite the previous file
          }
        }catch(e) {
          // Rename the file to match the filename that the user uploaded
          fs.rename(file.path, 'public/' + tempUrl, function (err) {
            if (err) {
              console.log(err);
              return callback( 'PERMISSIONERROR', null );
            }else{
              console.log('No rename error');
              if ( userId == null ) {
                while( userId == null ) {
                  if ( userId ) {
                    callback( null, tempUrl );
                    break;
                  }
                }
              } else {
                callback( null, tempUrl );
              }
            }
          }); //end rename
        }
      }

    });
    form.parse(req); // parse the incoming request to get form-data
  })(sendResponse);
});

router.post('/updateProfile', function(req,res,next) {
  var updatedUser = req.body.user;
  Profile.findOne({userId:updatedUser.userId}, function(err,profileData){
    if ( err || !profileData ) {
      console.error(err);
      res.writeHead(500,{'Content-Type':'application/json'});
      res.end( JSON.stringify({ error:'MongoDB error while reading the user profile.'}) );
    }else {
      profileData.name = updatedUser.name;
      profileData.age = updatedUser.age;
      profileData.country = updatedUser.country;
      profileData.emailId = updatedUser.emailId;
      if ( !updatedUser.imageLink.trim() ) {
        updatedUser.imageLink = 'images/userProfileImages/user.png';
      }
      profileData.imageLink = updatedUser.imageLink;
      validateAndSaveProfile( profileData, res );
    }
  });
});

// persist user profile to MongoDB
function validateAndSaveProfile( profileData, res ) {
  var validationError = profileData.validateSync();
  if ( validationError ) {
    console.log('Mongoose validaton error of user profile.');
    console.error(validationError);
    res.writeHead(500,{'Content-Type':'application/json'});
    res.end( JSON.stringify({ error:'Mongoose validaton error of user profile.'}) );
  } else {
    profileData.save( function(err, updatedUserProfile ) {
      if ( err ) {
        console.log('Could not save the updated user profile to MongoDB!');
        console.error(err);
        res.writeHead(500,{'Content-Type':'application/json'});
        res.end( JSON.stringify({ error:'Could not save the updated user profile to MongoDB!'}) );
      }else {
        console.log("User profile updated sucessfully!!\n");
        res.end( JSON.stringify({ error:null, updatedUserProfile: updatedUserProfile }) );
      }
    }); //end save
  }
}

module.exports = router;


text:
require 'spec_helper'
require 'sneakers'
require 'sneakers/cli'
require 'sneakers/runner'

describe Sneakers::CLI do
  describe "#work" do
    before do
      any_instance_of(Sneakers::Runner) do |runner|
        stub(runner).run{ true }
      end
    end

    after do
      # require cleanup
      Object.send(:remove_const, :TitleScraper) if Object.constants.include?(:TitleScraper)
    end

    describe 'with dirty class loading' do
      it "should perform a run" do
        any_instance_of(Sneakers::Runner) do |runner|
          mock(runner).run{ true }
        end
        out = capture_io{ Sneakers::CLI.start [
          'work',
          "TitleScraper",
          "--require=#{File.expand_path('../fixtures/require_worker.rb', File.dirname(__FILE__))}"
        ]}.join ''

        out.must_match(/Workers.*:.*TitleScraper.*/)

      end

      it "should be able to run as front-running process" do
        out = capture_io{ Sneakers::CLI.start [
          'work',
          "TitleScraper",
          "--require=#{File.expand_path('../fixtures/require_worker.rb', File.dirname(__FILE__))}"
        ]}.join ''

        out.must_match(/Log.*Console/)
      end

      it "should be able to run as daemonized process" do
        out = capture_io{ Sneakers::CLI.start [
          'work',
          "TitleScraper",
          "--daemonize",
          "--require=#{File.expand_path('../fixtures/require_worker.rb', File.dirname(__FILE__))}"
        ]}.join ''

        out.must_match(/sneakers.log/)
      end
    end

    it "should fail when no workers found" do
      out = capture_io{ Sneakers::CLI.start ['work', 'TitleScraper'] }.join ''
      out.must_match(/Missing workers: TitleScraper/)
    end

    it "should run all workers when run without specifying any" do
      out = capture_io{ Sneakers::CLI.start [
        "work",
        "--require=#{File.expand_path("../fixtures/require_worker.rb", File.dirname(__FILE__))}"
      ]}.join ''

      out.must_match(/Workers.*:.*TitleScraper.*/)
    end

    after do
      # require cleanup
      Object.send(:remove_const, :TitleScraper) if Object.constants.include?(:TitleScraper)
    end
  end
end


text:
layout: archive
title: Archive
permalink: /archive/
category: "all"
---


text:
import json;
import os;
import numpy as np;

def CreateDataBundle(config):
#     dataPath = config["dataPath"]; #'/Users/zhaot/Work/neutube/neurolabi/data';
    sessionPath = config["sessionPath"]; #dataPath + '/flyem/FIB/skeletonization/session11';
    if config.has_key("swcDir"):
        swcPath = config['swcDir']; #sessionPath + '/' + config['swcDir'];
    else:
        swcPath = sessionPath + '/swc/adjusted';

    swcFileList = list();
    if config.has_key("minBodySize") | config.has_key("maxBodySize"):
        data = np.loadtxt(sessionPath + '/bodies/bodysize.txt', delimiter=',');
        bodyList = data[:, 0];
        bodySize = data[:, 1];
        lowerThreshold = -1;
        upperThreshold = -1;
        if config.has_key("minBodySize"):
            lowerThreshold = config["minBodySize"];
        if config.has_key("maxBodySize"):
            upperThreshold = config["maxBodySize"];

        print lowerThreshold;
        print upperThreshold;
        for i in range(0, len(bodyList)):
#             print bodySize[i];
#             print (bodySize[i] >= lowerThreshold) | (lowerThreshold < 0);
#             print (bodySize[i] <= upperThreshold) | (upperThreshold < 0);
#             print ((bodySize[i] >= lowerThreshold) | (lowerThreshold < 0)) & ((bodySize[i] <= upperThreshold) | (upperThreshold < 0));
            if ((bodySize[i] >= lowerThreshold) | (lowerThreshold < 0)) & ((bodySize[i] <= upperThreshold) | (upperThreshold < 0)):
                print str(int(bodyList[i]));
                swcFileList.append(str(int(bodyList[i])) + '.swc');
    else:
        swcFileList = os.listdir(swcPath);

    print len(swcFileList), " neurons";

    dataBundle = {"neuron": list()};

    neuronClass = {};

    #Add predicted
    if (config["addingClass"]):
#         predictPath = sessionPath + "/predict.txt";
        predictPath = config["predict"];
        if predictPath.endswith(".json"):
            f = open(predictPath);
            classBundle = json.load(f);
            f.close();
            for neuron in classBundle["neuron"]:
                for bodyId in neuron["id"]:
                    neuronClass[bodyId] = neuron["class"];
        else:
            f = open(predictPath);
            lines = f.readlines();
            f.close();
            for line in lines:
                line.strip();
                line = line.replace("_", " ");
                line = line.replace("(", " ");
                line = line.replace(")", " ");
                line = line.replace(":", " ");
                tokens = line.split();
                #print(tokens)
                if len(tokens) > 1:
                    print(int(tokens[1]), tokens[3]);
                    neuronClass[int(tokens[1])] = tokens[3];
                    if tokens[3] == "unknown":
                        neuronClass[int(tokens[1])] = tokens[3] + " " + tokens[4];

    for f in swcFileList:
        if f.endswith('.swc'):
#             print f;
            bodyId = f.split('.')[0];
            neuron = {"id": int(bodyId), "name": "FIB_" + bodyId,
                      "model": swcPath + "/" + f};
            if (config["addingClass"]):
                neuron["class"] = neuronClass[int(bodyId)];
            if config.has_key("objDir"):
                neuron["volume"] = (config["objDir"] + "/" + os.path.basename(f)).replace('.swc', '.obj');
            dataBundle["neuron"].append(neuron);

    otherFields = ["image_resolution", "synapse_scale", "synapse", "source_offset", "source_dimension"];
    for field in otherFields:
        if config.has_key(field):
            dataBundle[field] = config[field];

    # dataBundlePath = sessionPath + "/data_bundle_with_class.json";
    dataBundlePath = config["output"]; #sessionPath + "/data_bundle.json";
    outFile = open(dataBundlePath, "w");
    json.dump(dataBundle, outFile, indent = 2);
    outFile.close();

    print dataBundlePath + " saved";

if __name__ == '__main__':
    dataPath = '/Users/zhaot/Work/neutube/neurolabi/data';
    config = { "sessionPath": dataPath + '/flyem/FIB/skeletonization/session11', "addingClass": False};
    config["output"] = config["sessionPath"] + "/data_bundle.json";
    CreateDataBundle(config);


text:
using System;
using NUnit.Framework;
using ObviousCode.Alchemy.Creatures.DecisionProcessing;

namespace ObviousCode.Alchemy.Creatures.Tests
{
	[TestFixture]
	public class EqualsPredicateTest
	{
		public EqualsPredicateTest ()
		{
		}

		[Test]
		public void WhenEqualsPredicateLoadedWithNonMatchingValues_AnswerShouldBeFalse ()
		{
			EqualsPredicate equals = new EqualsPredicate ();

			equals.Push (new Value (3.5m, "TEST"));
			equals.Push (new Value (6.5m, "TEST"));

			Assert.IsFalse (equals.GetValue ());
		}

		[Test]
		public void WhenEqualsPredicateLoadedWithMatchingValues_AnswerShouldBeFalse ()
		{
			EqualsPredicate equals = new EqualsPredicate ();

			equals.Push (new Value (3.5m, "TEST"));
			equals.Push (new Value (3.5m, "TEST"));

			Assert.IsTrue (equals.GetValue ());
		}

		[Test]
		[ExpectedException (typeof(InvalidOperationException))]
		public void WhenNoValuesAddedToPredicate_Fails ()
		{
			EqualsPredicate equals = new EqualsPredicate ();

			Assert.IsTrue (equals.GetValue ());
		}

		[Test]
		[ExpectedException (typeof(InvalidOperationException))]
		public void WhenOneValueAddedToPredicate_Fails ()
		{
			EqualsPredicate equals = new EqualsPredicate ();

			equals.Push (new Value (23m, "TEST"));

			Assert.IsTrue (equals.GetValue ());
		}

		[Test]
		[ExpectedException (typeof(StackOverflowException))]
		public void WhenThirdValueAddedToPredicate_Fails ()
		{
			EqualsPredicate equals = new EqualsPredicate ();

			equals.Push (new Value (123.456m, "TEST"));
			equals.Push (new Value (123.456m, "TEST"));
			equals.Push (new Value (123.456m, "TEST"));

			Assert.IsTrue (equals.GetValue ());
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1495</FormatID>
      <FormatName>Sibelius</FormatName>
      <FormatVersion>
      </FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>
      </FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Sibelius is a WYSIWYG scorewriter program, created by Sibelius Software (now part of Avid Technology) for Microsoft Windows, Mac OS X, and historically RISC OS. It is used by composers, arrangers, performers, music publishers, teachers and students, particularly for writing classical, jazz, band, vocal, film and television music.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>178</ProvenanceSourceID>
      <ProvenanceName>National Library of New Zealand / National Library of New Zealand</ProvenanceName>
      <ProvenanceSourceDate>11 Feb 2015</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>11 Feb 2015</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/696</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <ExternalSignature>
        <ExternalSignatureID>1569</ExternalSignatureID>
        <Signature>sib</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1025</SignatureID>
        <SignatureName>Sibelius</SignatureName>
        <SignatureNote>.SIBELIUS</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1267</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>0F534942454C495553</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>