text:
package vtworkerdata

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
	logutil "vitess.io/vitess/go/vt/proto/logutil"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

// ExecuteVtworkerCommandRequest is the payload for ExecuteVtworkerCommand.
type ExecuteVtworkerCommandRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Args []string `protobuf:"bytes,1,rep,name=args,proto3" json:"args,omitempty"`
}

func (x *ExecuteVtworkerCommandRequest) Reset() {
	*x = ExecuteVtworkerCommandRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_vtworkerdata_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *ExecuteVtworkerCommandRequest) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*ExecuteVtworkerCommandRequest) ProtoMessage() {}

func (x *ExecuteVtworkerCommandRequest) ProtoReflect() protoreflect.Message {
	mi := &file_vtworkerdata_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use ExecuteVtworkerCommandRequest.ProtoReflect.Descriptor instead.
func (*ExecuteVtworkerCommandRequest) Descriptor() ([]byte, []int) {
	return file_vtworkerdata_proto_rawDescGZIP(), []int{0}
}

func (x *ExecuteVtworkerCommandRequest) GetArgs() []string {
	if x != nil {
		return x.Args
	}
	return nil
}

// ExecuteVtworkerCommandResponse is streamed back by ExecuteVtworkerCommand.
type ExecuteVtworkerCommandResponse struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Event *logutil.Event `protobuf:"bytes,1,opt,name=event,proto3" json:"event,omitempty"`
}

func (x *ExecuteVtworkerCommandResponse) Reset() {
	*x = ExecuteVtworkerCommandResponse{}
	if protoimpl.UnsafeEnabled {
		mi := &file_vtworkerdata_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *ExecuteVtworkerCommandResponse) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*ExecuteVtworkerCommandResponse) ProtoMessage() {}

func (x *ExecuteVtworkerCommandResponse) ProtoReflect() protoreflect.Message {
	mi := &file_vtworkerdata_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use ExecuteVtworkerCommandResponse.ProtoReflect.Descriptor instead.
func (*ExecuteVtworkerCommandResponse) Descriptor() ([]byte, []int) {
	return file_vtworkerdata_proto_rawDescGZIP(), []int{1}
}

func (x *ExecuteVtworkerCommandResponse) GetEvent() *logutil.Event {
	if x != nil {
		return x.Event
	}
	return nil
}

var File_vtworkerdata_proto protoreflect.FileDescriptor

var file_vtworkerdata_proto_rawDesc = []byte{
	0x0a, 0x12, 0x76, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70,
	0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x76, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x64, 0x61,
	0x74, 0x61, 0x1a, 0x0d, 0x6c, 0x6f, 0x67, 0x75, 0x74, 0x69, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74,
	0x6f, 0x22, 0x33, 0x0a, 0x1d, 0x45, 0x78, 0x65, 0x63, 0x75, 0x74, 0x65, 0x56, 0x74, 0x77, 0x6f,
	0x72, 0x6b, 0x65, 0x72, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65,
	0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x61, 0x72, 0x67, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09,
	0x52, 0x04, 0x61, 0x72, 0x67, 0x73, 0x22, 0x46, 0x0a, 0x1e, 0x45, 0x78, 0x65, 0x63, 0x75, 0x74,
	0x65, 0x56, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
	0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x24, 0x0a, 0x05, 0x65, 0x76, 0x65, 0x6e,
	0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x6c, 0x6f, 0x67, 0x75, 0x74, 0x69,
	0x6c, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x05, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x42, 0x2b,
	0x5a, 0x29, 0x76, 0x69, 0x74, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6f, 0x2f, 0x76, 0x69, 0x74, 0x65,
	0x73, 0x73, 0x2f, 0x67, 0x6f, 0x2f, 0x76, 0x74, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x76,
	0x74, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x64, 0x61, 0x74, 0x61, 0x62, 0x06, 0x70, 0x72, 0x6f,
	0x74, 0x6f, 0x33,
}

var (
	file_vtworkerdata_proto_rawDescOnce sync.Once
	file_vtworkerdata_proto_rawDescData = file_vtworkerdata_proto_rawDesc
)

func file_vtworkerdata_proto_rawDescGZIP() []byte {
	file_vtworkerdata_proto_rawDescOnce.Do(func() {
		file_vtworkerdata_proto_rawDescData = protoimpl.X.CompressGZIP(file_vtworkerdata_proto_rawDescData)
	})
	return file_vtworkerdata_proto_rawDescData
}

var file_vtworkerdata_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_vtworkerdata_proto_goTypes = []interface{}{
	(*ExecuteVtworkerCommandRequest)(nil),  // 0: vtworkerdata.ExecuteVtworkerCommandRequest
	(*ExecuteVtworkerCommandResponse)(nil), // 1: vtworkerdata.ExecuteVtworkerCommandResponse
	(*logutil.Event)(nil),                  // 2: logutil.Event
}
var file_vtworkerdata_proto_depIdxs = []int32{
	2, // 0: vtworkerdata.ExecuteVtworkerCommandResponse.event:type_name -> logutil.Event
	1, // [1:1] is the sub-list for method output_type
	1, // [1:1] is the sub-list for method input_type
	1, // [1:1] is the sub-list for extension type_name
	1, // [1:1] is the sub-list for extension extendee
	0, // [0:1] is the sub-list for field type_name
}

func init() { file_vtworkerdata_proto_init() }
func file_vtworkerdata_proto_init() {
	if File_vtworkerdata_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_vtworkerdata_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*ExecuteVtworkerCommandRequest); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_vtworkerdata_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*ExecuteVtworkerCommandResponse); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_vtworkerdata_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   0,
		},
		GoTypes:           file_vtworkerdata_proto_goTypes,
		DependencyIndexes: file_vtworkerdata_proto_depIdxs,
		MessageInfos:      file_vtworkerdata_proto_msgTypes,
	}.Build()
	File_vtworkerdata_proto = out.File
	file_vtworkerdata_proto_rawDesc = nil
	file_vtworkerdata_proto_goTypes = nil
	file_vtworkerdata_proto_depIdxs = nil
}


