text:
package org.apache.skywalking.apm.meter.micrometer;

import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import org.apache.skywalking.apm.toolkit.meter.Histogram;
import org.apache.skywalking.apm.toolkit.meter.MeterId;
import org.junit.Assert;
import org.junit.Test;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MeterBuilderTest {

    @Test
    public void testBuildHistogram() {
        final MeterId meterId = new MeterId("test", MeterId.MeterType.COUNTER,
            Arrays.asList(new MeterId.Tag("k1", "v1")));

        // Build a new distribution config
        final DistributionStatisticConfig statisticConfig = DistributionStatisticConfig.builder()
            .serviceLevelObjectives(Duration.ofMillis(1).toNanos(), Duration.ofMillis(5).toNanos(), Duration.ofMillis(10).toNanos())
            .minimumExpectedValue(0d).build();

        // Check histogram
        final Optional<Histogram> histogramOptional = MeterBuilder.buildHistogram(meterId, true, statisticConfig, true);
        final Histogram histogram = histogramOptional.orElse(null);
        Assert.assertNotNull(histogram);

        // Don't need the histogram
        Assert.assertNull(MeterBuilder.buildHistogram(meterId, true, DistributionStatisticConfig.DEFAULT, true).orElse(null));
    }

    @Test
    public void testConvertId() {
        final List<MeterId.Tag> meterTags = Arrays.asList(new MeterId.Tag("k1", "v1"));

        // Counter type check
        final Meter.Id counterId = new Meter.Id("test", Tags.of("k1", "v1"), null, "test", Meter.Type.COUNTER);
        assertId(MeterBuilder.convertId(counterId, "test"), "test", MeterId.MeterType.COUNTER, meterTags);

        // Gauge type check
        final Meter.Id gaugeId = new Meter.Id("test", Tags.of("k1", "v1"), null, "test", Meter.Type.GAUGE);
        assertId(MeterBuilder.convertId(gaugeId, "test"), "test", MeterId.MeterType.GAUGE, meterTags);

        // Histogram type check
        final Meter.Id otherId = new Meter.Id("test", Tags.of("k1", "v1"), null, "test", Meter.Type.DISTRIBUTION_SUMMARY);
        assertId(MeterBuilder.convertId(otherId, "test"), "test", MeterId.MeterType.HISTOGRAM, meterTags);
    }

    /**
     * Assert the meter id
     */
    private void assertId(MeterId meterId, String name, MeterId.MeterType type, List<MeterId.Tag> tags) {
        Assert.assertEquals(name, meterId.getName());
        Assert.assertEquals(type, meterId.getType());
        Assert.assertEquals(tags, meterId.getTags());
    }

}


text:
$(document).ready(function(){

	$("#msg_action").hide();
	$("#msg").hide();

	changeTag();
	$('#list-category').load(base_url()+'news/loadCategory', { type: 'div' }, function(){
		changeCheckbox();
	});
	$.post(base_url()+'news/loadCategory', { type: 'select' }, function(dataReturn){
		var dataReturnSelect = '<option value="0">--- Categoria principal ---</option>'+dataReturn;
		$('#category_level').html(dataReturnSelect);
	});

	if(document.getElementById("postAddForm") !== null || document.getElementById("postEditForm") !== null){
		$("#title").limiter(50, $("#chars_title"));
		$("#resume").limiter(300, $("#chars_resume"));
	}

	/**
     * Notícias
     *
     */
     // validação ações Posts
    $("#actionPosts").validate({
		rules: {
			action: "required",
			'action_value[]': "required"
		},
		messages: {
			action: "Seleciona uma ação.",
			'action_value[]': ""
		}
	});

    var optionsActionPosts = {
		type: "POST",
		url: base_url()+"news/actionPosts",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg_action')
					.removeClass().addClass("alert alert-success")
					.html("
Registro(s) alterado(s) com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg_action')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();

			}
		}
	};
	$("#actionPosts").ajaxForm(optionsActionPosts);

    // validação cadastro post
    $("#postAddForm").validate({
		rules: {
			title:
			{
				required: true,
				"remote":
                {
                  url: base_url()+'news/checkPost',
                  type: "post",
                  data:
                  {
                      title: function()
                      {
                          return $('#title').val();
                      }
                  }
                }
			},
			description: "required",
			'category[]': "required"
		},
		messages: {
			title:
			{
				required: "Este campo é obrigatório.",
				remote: "Post já cadastrado"
			},
			description: "Este campo é obrigatório.",
			'category[]': ""
		}
	});

	// cadastro post
	var optionsPostAdd = {
		type: "POST",
		url: base_url()+"news/insertPost",
		clearForm: true,
		success: function(data){
			if(data == "success"){
				// remove exibição de imagem
				btnRemove();

				// limpar textarea descrição
				$('.redactor_editor').html('');

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Post cadastrado com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#postAddForm").ajaxForm(optionsPostAdd);

	// validação edição post
    $("#postEditForm").validate({
		rules: {
			description: "required",
			'category[]': "required"
		},
		messages: {
			description: "Este campo é obrigatório.",
			'category[]': ""
		}
	});

	// edição post
	var optionsEditAdd = {
		type: "POST",
		url: base_url()+"news/updatePost",
		clearForm: false,
		success: function(data){
			if(data == "success"){
				// remove exibição de imagem
				btnRemove();

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Post alterado com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);
			}
		}
	};
	$("#postEditForm").ajaxForm(optionsEditAdd);

    // validação ações Tags
    $("#actionTags").validate({
		rules: {
			action: "required",
			'action_value[]': "required"
		},
		messages: {
			action: "Seleciona uma ação.",
			'action_value[]': ""
		}
	});

	var optionsActionTags = {
		type: "POST",
		url: base_url()+"news/actionTags",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg_action')
					.removeClass().addClass("alert alert-success")
					.html("
Registro(s) alterado(s) com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg_action')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout("document.location.reload(true);", 2000);

			}
		}
	};
	$("#actionTags").ajaxForm(optionsActionTags);

     // validação cadastro tags
    $("#tagAddForm").validate({
		rules: {
			tag:
			{
				required: true,
				"remote":
                {
                  url: base_url()+'news/checkTag',
                  type: "post",
                  data:
                  {
                      tag: function()
                      {
                          return $('#tag').val();
                      }
                  }
                }
			}
		},
		messages: {
			tag:
			{
				required: "Este campo é obrigatório.",
				remote: "Tag já cadastrada"
			}
		}
	});

	var optionsTagAdd = {
		type: "POST",
		url: base_url()+"news/insertTag",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Tag cadastrada com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#tagAddForm").ajaxForm(optionsTagAdd);

	// validação edição tags
    $("#tagEditForm").validate({
		rules: {
			tag:
			{
				required: true,
				"remote":
                {
                  url: base_url()+'news/checkTag',
                  type: "post",
                  data:
                  {
                      tag: function()
                      {
                          return $('#tag').val();
                      }
                  }
                }
			}
		},
		messages: {
			tag:
			{
				required: "Este campo é obrigatório.",
				remote: "Tag já cadastrada"
			}
		}
	});

	var optionsTagEdit = {
		type: "POST",
		url: base_url()+"news/updateTag",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Tag salva com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#tagEditForm").ajaxForm(optionsTagEdit);

	// validação cadastro categorias
    $("#categoriesAddForm").validate({
		rules: {
			category:
			{
				required: true,
				"remote":
                {
                  url: base_url()+'news/checkCategory',
                  type: "post",
                  data:
                  {
                      category: function()
                      {
                          return $('#category').val();
                      }
                  }
                }
			}
		},
		messages: {
			category:
			{
				required: "Este campo é obrigatório.",
				remote: "Categoria já cadastrada"
			}
		}
	});

	var optionsCategoriesAdd = {
		type: "POST",
		url: base_url()+"news/insertCategory",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Categoria cadastrada com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#categoriesAddForm").ajaxForm(optionsCategoriesAdd);

	// validação edição categorias
    $("#categoriesEditForm").validate({
		rules: {
			category:
			{
				required: true,
				"remote":
                {
                  url: base_url()+'news/checkCategory',
                  type: "post",
                  data:
                  {
                      category: function()
                      {
                          return $('#category').val();
                      }
                  }
                }
			}
		},
		messages: {
			category:
			{
				required: "Este campo é obrigatório.",
				remote: "Categoria já cadastrada"
			}
		}
	});

	// edição categorias
	var optionsCategoryEdit = {
		type: "POST",
		url: base_url()+"news/updateCategory",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Categoria salva com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#categoriesEditForm").ajaxForm(optionsCategoryEdit);
});

// função para contar caracteres input
(function($) {
    $.fn.extend( {
        limiter: function(limit, elem) {
            $(this).on("keyup focus", function() {
                setCount(this, elem);
            });
            function setCount(src, elem) {
                var chars = src.value.length;
                if (chars > limit) {
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                }
                elem.html( limit - chars );
            }
            setCount($(this)[0], elem);
        }
    });
})(jQuery);

// função para remover exibição de imagem
function btnRemove()
{
	$('#btnRemove').click();
}

function cropPreview(width, height){
//function cropPreview(){
	var boundx;
	var boundy;
	var preview = $('#preview-pane');
	var pcnt = $('#preview-pane .preview-container');
	var pimg = $('#preview-pane .preview-container img');
	var xsize = pcnt.width();
	var ysize = pcnt.height();

	$('#target').Jcrop({
		onChange: updatePreview,
		onSelect: updatePreview,
		aspectRatio: width/height
	}, function(){
		var bounds = this.getBounds();
		boundx = bounds[0];
		boundy = bounds[1];
		jcrop_api = this;
		//preview.appendTo(jcrop_api.ui.holder);
        //jcrop_api.animateTo([100,100,205,205]);
	}, function(){
		$(".jcrop-holder").not(":last").remove();
	});

	function updatePreview(c){
		if (parseInt(c.w) > 0){
			var rx = xsize / c.w;
			var ry = ysize / c.h;
			pimg.css({
				width: Math.round(rx * boundx) + 'px',
				height: Math.round(ry * boundy) + 'px',
				marginLeft: '-' + Math.round(rx * c.x) + 'px',
				marginTop: '-' + Math.round(ry * c.y) + 'px'
			});

			$('#x1').val(c.x);
			$('#y1').val(c.y);
			$('#x2').val(c.x2);
			$('#y2').val(c.y2);
			$('#w').val(c.w);
			$('#h').val(c.h);
		}
	}

	$('button.close').click(function(e){
		$('#target, #target_preview, .jcrop-holder img').attr('src', '');

		//jcrop_api.setSelect([100,100,205,205]);
		$('#sendImage, #image_value, #x, #x2, #y, #y2, #w, #y').val('');
	});

}

function uploadImage(){

	var file_data = $("#sendImage").prop("files")[0];   // Getting the properties of file from file field
	var form_data = new FormData();                  // Creating object of FormData class
	// nome input file
	form_data.append("image", file_data);

	$("#box_image_loader").show()
	$("#box_image").hide();

	$.ajax({
        url: base_url()+'news/addImage',
        dataType: 'html',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         // Setting the data attribute of ajax with file_data
        type: 'post',
        success: function(dataReturn)
        {
        	$("#box_image_loader").hide();
        	$("#box_image").show();

        	var items = dataReturn.split('||');

	    	if(items[0] == 'success'){

	    		$('#target, #target_preview, .jcrop-holder img').attr('src', items[4]+'upload/posts/resize/'+items[1]+'');
	    		$('#image_value').attr('value', items[4]+'upload/posts/resize/'+items[1]+'');

	    		$('#target').on('load', function(){

					$("#cropImage").modal({
						backdrop: 'static',
						keyboard: false
					});

	    		});

	    		//alert(items[2]+', '+items[3]);
	    		cropPreview(items[2], items[3]);
	    		//cropPreview();

			} else {
				//alert('falha');
			}

        }
   });
}

function verificaImageCrop(){
	$.post(base_url()+'news/addImageCrop', $('#coord_image').serialize(), function(dataReturn){
		var items = dataReturn.split('||');
		$('.thumbnail').html('');

		$('#getNameImage').val(items[0]);

		$("#cropImage button.close").trigger('click');
		$('#target, #target_preview, .jcrop-holder img').attr('src', '');
		$('#sendImage, #image_value, #x, #x2, #y, #y2, #w, #y').val('');
	});
}

function changeTag() {
    var tags = [];

    $(".bootstrap-tagsinput input").keyup(function(e){
        if(e.keyCode == 13){
            $('span.tag').each(function() {
                var text = $(this).text();
                if($.inArray(text, tags) < 0){
                    tags.push(text);
                }
            });

            $('#getTag').attr('value', tags.toString());
        }

        $(".bootstrap-tagsinput .tag span[data-role='remove']").click(function(){
            var index = tags.indexOf($(this).parent().text());
            tags.splice(index, 1);

            $('#getTag').attr('value', tags.toString());
        });
    });

    $('#getTag').attr('value', tags.toString());
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>BaseComponentEntity</title>
<meta name="date" content="2015-01-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

bropals.lib.simplegame.entity.component

Class BaseComponentEntity

java.lang.Object

bropals.lib.simplegame.entity.BaseEntity

bropals.lib.simplegame.entity.component.BaseComponentEntity

public abstract class BaseComponentEntity
extends BaseEntity

An entity that uses components to define its behavior. Rendering is
 done by extending and overriding render() like BaseEntity.

Constructor Summary

Constructors

Constructor and Description

BaseComponentEntity(GameWorld par)

Creates a new component entity with the given parent.

Method Summary

Methods

Modifier and Type
Method and Description

void
addComponent(EntityComponent component)

Adds a component to this entity, extending its behavior.

<T extends EntityComponent>
T
getComponent(java.lang.Class<T> type)

Gets the component of the specified type in this entity.

void
removeComponent(EntityComponent component)

Removes a component from this entity, shrinking its behavior.

void
update()

Updates this entity.

Methods inherited from class bropals.lib.simplegame.entity.BaseEntity

getParent, removeParent, render, setParent

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BaseComponentEntity

public BaseComponentEntity(GameWorld par)

Creates a new component entity with the given parent. The parent will
 add this entity to its list of entities.

Parameters:

par - this component entity's parent.

Method Detail

update

public void update()

Description copied from class: BaseEntity

Updates this entity. Meant to be overridden and implemented in a subclass.

Specified by:

update in class BaseEntity

addComponent

public void addComponent(EntityComponent component)

Adds a component to this entity, extending its behavior.

Parameters:

component - the component to add

removeComponent

public void removeComponent(EntityComponent component)

Removes a component from this entity, shrinking its behavior.

Parameters:

component - the component to remove

getComponent

public <T extends EntityComponent> T getComponent(java.lang.Class<T> type)

Gets the component of the specified type in this entity.

Type Parameters:

T - the type of the component that is being obtained

Parameters:

type - the class of the component that is being obtained

Returns:

the component of that type, or null if this
 entity does not have a component of that type.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "SimTKsimbody.h"
#include "SimTKcommon/Testing.h"

using namespace SimTK;
using namespace std;

const Real TOL = 1e-10;
const Real BOND_LENGTH = 0.5;

#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");}

template <class T>
void assertEqual(T val1, T val2, double tol=TOL) {
    ASSERT(abs(val1-val2) < tol);
}

template <int N>
void assertEqual(Vec<N> val1, Vec<N> val2, double tol) {
    double norm = max(val1.norm(), 1.0);
    for (int i = 0; i < N; ++i)
        ASSERT(abs(val1[i]-val2[i]) < tol*norm);
}

template<>
void assertEqual(Vector val1, Vector val2, double tol) {
    ASSERT(val1.size() == val2.size());
    for (int i = 0; i < val1.size(); ++i)
        assertEqual(val1[i], val2[i], tol);
}

template<>
void assertEqual(SpatialVec val1, SpatialVec val2, double tol) {
    assertEqual(val1[0], val2[0], tol);
    assertEqual(val1[1], val2[1], tol);
}

template<>
void assertEqual(Transform val1, Transform val2, double tol) {
    assertEqual(val1.p(), val2.p(), tol);
    ASSERT(val1.R().isSameRotationToWithinAngle(val2.R(), tol));
}

void compareReactionToConstraint(SpatialVec reactionForce, const Constraint& constraint, const State& state) {
    Vector_<SpatialVec> constraintForce(constraint.getNumConstrainedBodies());
    Vector mobilityForce(constraint.getNumConstrainedU(state));
    constraint.calcConstraintForcesFromMultipliers(state, constraint.getMultipliersAsVector(state), constraintForce, mobilityForce);

    // Transform the reaction force from the joint location to the body location.

    const MobilizedBody& body = constraint.getMobilizedBodyFromConstrainedBody(ConstrainedBodyIndex(1));
    Vec3 localForce = ~body.getBodyTransform(state).R()*reactionForce[1];
    reactionForce[0] += body.getBodyTransform(state).R()*(body.getOutboardFrame(state).p()%localForce);
    assertEqual(reactionForce, -1*constraint.getAncestorMobilizedBody().getBodyRotation(state)*constraintForce[1]);
}

/**
 * Compare the forces generated by equivalent mobilizers and constraints.
 */

void testByComparingToConstraints() {
    MultibodySystem system;
    SimbodyMatterSubsystem matter(system);
    GeneralForceSubsystem forces(system);
    Force::UniformGravity(forces, matter, Vec3(0, -9.8, 0));

    // Create two free joints (which should produce no reaction forces).

    Body::Rigid body = Body::Rigid(MassProperties(1.3, Vec3(0), Inertia(1.3)));
    MobilizedBody::Free f1(matter.updGround(), Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    MobilizedBody::Free f2(f1, Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));

    // Two ball joints, and two free joints constrained to act like ball joints.

    MobilizedBody::Free fb1(matter.updGround(), Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    MobilizedBody::Free fb2(fb1, Transform(Vec3(0, 0, BOND_LENGTH)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    Constraint::Ball fb1constraint(matter.updGround(), Vec3(0, 0, 0), fb1, Vec3(BOND_LENGTH, 0, 0));
    Constraint::Ball fb2constraint(fb1, Vec3(0, 0, BOND_LENGTH), fb2, Vec3(BOND_LENGTH, 0, 0));
    MobilizedBody::Ball b1(matter.updGround(), Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    MobilizedBody::Ball b2(b1, Transform(Vec3(0, 0, BOND_LENGTH)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    Force::ConstantTorque(forces, fb2, Vec3(0.1, 0.1, 1.0));
    Force::ConstantTorque(forces, b2, Vec3(0.1, 0.1, 1.0));

    // Two translation joints, and two free joints constrained to act like translation joints.

    MobilizedBody::Free ft1(matter.updGround(), Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    MobilizedBody::Free ft2(ft1, Transform(Vec3(0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
    Constraint::ConstantOrientation ft1constraint(matter.updGround(), Rotation(0, Vec3(1)), ft1, Rotation(0, Vec3(1)));
    Constraint::ConstantOrientation ft2constraint(ft1, Rotation(0, Vec3(1)), ft2, Rotation(0, Vec3(1)));
    MobilizedBody::Translation t1(matter.updGround(), Transform(Vec3(0)), body, Transform(Vec3(BOND_LENGTH, 0, 0)));
    MobilizedBody::Translation t2(t1, Transform(Vec3(0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
    Force::ConstantTorque(forces, ft2, Vec3(0.1, 0.1, 1.0));
    Force::ConstantTorque(forces, t2, Vec3(0.1, 0.1, 1.0));

    // Create the state.

    system.realizeTopology();
    State state = system.getDefaultState();
    Random::Gaussian random;
    int nq = state.getNQ()/2;
    for (int i = 0; i < state.getNY(); ++i)
        state.updY()[i] = random.getValue();
    system.realize(state, Stage::Velocity);
    Transform b1transform = b1.getMobilizerTransform(state);
    Transform b2transform = b2.getMobilizerTransform(state);
    SpatialVec b1velocity = b1.getMobilizerVelocity(state);
    SpatialVec b2velocity = b2.getMobilizerVelocity(state);
    Transform t1transform = t1.getMobilizerTransform(state);
    Transform t2transform = t2.getMobilizerTransform(state);
    SpatialVec t1velocity = t1.MobilizedBody::getMobilizerVelocity(state);
    SpatialVec t2velocity = t2.MobilizedBody::getMobilizerVelocity(state);
    fb1.setQToFitTransform(state, b1transform);
    fb2.setQToFitTransform(state, b2transform);
    fb1.setUToFitVelocity(state, b1velocity);
    fb2.setUToFitVelocity(state, b2velocity);
    ft1.setQToFitTransform(state, t1transform);
    ft2.setQToFitTransform(state, t2transform);
    ft1.setUToFitVelocity(state, t1velocity);
    ft2.setUToFitVelocity(state, t2velocity);

    system.project(state, TOL);
    system.realize(state, Stage::Acceleration);

    // Make sure the free and constrained bodies really are identical.

    assertEqual(b1.getBodyTransform(state), fb1.getBodyTransform(state));
    assertEqual(b2.getBodyTransform(state), fb2.getBodyTransform(state));
    assertEqual(b1.getBodyVelocity(state), fb1.getBodyVelocity(state));
    assertEqual(b2.getBodyVelocity(state), fb2.getBodyVelocity(state));
    assertEqual(t1.getBodyTransform(state), ft1.getBodyTransform(state));
    assertEqual(t2.getBodyTransform(state), ft2.getBodyTransform(state));
    assertEqual(t1.getBodyVelocity(state), ft1.getBodyVelocity(state));
    assertEqual(t2.getBodyVelocity(state), ft2.getBodyVelocity(state));

    // Calculate the mobility reaction forces.

    Vector_<SpatialVec> forcesAtMInG(matter.getNumBodies());
    matter.calcMobilizerReactionForces(state, forcesAtMInG);

    // Check that the bulk calculation matches the body-by-body calculation.
    for (MobilizedBodyIndex bx(0); bx < matter.getNumBodies(); ++bx) {
        assertEqual(forcesAtMInG[bx],
            matter.getMobilizedBody(bx)
               .findMobilizerReactionOnBodyAtMInGround(state));
    }

    // Make sure all free bodies have no reaction force on them.

    assertEqual((forcesAtMInG[f1.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));
    assertEqual((forcesAtMInG[f2.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));
    assertEqual((forcesAtMInG[fb1.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));
    assertEqual((forcesAtMInG[fb2.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));
    assertEqual((forcesAtMInG[ft1.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));
    assertEqual((forcesAtMInG[ft2.getMobilizedBodyIndex()]), SpatialVec(Vec3(0), Vec3(0)));

    // The reaction forces should match the corresponding constraint forces.

    compareReactionToConstraint(forcesAtMInG[b1.getMobilizedBodyIndex()], fb1constraint, state);
    compareReactionToConstraint(forcesAtMInG[b2.getMobilizedBodyIndex()], fb2constraint, state);
    compareReactionToConstraint(forcesAtMInG[t1.getMobilizedBodyIndex()], ft1constraint, state);
    compareReactionToConstraint(forcesAtMInG[t2.getMobilizedBodyIndex()], ft2constraint, state);
}

/*
 * (sherm 110919) None of the existing tests caught the problem reported
 * in bug #1535 -- incorrect reaction torques sometimes.
 * This is a pair of identical two-body pendulums, one done with pin joints
 * and one done with equivalent constraints.
 */
void testByComparingToConstraints2() {
    MultibodySystem system;
    SimbodyMatterSubsystem matter(system);
    GeneralForceSubsystem forces(system);
    Force::UniformGravity gravity(forces, matter, Vec3(10, -9.8, 3));

    Body::Rigid pendulumBody(MassProperties(1.0, Vec3(0), Inertia(1)));
    pendulumBody.addDecoration(Transform(), DecorativeSphere(0.1).setColor(Red));

    // First double pendulum, using Pin joints.
    Rotation x45(Pi/4, XAxis);
    MobilizedBody::Pin pendulum1(matter.updGround(),
                                Transform(x45,Vec3(0,-1,0)),
                                pendulumBody,
                                Transform(Vec3(0, 1, 0)));
    MobilizedBody::Pin pendulum1b(pendulum1,
                                Transform(x45,Vec3(0,-1,0)),
                                pendulumBody,
                                Transform(Vec3(0, 1, 0)));

    // Second double pendulum, using Free joints plus 5 constraints.
    MobilizedBody::Free pendulum2(matter.updGround(),
                                  Transform(x45,Vec3(2,-1,0)),
                                  pendulumBody,
                                  Transform(Vec3(0,1,0)));
    Constraint::Ball ballcons2(matter.updGround(), Vec3(2,-1,0),
                               pendulum2, Vec3(0,1,0));
    const Transform& X_GF2 = pendulum2.getDefaultInboardFrame();
    const Transform& X_P2M = pendulum2.getDefaultOutboardFrame();
    Constraint::ConstantAngle angx2(matter.Ground(), X_GF2.x(),
                              pendulum2, X_P2M.z());
    Constraint::ConstantAngle angy2(matter.Ground(), X_GF2.y(),
                              pendulum2, X_P2M.z());

    MobilizedBody::Free pendulum2b(pendulum2,
                                   Transform(x45,Vec3(0,-1,0)),
                                   pendulumBody,
                                   Transform(Vec3(0,1,0)));
    Constraint::Ball ballcons2b(pendulum2, Vec3(0,-1,0),
                                pendulum2b, Vec3(0,1,0));
    const Transform& X_GF2b = pendulum2b.getDefaultInboardFrame();
    const Transform& X_P2Mb = pendulum2b.getDefaultOutboardFrame();
    Constraint::ConstantAngle angx2b(pendulum2, X_GF2b.x(),
                              pendulum2b, X_P2Mb.z());
    Constraint::ConstantAngle angy2b(pendulum2, X_GF2b.y(),
                              pendulum2b, X_P2Mb.z());

    // Uncomment if you want to see this.
    //Visualizer viz(system);

    // Initialize the system and state.

    system.realizeTopology();
    State state = system.getDefaultState();
    pendulum1.setOneQ(state, 0, Pi/4);
    pendulum1.setOneU(state, 0, 1.0); // initial velocity 1 rad/sec

    pendulum1b.setOneU(state, 0, 1.0); // initial velocity 1 rad/sec
    pendulum1b.setOneQ(state, 0, Pi/4);

    pendulum2.setQToFitRotation(state, Rotation(Pi/4, ZAxis));
    pendulum2.setUToFitAngularVelocity(state, Vec3(0,0,1));
    pendulum2b.setQToFitRotation(state, Rotation(Pi/4, ZAxis));
    pendulum2b.setUToFitAngularVelocity(state, Vec3(0,0,1));

    system.realize(state);
    //viz.report(state);

    const MobodIndex p2x = pendulum2.getMobilizedBodyIndex();
    const MobodIndex p2bx = pendulum2b.getMobilizedBodyIndex();

    Vector_<SpatialVec> forcesAtMInG, forcesAtBInG, forcesAtFInG;
    matter.calcMobilizerReactionForces(state, forcesAtMInG);

    // Check that the bulk results match the individual ones, and fill
    // up the Vector of reaction on the parent bodies.
    forcesAtFInG.resize(forcesAtMInG.size());
    for (MobilizedBodyIndex mbx(0); mbx < matter.getNumBodies(); ++mbx) {
        SimTK_TEST_EQ(forcesAtMInG[mbx], matter.getMobilizedBody(mbx)
            .findMobilizerReactionOnBodyAtMInGround(state));

        forcesAtFInG[mbx] = matter.getMobilizedBody(mbx)
            .findMobilizerReactionOnParentAtFInGround(state);
    }

    // Now we'll convert forces on B at M to forces on P at F manually, and
    // compare with the ones we got by asking the mobilized body.
    Vector_<SpatialVec> forcesAtFInG_byhand(forcesAtMInG.size());
    forcesAtFInG_byhand[0] = -forcesAtMInG[0]; // Ground is "welded" at origin
    for (MobilizedBodyIndex i(1); i < matter.getNumBodies(); ++i) {
        const MobilizedBody& body   = matter.getMobilizedBody(i);
        const MobilizedBody& parent = body.getParentMobilizedBody();
        // Want to shift reaction by p_MF, the vector from M to F across the
        // mobilizer, and negate. Can get p_FM; must reexpress in G.
        const Vec3& p_FM = body.getMobilizerTransform(state).p();
        const Rotation& R_PF = body.getInboardFrame(state).R(); // In parent.
        const Rotation& R_GP = parent.getBodyTransform(state).R();
        Rotation R_GF   =   R_GP*R_PF;  // F frame orientation in Ground.
        Vec3     p_MF_G = -(R_GF*p_FM); // Re-express and negate shift vector.
        forcesAtFInG_byhand[i] = -shiftForceBy(forcesAtMInG[i], p_MF_G);
    }

    SimTK_TEST_EQ(forcesAtFInG, forcesAtFInG_byhand);

    // Shift the reaction forces to body origins for easy comparison with
    // the reported constraint forces.
    forcesAtBInG.resize(forcesAtMInG.size());
    const MobodIndex p1x = pendulum1.getMobilizedBodyIndex();
    const MobodIndex p1bx = pendulum1b.getMobilizedBodyIndex();
    const Rotation& R_G1 = pendulum1.getBodyTransform(state).R();
    const Rotation& R_G1b = pendulum1b.getBodyTransform(state).R();
    forcesAtBInG[p1x] = shiftForceFromTo(forcesAtMInG[p1x],
                                         R_G1*Vec3(0,1,0), Vec3(0));
    forcesAtBInG[p1bx] = shiftForceFromTo(forcesAtMInG[p1bx],
                                         R_G1b*Vec3(0,1,0), Vec3(0));

    // Compare those manually-shifted quantities to the ones we can get
    // direction from the MobilizedBody.
    SpatialVec forcesAtBInG_p1 =
        pendulum1.findMobilizerReactionOnBodyAtOriginInGround(state);
    SpatialVec forcesAtBInG_p1b =
        pendulum1b.findMobilizerReactionOnBodyAtOriginInGround(state);

    SimTK_TEST_EQ(forcesAtBInG[p1x], forcesAtBInG_p1);
    SimTK_TEST_EQ(forcesAtBInG[p1bx], forcesAtBInG_p1b);

    // The constraints apply forces to parent and body; we want to compare
    // forces on the body, which will be the second entry here. We're assuming
    // the ball and constant angle constraints are ordered the same way; if
    // that ever changes the constraints can be queried to find the mobilized
    // body index corresponding to the constrained body index.
    Vector_<SpatialVec> cons2Forces =
        -(ballcons2.getConstrainedBodyForcesAsVector(state)
          + angx2.getConstrainedBodyForcesAsVector(state)
          + angy2.getConstrainedBodyForcesAsVector(state));
    Vector_<SpatialVec> cons2bForces =
        -(ballcons2b.getConstrainedBodyForcesAsVector(state)
          + angx2b.getConstrainedBodyForcesAsVector(state)
          + angy2b.getConstrainedBodyForcesAsVector(state));

    // Couldn't quite make default tolerance on some platforms. This uses
    // 10X default.
    SimTK_TEST_EQ_SIZE(cons2Forces[1], forcesAtBInG[p1x], 10);
    SimTK_TEST_EQ_SIZE(cons2bForces[1], forcesAtBInG[p1bx], 10);
}

/**
 * Construct a system of several bodies, and compare the reaction forces to those calculated by SD/FAST.
 */

void testByComparingToSDFAST() {
    MultibodySystem system;
    SimbodyMatterSubsystem matter(system);
    GeneralForceSubsystem forces(system);
    Force::UniformGravity(forces, matter, Vec3(0, -9.8, 0));

    // Construct the set of bodies.

    Inertia inertia = Inertia(Mat33(0.1, 0.01, 0.01,
                                    0.01, 0.1, 0.01,
                                    0.01, 0.01, 0.1));
    MobilizedBody::Slider body1(matter.updGround(), MassProperties(10.0, Vec3(0), inertia));
    MobilizedBody::Pin body2(body1, Vec3(0.1, 0.1, 0), MassProperties(20.0, Vec3(0), inertia), Vec3(0, -0.2, 0));
    MobilizedBody::Gimbal body3(body2, Vec3(0, 0.2, 0), MassProperties(20.0, Vec3(0), inertia), Vec3(0, -0.2, 0));
    MobilizedBody::Pin body4(body3, Vec3(0, 0.2, 0), MassProperties(30.0, Vec3(0), inertia), Vec3(0, -0.2, 0));
    State state = system.realizeTopology();
    system.realize(state, Stage::Acceleration);

    // Calculate reaction forces, and compare to the values that were generated by SD/FAST.

    Vector_<SpatialVec> reaction(matter.getNumBodies());
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~body1.getBodyTransform(state).R()*reaction[body1.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 68.6), Vec3(0, 784.0, 0)));
    assertEqual(~body2.getBodyTransform(state).R()*reaction[body2.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(0, 686.0, 0)));
    assertEqual(~body3.getBodyTransform(state).R()*reaction[body3.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(0, 490.0, 0)));
    assertEqual(~body4.getBodyTransform(state).R()*reaction[body4.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(0, 294.0, 0)));

    // Now set it to a different configuration and try again.

    body1.setLength(state, 1.0);
    body2.setAngle(state, 0.5);
    Rotation r;
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 0.2, ZAxis, -0.1, XAxis, 2.0, YAxis);
    body3.setQToFitRotation(state, r);
    body4.setAngle(state, -0.5);
    system.realize(state, Stage::Acceleration);
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~body1.getBodyTransform(state).R()*reaction[body1.getMobilizedBodyIndex()], SpatialVec(Vec3(1.647327, 0.783211, 34.088183), Vec3(0, 359.274099, 3.342380)), 1e-5);
    assertEqual(~body2.getBodyTransform(state).R()*reaction[body2.getMobilizedBodyIndex()], SpatialVec(Vec3(1.688077, 0.351125, 0), Vec3(55.399123, 267.455570, 3.342380)), 1e-5);
    assertEqual(~body3.getBodyTransform(state).R()*reaction[body3.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(-17.757553, 174.663042, -11.383057)), 1e-5);
    assertEqual(~body4.getBodyTransform(state).R()*reaction[body4.getMobilizedBodyIndex()], SpatialVec(Vec3(0.910890, 0.082353, 0), Vec3(-13.977214, 74.444715, 4.943682)), 1e-5);

    // Try giving it momentum.

    state.updQ() = 0.0;
    body2.setOneU(state, 0, 1);
    body3.setUToFitAngularVelocity(state, Vec3(3, 4, 2));
    body4.setOneU(state, 0, 5);
    system.realize(state, Stage::Acceleration);
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~body1.getBodyTransform(state).R()*reaction[body1.getMobilizedBodyIndex()], SpatialVec(Vec3(-13.549253, 2.723897, -6.355912), Vec3(0, 34.0, -27.088584)), 1e-5);
    assertEqual(~body2.getBodyTransform(state).R()*reaction[body2.getMobilizedBodyIndex()], SpatialVec(Vec3(-10.840395, 0.015039, 0), Vec3(-0.440882, -64.0, -27.088584)), 1e-5);
    assertEqual(~body3.getBodyTransform(state).R()*reaction[body3.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(0.692814, -256.000000, -27.088584)), 1e-5);
    assertEqual(~body4.getBodyTransform(state).R()*reaction[body4.getMobilizedBodyIndex()], SpatialVec(Vec3(3.276930, -0.281928, 0), Vec3(3.796164, -372.0, 21.472977)), 1e-5);
}

/**
 * Construct a system of several bodies, and compare the reaction forces to those calculated by SD/FAST.
 */

void testByComparingToSDFAST2() {
    MultibodySystem system;
    SimbodyMatterSubsystem matter(system);
    GeneralForceSubsystem forces(system);
    Force::UniformGravity(forces, matter, Vec3(0, -9.8065, 0));

    // Construct the set of bodies.

    Body::Rigid femur(MassProperties(8.806, Vec3(0), Inertia(Vec3(0.1268, 0.0332, 0.1337))));
    Body::Rigid tibia(MassProperties(3.510, Vec3(0), Inertia(Vec3(0.0477, 0.0048, 0.0484))));
    MobilizedBody::Pin p1(matter.Ground(), Transform(Vec3(0.0000, -0.0700, 0.0935)), femur, Transform(Vec3(0.0020, 0.1715, 0)));
    MobilizedBody::Slider p2(p1, Transform(Vec3(0.0033, -0.2294, 0)), tibia, Transform(Vec3(0.0, 0.1862, 0.0)));
    State state = system.realizeTopology();
    system.realize(state, Stage::Acceleration);

    // Calculate reaction forces, and compare to the values that were generated by SD/FAST.

    Vector_<SpatialVec> reaction(matter.getNumBodies());
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~p1.getBodyTransform(state).R()*reaction[p1.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(0.438079, 120.773069, 0)), 1e-5);
    assertEqual(~p2.getBodyTransform(state).R()*reaction[p2.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0.014040), Vec3(0, 34.422139, 0)), 1e-5);

    // Now set it to a different configuration and try again.

    p1.setOneQ(state, 0, -90*NTraits<Real>::getPi()/180);
    p2.setOneQ(state, 0, 0.1);
    system.realize(state, Stage::Acceleration);
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~p1.getBodyTransform(state).R()*reaction[p1.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(-39.481457, 10.489344, 0)), 1e-5);
    assertEqual(~p2.getBodyTransform(state).R()*reaction[p2.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 1.502242), Vec3(0, 11.035987, 0)), 1e-5);
}

/**
 * Construct a system of several bodies and a constraint, and compare the reaction forces to those calculated by SD/FAST.
 */

void testByComparingToSDFASTWithConstraint() {
    MultibodySystem system;
    SimbodyMatterSubsystem matter(system);
    GeneralForceSubsystem forces(system);
    Force::UniformGravity(forces, matter, Vec3(0, -9.8, 0));

    // Construct the set of bodies.

    Inertia inertia = Inertia(Mat33(0.1, 0.01, 0.01,
                                    0.01, 0.1, 0.01,
                                    0.01, 0.01, 0.1));
    MobilizedBody::Gimbal body1(matter.updGround(),
        MassProperties(10.0, Vec3(0), inertia));
    MobilizedBody::Gimbal body2(body1, Vec3(0, -0.1, 0.2),
        MassProperties(20.0, Vec3(0), inertia), Vec3(0, 0.2, 0));
    MobilizedBody::Gimbal body3(body1, Vec3(0, -0.1, -0.2),
        MassProperties(20.0, Vec3(0), inertia), Vec3(0, 0.2, 0));
    MobilizedBody::Gimbal body4(body2, Vec3(0, -0.2, 0),
        MassProperties(30.0, Vec3(0), inertia), Vec3(0, 0.2, 0));
    MobilizedBody::Gimbal body5(body3, Vec3(0, -0.2, 0),
        MassProperties(30.0, Vec3(0), inertia), Vec3(0, 0.2, 0));
    Constraint::Rod constraint(body4, body5, 0.15);
    State state = system.realizeTopology();
    system.realize(state, Stage::Velocity);
    // After I changed the Rod constraint to use distance rather than distance^2
    // it assembled slightly differently and then wouldn't pass this test to
    // this precision. So I replaced the project() call with the result from
    // the older squared equations. The result I was getting from project() with
    // the distance equations was:
    //          0 0 0 0.188972205696439 0 0 -0.188972205696439 0 0
    //          0.062986198663389 0 0 -0.062986198663389 0 0
    // which is nearly identical to those below, but different enough to cause
    // a failure here. With the same set of q's, the reactions should be the
    // same regardless of the equations being used for Rod. (sherm 140506)
    //system.project(state, 1e-10);
    Real q[15]={0,0,0,0.189000969332574,0,0,-0.189000969332574,0,0,
                0.0628990902570866,0,0,-0.0628990902570866,0,0};
    state.updQ() = Vector(15, q);
    system.realize(state, Stage::Acceleration);

    // Calculate reaction forces, and compare to the values that were generated by SD/FAST.

    Vector_<SpatialVec> reaction(matter.getNumBodies());
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~body1.getBodyTransform(state).R()*reaction[body1.getMobilizedBodyIndex()],
                SpatialVec(Vec3(0, 0, 0), Vec3(-0.000626, 1077.988912, 0.000030)), 1e-5);
    assertEqual(~body2.getBodyTransform(state).R()*reaction[body2.getMobilizedBodyIndex()],
                SpatialVec(Vec3(0, 0, 0), Vec3(-0.005038, 495.288692, -18.767467)), 1e-5);
    assertEqual(~body3.getBodyTransform(state).R()*reaction[body3.getMobilizedBodyIndex()],
                SpatialVec(Vec3(0, 0, 0), Vec3(0.004236, 495.287857, 18.767535)), 1e-5);
    assertEqual(~body4.getBodyTransform(state).R()*reaction[body4.getMobilizedBodyIndex()],
                SpatialVec(Vec3(0, 0, 0), Vec3(0.006251, 303.365940, -0.202330)), 1e-5);
    assertEqual(~body5.getBodyTransform(state).R()*reaction[body5.getMobilizedBodyIndex()],
                SpatialVec(Vec3(0, 0, 0), Vec3(-0.005933, 303.365472, 0.202301)), 1e-5);

    // Now set it to a different configuration and try again.

    Rotation r;
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 1.0, ZAxis, 1.0, XAxis, 1.0, YAxis);
    body1.setQToFitRotation(state, r);
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 0.433843, ZAxis, 0.647441, XAxis, 0.500057, YAxis);
    body2.setQToFitRotation(state, r);
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 0.066156, ZAxis, -0.117266, XAxis, -0.047605, YAxis);
    body3.setQToFitRotation(state, r);
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 0.000997, ZAxis, 0.055206, XAxis, 0.0, YAxis);
    body4.setQToFitRotation(state, r);
    r.setRotationFromThreeAnglesThreeAxes(BodyRotationSequence, 1.008746, ZAxis, 0.951972, XAxis, 1.0, YAxis);
    body5.setQToFitRotation(state, r);
    system.realize(state, Stage::Acceleration);
    matter.calcMobilizerReactionForces(state, reaction);
    assertEqual(~body1.getBodyTransform(state).R()*reaction[body1.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(99.121319, 139.500095, 95.065409)), 1e-5);
    assertEqual(~body2.getBodyTransform(state).R()*reaction[body2.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(15.359115, 55.876994, 22.508078)), 1e-5);
    assertEqual(~body3.getBodyTransform(state).R()*reaction[body3.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(15.696393, 65.002065, 13.133021)), 1e-5);
    assertEqual(~body4.getBodyTransform(state).R()*reaction[body4.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(-6.262023, 32.714510, -9.770708)), 1e-5);
    assertEqual(~body5.getBodyTransform(state).R()*reaction[body5.getMobilizedBodyIndex()], SpatialVec(Vec3(0, 0, 0), Vec3(10.471620, 0.963822, -4.640161)), 1e-5);
}

// Create a free body in space and apply some forces to it.
// As long as we don't apply mobility forces, the reaction force
// in the mobilizer should be zero.
// It is important to do this with a full inertia, offset com,
// non-unit mass, twisted frames, non-zero velocities, etc.

const Real d = 1.5; // length (m)
const Real mass = 2; // kg
const Transform X_GF(Rotation(Pi/3, Vec3(.1,-.3,.3)), Vec3(-4,-5,-1));
const Transform X_BM(Rotation(-Pi/10, Vec3(7,5,3)), Vec3(0,d,0));

void testFreeMobilizer() {
    MultibodySystem forward;
    SimbodyMatterSubsystem fwdMatter(forward);
    GeneralForceSubsystem fwdForces(forward);
    Force::UniformGravity(fwdForces, fwdMatter, Vec3(0, -1, 0));

    const Vec3 com(1,2,3);
    const UnitInertia centralGyration(1, 1.5, 2, .1, .2, .3);
    Body::Rigid body(MassProperties(mass, com, mass*centralGyration.shiftFromMassCenter(com, 1)));

    MobilizedBody::Free fwdA (fwdMatter.Ground(),  X_GF, body, X_BM);

    Force::ConstantForce(fwdForces, fwdA, Vec3(-1,.27,4), Vec3(5,.6,-1));
    Force::ConstantTorque(fwdForces, fwdA, Vec3(-5.5,1.6,-1.1));

    State fwdState  = forward.realizeTopology();
    fwdA.setQToFitTransform(fwdState, Transform(Rotation(Pi/9,Vec3(-1.8,4,2.2)), Vec3(.1,.2,.7)));

    forward.realize (fwdState,  Stage::Position);

    fwdA.setUToFitVelocity(fwdState, SpatialVec(Vec3(.99,2,4), Vec3(-1.2,4,.000333)));
    forward.realize (fwdState,  Stage::Velocity);
    forward.realize (fwdState,  Stage::Acceleration);

    Vector_<SpatialVec> fwdReac;
    fwdMatter.calcMobilizerReactionForces(fwdState, fwdReac);

    // We expect no reaction from a Free joint.
    assertEqual(fwdReac[0], SpatialVec(Vec3(0)));
    assertEqual(fwdReac[1], SpatialVec(Vec3(0)));
}

int main() {
    SimTK_START_TEST("TestMobilizerReactionForces");
        SimTK_SUBTEST(testByComparingToConstraints);
        SimTK_SUBTEST(testByComparingToConstraints2);
        SimTK_SUBTEST(testByComparingToSDFAST);
        SimTK_SUBTEST(testByComparingToSDFAST2);
        SimTK_SUBTEST(testByComparingToSDFASTWithConstraint);
        SimTK_SUBTEST(testFreeMobilizer);
    SimTK_END_TEST();
}


text:
/*
 * ImageCustomizer.java
 *
 * Created on January 25, 2009, 2:23 PM
 */

package org.netbeans.modules.web.stripes.palette.items;

import javax.swing.text.JTextComponent;

import org.netbeans.modules.web.stripes.palette.CodeSnippet;
import org.netbeans.modules.web.stripes.palette.CodeSnippetCustomizer;
import org.netbeans.modules.web.stripes.palette.StripesPaletteUtilities;
import org.netbeans.modules.web.stripes.util.StringUtils;
import org.netbeans.modules.web.stripes.util.browse.BrowseDialogs;

/**
 *
 * @author  Josef Sustacek
 */
public class ImageCustomizer extends CodeSnippetCustomizer {

    private JTextComponent target;

    /** Creates new form ImageCustomizer */
    public ImageCustomizer(CodeSnippet codeSnippet, JTextComponent target) {
        super(codeSnippet);

        this.target = target;

        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        srcText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        altText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        nameText = new javax.swing.JTextField();
        browseBtn = new javax.swing.JButton();

        jLabel1.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.jLabel1.text")); // NOI18N

        srcText.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.srcText.text")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.jLabel2.text")); // NOI18N

        altText.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.altText.text")); // NOI18N

        jLabel3.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.jLabel3.text")); // NOI18N

        nameText.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.nameText.text")); // NOI18N

        browseBtn.setText(org.openide.util.NbBundle.getMessage(ImageCustomizer.class, "ImageCustomizer.browseBtn.text")); // NOI18N
        browseBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(altText)
                    .addComponent(nameText)
                    .addComponent(srcText, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(browseBtn)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(nameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(browseBtn)
                    .addComponent(srcText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(altText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseBtnActionPerformed
    String imagePath = BrowseDialogs.imageSourcesDialog(
            StripesPaletteUtilities.getProject(target), this,
            new String[] {"jpg", "jpeg", "gif", "png", "bmp"});

    if(!StringUtils.nullOrEmpty(imagePath)){
        srcText.setText(imagePath);
    }
}//GEN-LAST:event_browseBtnActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField altText;
    private javax.swing.JButton browseBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField nameText;
    private javax.swing.JTextField srcText;
    // End of variables declaration//GEN-END:variables

    @Override
    protected void evaluateInput() {
        codeSnippet.setProperty(Image.NAME, nameText.getText());
        codeSnippet.setProperty(Image.SRC, srcText.getText());
        codeSnippet.setProperty(Image.ALT, altText.getText());
    }
}


text:
package com.cabinetms.programtactic.entity;

import com.cabinetms.programtactic.entity.CabinetmsProgramTactic;
import com.google.common.collect.Lists;

import java.util.List;

import org.hibernate.validator.constraints.Length;
import com.cabinetms.program.entity.Program;

import com.thinkgem.jeesite.common.persistence.DataEntity;
import com.thinkgem.jeesite.common.utils.StringUtils;

/**
 * 节目策略一对多生成Entity
 * @author 于滨
 * @version 2016-10-19
 */
public class CabinetmsProgramTacticDetail extends DataEntity<CabinetmsProgramTacticDetail> {

	private static final long serialVersionUID = 1L;
	private CabinetmsProgramTactic programTactic;		// 节目策略ID 父类
	private String programTacticName;		// 节目策略名称
	private Program program;		// 节目ID
	private String programName;		// 节目名称
	private Integer starttime;		// 开始时间
	private Integer endtime;		// 结束时间

	private String starttimeparam;
	private String endtimeparam;

	private List<Program> programList = Lists.newArrayList();

	public CabinetmsProgramTacticDetail() {
		super();
	}

	public CabinetmsProgramTacticDetail(String id){
		super(id);
	}

	public CabinetmsProgramTacticDetail(CabinetmsProgramTactic programTactic){
		this.programTactic = programTactic;
	}

	public CabinetmsProgramTactic getProgramTactic() {
		return programTactic;
	}

	public void setProgramTactic(CabinetmsProgramTactic programTactic) {
		this.programTactic = programTactic;
	}

	@Length(min=0, max=64, message="节目策略名称长度必须介于 0 和 64 之间")
	public String getProgramTacticName() {
		return programTacticName;
	}

	public void setProgramTacticName(String programTacticName) {
		this.programTacticName = programTacticName;
	}

	public Program getProgram() {
		return program;
	}

	public void setProgram(Program program) {
		this.program = program;
	}

	@Length(min=0, max=64, message="节目名称长度必须介于 0 和 64 之间")
	public String getProgramName() {
		return programName;
	}

	public void setProgram(String programName) {
		this.programName = programName;
	}

	public Integer getStarttime() {
		return starttime;
	}

	public void setStarttime(Integer starttime) {
		this.starttime = starttime;
	}

	public Integer getEndtime() {
		return endtime;
	}

	public void setEndtime(Integer endtime) {
		this.endtime = endtime;
	}

	public List<Program> getProgramList() {
		return programList;
	}

	public void setProgramList(List<Program> programList) {
		this.programList = programList;
	}

	public String getStarttimeparam() {
		if(this.starttime!=null && this.starttime>0){
			String startTimeStr = String.valueOf(this.starttime);
			if(startTimeStr.length()<6){
				startTimeStr = "0"+startTimeStr;
			}
			this.starttimeparam = startTimeStr.substring(0, 2)+":"+startTimeStr.substring(2, 4)+":"+startTimeStr.substring(4, 6);
		}
		return starttimeparam;
	}

	public void setStarttimeparam(String starttimeparam) {
		this.starttimeparam = starttimeparam;
		if(StringUtils.isNotBlank(starttimeparam)){
			setStarttime(Integer.parseInt(starttimeparam.replace(":", "")));
		}
	}

	public String getEndtimeparam() {
		if(this.endtime!=null && this.endtime>0){
			String endTimeStr = String.valueOf(this.endtime);
			if(endTimeStr.length()<6){
				endTimeStr = "0"+endTimeStr;
			}
			this.endtimeparam = endTimeStr.substring(0, 2)+":"+endTimeStr.substring(2, 4)+":"+endTimeStr.substring(4, 6);
		}
		return endtimeparam;
	}

	public void setEndtimeparam(String endtimeparam) {
		this.endtimeparam = endtimeparam;
		if(StringUtils.isNotBlank(endtimeparam)){
			setEndtime(Integer.parseInt(endtimeparam.replace(":", "")));
		}
	}

}


text:
package org.osanchezh.keepnotes.soa.model.entity;

import java.io.Serializable;

public interface Entity extends Serializable
{

}


text:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule }              from './app.module';

function main() {
    platformBrowserDynamic().bootstrapModule(AppModule);
}

if (document.readyState === 'complete') {
    main();
} else {
    document.addEventListener('DOMContentLoaded', main);
}


text:
"""
esdc_api.response
~~~~~~~~~~~~~~~~~

This module provides the Response object returned by Danube Cloud API :class:`.Client` request methods.
"""

import json
from collections import namedtuple

from .exceptions import ESAPIRuntimeError, ServerError, ClientError, TaskError, TaskFailure, TaskRevoked

__all__ = (
    'Response',
    'Content'
)

#: Danube Cloud API Response content tuple returned by :attr:`.Response.content` property.
Content = namedtuple('Content', ('result', 'dc', 'task_status', 'task_id'))

class Response(object):
    """
    Danube Cloud API Response (wrapper around :class:`requests.Response <requests.Response>` class).

    :param response: The :class:`requests.Response <requests.Response>` object.
    """
    def __init__(self, response):
        """Initialize the response object."""
        self._response = response
        self._content = None
        self._raw_content = None
        self._status_code = None
        headers = response.headers
        #: Danube Cloud API version.
        self.version = headers.get('es_version', '???')
        self.task_id = headers.get('es_task_id', None)
        self.stream = headers.get('es_stream', None)  # Only set for stream responses
        self.dc = headers.get('es_dc', None)

    def __getstate__(self):
        # Fetch raw content before serializing
        if self._raw_content is None:
            self.consume_raw_content()

        return self.__dict__

    def __repr__(self):
        return '<Danube Cloud API :: %s [%s]>' % (self.__class__.__name__, self.status_code)

    def __bool__(self):
        return self.ok

    def __nonzero__(self):
        return self.__bool__()

    @staticmethod
    def is_status_code_ok(status_code):
        """Helper method for checking the HTTP status code.

        :param int status_code: HTTP status code.
        :return: `True` if status_code < 400.
        :rtype: bool
        """
        if 400 <= status_code < 600:
            return False
        else:
            return True

    @staticmethod
    def _get_exception(status_code, task_status, task_response):
        """Return Danube Cloud API exception class according to status_code (and other parameters)."""
        if status_code >= 500:
            return ServerError

        if task_response:
            if task_status == 'FAILURE':
                return TaskFailure
            elif task_status == 'REVOKED':
                return TaskRevoked
            else:
                return TaskError

        return ClientError

    def parse_raw_content(self, raw_content):
        """Parse raw content and return content tuple or API error exception (without raising it).

        :param raw_content: Last item yielded by :func:`fetch_raw_content`.
        :return: :class:`.ESAPIError` or :class:`.Content`.
        """
        assert isinstance(raw_content, bytes), 'Raw content must be an instance of bytes'

        task_id = self.task_id
        task_status = detail = None
        raw_content = raw_content.decode('utf-8')

        # noinspection PyBroadException
        try:
            content = json.loads(raw_content)
        except:
            content = raw_content
        else:
            if isinstance(content, dict):
                task_status = content.get('status', None)
                self.task_id = content.get('task_id', task_id)
                detail = content.get('detail', None)

                if 'result' in content:
                    content = content['result']

        if self.is_status_code_ok(self.status_code):
            return Content(content, self.dc, task_status, self.task_id)

        if detail is None:
            detail = content

        exc = self._get_exception(self.status_code, task_status, self._response.headers.get('es_task_response', None))

        return exc(self.status_code, detail, self.dc, task_status, self.task_id)

    def fetch_raw_content(self):
        """Fetch content from the server and yield `None` while waiting for some data.
        The last yielded item is always the raw content (`bytes`).

        :return: Generator which yields `None` until it yields the raw content (`bytes`).
        :rtype: generator
        """
        if self._raw_content is not None:
            raise ESAPIRuntimeError('The raw content for this response was already consumed')

        if self.stream:  # Streaming response
            content = None

            for chunk in self._response.iter_content(chunk_size=1):
                if chunk.isspace():
                    yield None
                else:
                    try:
                        data = chunk + self._response.content
                        data = data.strip().split(b'\n', 1)
                        content = data.pop()
                        self._status_code = int(data[0])
                    except Exception as e:
                        raise ESAPIRuntimeError('Could not read status code from streaming response: %s', e)
                    else:
                        break
        else:
            content = self._response.content

        self._raw_content = content

        yield content

    def consume_raw_content(self):
        """Iterate over the generator returned by :func:`fetch_raw_content` and return the last item - the raw content.

        :return: Raw content.
        :rtype: bytes
        """
        return list(self.fetch_raw_content())[-1]

    @property
    def raw_content(self):
        """Return raw content. Fetch and cache it by using :func:`consume_raw_content`; if not already consumed.

        :return: Raw content.
        :rtype: bytes
        """
        if self._raw_content is None:
            return self.consume_raw_content()
        else:
            return self._raw_content

    @property
    def status_code(self):
        """Return HTTP status code of this response.

        :return: HTTP status code.
        :rtype: int
        """
        return self._status_code or self._response.status_code

    @property
    def ready(self):
        """Indicate whether raw content was already consumed from server.

        :return: Raw content status.
        :rtype: bool
        """
        return self._raw_content is not None

    @property
    def content(self):
        """Parse raw content and return a content tuple.

        :return: Content namedtuple with :attr:`.Content.result` attribute.
        :rtype: :class:`.Content`
        :raise: :class:`.ESAPIError`
        """
        if self._content is None:
            self._content = self.parse_raw_content(self.raw_content)

        if isinstance(self._content, Exception):
            raise self._content
        else:
            return self._content

    @property
    def ok(self):
        """Return `True` if response status code is < 400. Also fetch the raw content if needed.

        :return: Response status according to the HTTP status code.
        :rtype: bool
        """
        if self._raw_content is None:
            self.consume_raw_content()

        return self.is_status_code_ok(self.status_code)

    @property
    def url(self):
        """Return the request URL."""
        return self._response.url

    @property
    def method(self):
        """Return the request method."""
        return self._response.method

    @property
    def headers(self):
        """Return the response headers."""
        return self._response.headers


text:
layout: page
title: "Oops!sss Nothing here..."
subheadline: "404"
teaser: "Maybe the webpage moved or we deleted it. Or did you maybe mistype the URL?"
permalink: "/404.html"
---
## No problem!

Try...
...to start over on the [home page]({{ site.url }}).
...our **search**.

### Search and Find

{% include google_search.html %}

<form onsubmit="google_search()" >
  <input type="text" id="google-search" placeholder="Search">
</form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wox.Skype
{
	public class SkypeUser
	{
		public string FullName { get; set; }

		public string StatusText { get; set; }

		public string UserName { get; set; }
	}
}