text:
package com.fasterxml.jackson.databind.ser.impl;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;

import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;

/**
 * Simple serializer that will call configured type serializer, passing
 * in configured data serializer, and exposing it all as a simple
 * serializer.
 */
public final class TypeWrappedSerializer
    extends JsonSerializer<Object>
{
    final protected TypeSerializer _typeSerializer;
    final protected JsonSerializer<Object> _serializer;

    @SuppressWarnings("unchecked")
    public TypeWrappedSerializer(TypeSerializer typeSer, JsonSerializer<?> ser)
    {
        super();
        _typeSerializer = typeSer;
        _serializer = (JsonSerializer<Object>) ser;
    }

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        _serializer.serializeWithType(value, jgen, provider, _typeSerializer);
    }

    @Override
    public void serializeWithType(Object value, JsonGenerator jgen, SerializerProvider provider,
            TypeSerializer typeSer) throws IOException
    {
        /* Is this an erroneous call? For now, let's assume it is not, and
         * that type serializer is just overridden if so
         */
        _serializer.serializeWithType(value, jgen, provider, typeSer);
    }

    @Override
    public Class<Object> handledType() { return Object.class; }

    /*
    /**********************************************************
    /* Extended API for other core classes
    /**********************************************************
     */

    public JsonSerializer<Object> valueSerializer() {
        return _serializer;
    }

    public TypeSerializer typeSerializer() {
        return _typeSerializer;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Esfa.Vacancy.Application.Commands.CreateApprenticeship;
using Esfa.Vacancy.Domain.Entities;
using FluentAssertions;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;

namespace Esfa.Vacancy.UnitTests.CreateApprenticeship.Application.GivenACreateApprenticeshipParametersMapper.WhenMappingLocation
{
    [TestFixture]
    public class AndLocationTypeIsEmployerLocation
    {
        private CreateApprenticeshipParameters _mappedParameters;
        private EmployerInformation _employerInformation;
        private CreateApprenticeshipRequest _createApprenticeshipRequest;

        [SetUp]
        public void Setup()
        {
            var fixture = new Fixture().Customize(new AutoMoqCustomization());
            _createApprenticeshipRequest = fixture.Build<CreateApprenticeshipRequest>()
                .With(request => request.LocationType, LocationType.EmployerLocation)
                .Create();
            _employerInformation = fixture.Create<EmployerInformation>();

            var mapper = fixture.Create<CreateApprenticeshipParametersMapper>();
            _mappedParameters = mapper.MapFromRequest(_createApprenticeshipRequest, _employerInformation);
        }

        [Test]
        public void ThenMapLocationTypeToNationwide()
        {
            _mappedParameters.LocationTypeId.Should().Be(1);
        }

        [Test]
        public void ThenMapAddressLine1FromEmployeeInformation()
        {
            _mappedParameters.AddressLine1.Should().Be(_employerInformation.AddressLine1);
            _mappedParameters.AddressLine1.Should().NotBe(_createApprenticeshipRequest.AddressLine1);
        }

        [Test]
        public void ThenMapAddressLine2FromEmployeeInformation()
        {
            _mappedParameters.AddressLine2.Should().Be(_employerInformation.AddressLine2);
            _mappedParameters.AddressLine2.Should().NotBe(_createApprenticeshipRequest.AddressLine2);
        }

        [Test]
        public void ThenMapAddressLine3FromEmployeeInformation()
        {
            _mappedParameters.AddressLine3.Should().Be(_employerInformation.AddressLine3);
            _mappedParameters.AddressLine3.Should().NotBe(_createApprenticeshipRequest.AddressLine3);
        }

        [Test]
        public void ThenMapAddressLine4FromEmployeeInformation()
        {
            _mappedParameters.AddressLine4.Should().Be(_employerInformation.AddressLine4);
            _mappedParameters.AddressLine4.Should().NotBe(_createApprenticeshipRequest.AddressLine4);
        }

        [Test]
        public void ThenMapAddressLine5FromEmployeeInformation()
        {
            _mappedParameters.AddressLine5.Should().Be(_employerInformation.AddressLine5);
            _mappedParameters.AddressLine5.Should().NotBe(_createApprenticeshipRequest.AddressLine5);
        }

        [Test]
        public void ThenMapTownFromEmployeeInformation()
        {
            _mappedParameters.Town.Should().Be(_employerInformation.Town);
            _mappedParameters.Town.Should().NotBe(_createApprenticeshipRequest.Town);
        }

        [Test]
        public void ThenMapPostcodeFromEmployeeInformation()
        {
            _mappedParameters.Postcode.Should().Be(_employerInformation.Postcode);
            _mappedParameters.Postcode.Should().NotBe(_createApprenticeshipRequest.Postcode);
        }
    }
}


text:
package be.peopleware.struts_II.persistentBean;

import javax.servlet.ServletRequest;
import org.apache.struts.action.Action;

import be.peopleware.bean_I.persistent.AsynchronousCRUD;
import be.peopleware.exception_I.TechnicalException;

/**
 * Abstract superclass for PersistentBean actions. Persistent
 * bean actions require a fresh {@link AsynchronousCRUD}
 * instance for each request.
 *
 * @author    Jan Dockx
 * @author    Peopleware n.v.
 */
public abstract class CrudAction extends Action {

  /*
*/
  //------------------------------------------------------------------

  /** {@value} */
  public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$

  /*
*/

  /**
   * Create a fresh instance of {@link AsynchronousCRUD}. The
   * instance will be returned when it is no longer needed
   * through {@link #releaseAsynchronousCRUD(AsynchronousCRUD)}.
   *
   * @pre       request != null;
   * @param     request
   *            Servlet request information.
   * @result    result != null;
   * @throws    TechnicalException
   *            A fatal error from which recovery is not possible.
   */
  protected abstract AsynchronousCRUD createAsynchronousCRUD(
      final ServletRequest request)
          throws TechnicalException;

  /**
   * Release an instance of {@link AsynchronousCRUD}, created
   * by {@link #createAsynchronousCRUD(ServletRequest)}.
   *
   * @param     asyncCRUD
   *            The AsynchronousCRUD instance to be released.
   * @pre       asyncCRUD != null;
   */
  protected abstract void releaseAsynchronousCRUD(
      final AsynchronousCRUD asyncCRUD);

  /**
   * @basic
   */
  final public CrudActionSecurityStrategy getSecurityStrategy() {
    return $securityStrategy;
  }

  /**
   * @post new.getSecurityStragegy() == securityStrategy;
   */
  final public void setSecurityStrategy(CrudActionSecurityStrategy securityStrategy) {
    $securityStrategy = securityStrategy;
  }

  private CrudActionSecurityStrategy $securityStrategy;

}


text:
Polymer({

    is: 'iron-pages',

    behaviors: [
      Polymer.IronResizableBehavior,
      Polymer.IronSelectableBehavior
    ],

    properties: {

      // as the selected page is the only one visible, activateEvent
      // is both non-sensical and problematic; e.g. in cases where a user
      // handler attempts to change the page and the activateEvent
      // handler immediately changes it back
      activateEvent: {
        type: String,
        value: null
      }

    },

    observers: [
      '_selectedPageChanged(selected)'
    ],

    _selectedPageChanged: function(selected, old) {
      this.async(this.notifyResize);
    }
  });


text:
package fi.vincit.multiusertest.rule.expectation.value;

import fi.vincit.multiusertest.rule.expectation.AssertionCalled;
import fi.vincit.multiusertest.rule.expectation.CallbackCalled;
import fi.vincit.multiusertest.rule.expectation.ConsumerProducerSet;
import fi.vincit.multiusertest.util.UserIdentifier;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class ReturnValueCallExceptionExpectationTest {

    @Rule
    public ExpectedException expectException = ExpectedException.none();

    @Test
    public void throwIfExceptionIsExpected() throws Throwable {
        ReturnValueCallExceptionExpectation<Object, IllegalStateException> sut =
                new ReturnValueCallExceptionExpectation<>(IllegalStateException.class);

        expectException.expect(AssertionError.class);
        sut.handleExceptionNotThrown(new ConsumerProducerSet(UserIdentifier.getAnonymous()));
    }

    @Test
    public void throwIfExpectationNotExpected() throws Throwable {
        ReturnValueCallExceptionExpectation<Object, IllegalStateException> sut =
                new ReturnValueCallExceptionExpectation<>(IllegalStateException.class);

        sut.handleThrownException(new ConsumerProducerSet(UserIdentifier.getAnonymous()), new IllegalStateException());
    }

    @Test
    public void throwIfExpectationNotExpected_CustomAssert() throws Throwable {
        AssertionCalled called = new AssertionCalled();

        ReturnValueCallExceptionExpectation<Object, IllegalStateException> sut =
                new ReturnValueCallExceptionExpectation<>(
                        IllegalStateException.class,
                        expectException -> called.withThrowable(expectException)
                );

        sut.handleThrownException(new ConsumerProducerSet(UserIdentifier.getAnonymous()), new IllegalStateException("Foo"));

        assertThat(called.getException().getMessage(), is("Foo"));
    }

    @Test
    public void throwIfExpectationNotExpected_WrongType() throws Throwable {
        ReturnValueCallExceptionExpectation<Object, IllegalStateException> sut =
                new ReturnValueCallExceptionExpectation<>(IllegalStateException.class);

        expectException.expect(AssertionError.class);
        sut.handleThrownException(new ConsumerProducerSet(UserIdentifier.getAnonymous()), new IllegalArgumentException());
    }

    @Test
    public void callAndAssertValue() throws Throwable {
        CallbackCalled called = new CallbackCalled();
        ReturnValueCallExceptionExpectation<Object, IllegalStateException> sut =
                new ReturnValueCallExceptionExpectation<>(IllegalStateException.class);

        sut.callAndAssertValue(called::markCalled);

        assertThat(called.wasCalled(), is(true));
    }

}


text:
%% Illustrate CIE xy chromaticity calculations and plots
%
% *Chromaticity* coordinates are widely used to summarize the hue
% and saturation of a light.  We calculate the chromaticity
% coordinates and the gamut of light from a display.
%
% See also:  chromaticityPlot, displayCreate, displayPlot
%
% Copyright ImagEval Consulting, LLC 2011

%%
ieInit

%%  Example of a display chromaticity analysis

% Create a display object and plot its white point
dFilename = 'lcdExample';
display = displayCreate(dFilename);
wPoint = displayGet(display,'white XYZ');
chromaticityPlot(chromaticity(wPoint));

% Show the white point
chromaticityPlot(displayGet(display,'white xy'));

%% Show the chromaticity points of the primaries
spdXYZ = displayGet(display,'primaries xyz');
chromaticityPlot(chromaticity(spdXYZ));

% You can also plot the gamut with the lines this way
displayPlot(display,'gamut');

%% Example of a scene chromaticity analysis

% A macbeth color chart
scene = sceneCreate;
xyz = sceneGet(scene,'xyz');
xyz = RGB2XWFormat(xyz);
chromaticityPlot(chromaticity(xyz));
title('xy chromaticities of MCC chart')

%%


text:
{% extends "base.html" %}
{% load blog_utils %}

{% block title %}Entries for {{ month|date:"F"}}, {{ month|date:"Y" }} | {{ block.super }}{% endblock %}

{% block content %}

Entries for {{ month|date:"F"}}, {{ month|date:"Y" }}

{% if object_list %}
{% for post in object_list %}
    {% show_post_brief post %}
{% endfor %}
{% else %}

No entries.

{% endif %}
{% endblock %}


text:
from distutils.core import setup
import py2exe

setup(console=['Panda3DToolsGUI.py'])


text:
#ifndef _Connector_
#define _Connector_

#include "qpid/framing/FrameHandler.h"
#include "qpid/framing/ProtocolVersion.h"

#include <boost/shared_ptr.hpp>

#include <string>

namespace qpid {

namespace sys {
class ShutdownHandler;
class SecurityLayer;
class Poller;
struct SecuritySettings;
}

namespace framing {
class InputHandler;
class AMQFrame;
}

namespace client {

struct ConnectionSettings;
class ConnectionImpl;

///@internal
class Connector : public framing::FrameHandler
{
  public:
    // Protocol connector factory related stuff (it might be better to separate this code from the TCP Connector in the future)
    typedef Connector* Factory(boost::shared_ptr<qpid::sys::Poller>,
                               framing::ProtocolVersion, const ConnectionSettings&, ConnectionImpl*);
    static Connector* create(const std::string& proto,
                             boost::shared_ptr<qpid::sys::Poller>,
                             framing::ProtocolVersion, const ConnectionSettings&, ConnectionImpl*);
    static void registerFactory(const std::string& proto, Factory* connectorFactory);

    virtual ~Connector() {};
    virtual void connect(const std::string& host, const std::string& port) = 0;
    virtual void init() {};
    virtual void close() = 0;
    virtual void handle(framing::AMQFrame& frame) = 0;
    virtual void abort() = 0;

    virtual void setInputHandler(framing::InputHandler* handler) = 0;
    virtual void setShutdownHandler(sys::ShutdownHandler* handler) = 0;
    virtual const std::string& getIdentifier() const = 0;

    virtual void activateSecurityLayer(std::auto_ptr<qpid::sys::SecurityLayer>);

    virtual const qpid::sys::SecuritySettings* getSecuritySettings() = 0;
};

}}

#endif


text:
package org.rlcommunity.critterbot.simulator;

/**
  * ObjectStateIRDistanceSensor
  *
  * State component for an infrared distance sensor
  *
  * @author Marc G. Bellemare
  */

import java.awt.Graphics;
import java.awt.Color;

public class ObjectStateIRDistanceSensor implements ObjectState
{
  public static final String NAME = SimulatorComponentIRDistance.NAME;
  public boolean debugDrawRays = false;

  protected double aData;
  protected double aRange;

  /** The relative error of the distance sensor */
  protected double aError;

  public static final double defaultError = 0.05;

  public ObjectStateIRDistanceSensor(double pRange) {
    this (pRange, defaultError);
  }

  public ObjectStateIRDistanceSensor(double pRange, double pError) {
    aData = 0;
    aRange = pRange;
    aError = pError;
  }

  public double getError() { return aError; }

  /** Sets the current sensor reading for this sensor
    *
    * @param pValue The ir distance sensor reading
    */
  public void setSensorValue(double pValue) { aData = pValue; }

  /** Returns the current sensor reading
    * @return The current sensor reading
    */
  public double getSensorValue() { return aData; }

  /** Sets the maximum range of this distance sensor
    * @param pRange The new maximum range (in meters) of the sensor
    */
  public void setRange(double pRange) { aRange = pRange; }

  /** Returns the maximum range of this distance sensor
    * @return The maximum range of the sensor, in meters
    */
  public double getRange() { return aRange; }

  /** ObjectState interface */

  /** Returns a unique identifier for this type of state. */
  public String getName() { return NAME; }

  public Object clone()
  {
    ObjectStateIRDistanceSensor newSensor =
      new ObjectStateIRDistanceSensor(aRange);

    newSensor.copyFrom(this);

    return newSensor;
  }

  protected void copyFrom(ObjectState os)
  {
    ObjectStateIRDistanceSensor sensor = (ObjectStateIRDistanceSensor)os;

    // Redundant code, but here for sanity purposes
    this.aRange = sensor.aRange;
    this.aError = sensor.aError;
  }

  /** only for debugging */
  public RayIntersection intersection;

  /** (Potentially) draw something about the state; may be null. This
    *  most likely should be moved out of here when we have time.
    *
    * @param g The canvas to draw on
    * @param parent The owner of this state
    */
  public void draw(SimulatorGraphics g, SimulatorObject parent)
  {
    if (intersection != null)
    {
      Vector2D pt = intersection.point;

	    Color tempC = g.getColor();
	    /*g.setColor(Color.red);

      int rad = 5;
	    g.drawOval((int)pt.x-rad, (int)pt.y-rad, 2*rad, 2*rad);

      Vector2D outPoint = intersection.normal.times(2*rad).plus(pt);
		  g.drawLine((int)pt.x, (int)pt.y,
                 (int)outPoint.x, (int)outPoint.y);
     */
      if (debugDrawRays)
      {
        Vector2D pos = parent.getPosition();
        Double dir = parent.getDirection();

        double rad = 0.03;
        if( aData >= aRange ) {
          g.setColor(new Color(230, 220, 220));
          g.drawLine (pos.x, pos.y,
            (pos.x + aRange * Math.cos(dir)),
            (pos.y + aRange * Math.sin(dir)));
          g.setColor(Color.orange);
          g.drawOval((pos.x + aRange * Math.cos(dir)) - rad,
            (pos.y + aRange * Math.sin(dir)) - rad,
            2 * rad, 2 * rad);
        }
        else {
          g.setColor(new Color(230, 220, 220));
          g.drawLine (pos.x, pos.y, pt.x, pt.y);
          g.setColor(Color.orange);
          g.drawOval(pt.x-rad, pt.y-rad, 2*rad, 2*rad);

        }
      }

      g.setColor(tempC);
    }
  }

  /** Provides a mean of clearing whatever data this ObjectState contains
    *  and resetting it to the default values. Meant to be used when
    *  re-initializing a state.
    */
  public void clearTransient()
  {
    aData = 0;
  }
}