<commit_before>
#include "Uniform.h"
#include "Utilities.h"

#include <ionMath.h>
#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>

namespace ion
{
	namespace GL
	{
		template <>
		void Uniform::Bind<float>(uint const Handle, float const & Value)
		{
			CheckedGLCall(glUniform1f(Handle, Value));
		}

		template <>
		void Uniform::Bind<int>(uint const Handle, int const & Value)
		{
			CheckedGLCall(glUniform1i(Handle, Value));
		}

		template <>
		void Uniform::Bind<uint>(uint const Handle, uint const & Value)
		{
			CheckedGLCall(glUniform1i(Handle, Value));
		}

		template <>
		void Uniform::Bind<glm::mat4>(uint const Handle, glm::mat4 const & Value)
		{
			CheckedGLCall(glUniformMatrix4fv(Handle, 1, GL_FALSE, glm::value_ptr(Value)));
		}

		template <>
		void Uniform::Bind<vec2f>(uint const Handle, vec2f const & Value)
		{
			CheckedGLCall(glUniform2f(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3f>(uint const Handle, vec3f const & Value)
		{
			CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4f>(uint const Handle, vec4f const & Value)
		{
			CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<color3f>(uint const Handle, color3f const & Value)
		{
			CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<color4f>(uint const Handle, color4f const & Value)
		{
			CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<vec2i>(uint const Handle, vec2i const & Value)
		{
			CheckedGLCall(glUniform2i(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3i>(uint const Handle, vec3i const & Value)
		{
			CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4i>(uint const Handle, vec4i const & Value)
		{
			CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<color3i>(uint const Handle, color3i const & Value)
		{
			CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<color4i>(uint const Handle, color4i const & Value)
		{
			CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<vec2u>(uint const Handle, vec2u const & Value)
		{
			CheckedGLCall(glUniform2ui(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3u>(uint const Handle, vec3u const & Value)
		{
			CheckedGLCall(glUniform3ui(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4u>(uint const Handle, vec4u const & Value)
		{
			CheckedGLCall(glUniform4ui(Handle, Value[0], Value[1], Value[2], Value[3]));
		}
	}
}
<commit_msg>Add bool binding function for GL::Uniform<commit_after>
#include "Uniform.h"
#include "Utilities.h"

#include <ionMath.h>
#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>

namespace ion
{
	namespace GL
	{
		template <>
		void Uniform::Bind<float>(uint const Handle, float const & Value)
		{
			CheckedGLCall(glUniform1f(Handle, Value));
		}

		template <>
		void Uniform::Bind<int>(uint const Handle, int const & Value)
		{
			CheckedGLCall(glUniform1i(Handle, Value));
		}

		template <>
		void Uniform::Bind<uint>(uint const Handle, uint const & Value)
		{
			CheckedGLCall(glUniform1i(Handle, Value));
		}

		template <>
		void Uniform::Bind<glm::mat4>(uint const Handle, glm::mat4 const & Value)
		{
			CheckedGLCall(glUniformMatrix4fv(Handle, 1, GL_FALSE, glm::value_ptr(Value)));
		}

		template <>
		void Uniform::Bind<vec2f>(uint const Handle, vec2f const & Value)
		{
			CheckedGLCall(glUniform2f(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3f>(uint const Handle, vec3f const & Value)
		{
			CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4f>(uint const Handle, vec4f const & Value)
		{
			CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<color3f>(uint const Handle, color3f const & Value)
		{
			CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<color4f>(uint const Handle, color4f const & Value)
		{
			CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<vec2i>(uint const Handle, vec2i const & Value)
		{
			CheckedGLCall(glUniform2i(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3i>(uint const Handle, vec3i const & Value)
		{
			CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4i>(uint const Handle, vec4i const & Value)
		{
			CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<color3i>(uint const Handle, color3i const & Value)
		{
			CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<color4i>(uint const Handle, color4i const & Value)
		{
			CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<vec2u>(uint const Handle, vec2u const & Value)
		{
			CheckedGLCall(glUniform2ui(Handle, Value[0], Value[1]));
		}

		template <>
		void Uniform::Bind<vec3u>(uint const Handle, vec3u const & Value)
		{
			CheckedGLCall(glUniform3ui(Handle, Value[0], Value[1], Value[2]));
		}

		template <>
		void Uniform::Bind<vec4u>(uint const Handle, vec4u const & Value)
		{
			CheckedGLCall(glUniform4ui(Handle, Value[0], Value[1], Value[2], Value[3]));
		}

		template <>
		void Uniform::Bind<bool>(uint const Handle, bool const & Value)
		{
			CheckedGLCall(glUniform1i(Handle, Value ? 1 : 0));
		}
	}
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <cassert>
#include <miopen/activ.hpp>
#include <miopen/logger.hpp>

namespace miopen {

ActivationDescriptor::ActivationDescriptor() {}

ActivationDescriptor::ActivationDescriptor(miopenActivationMode_t m, const double* pparms)
    : parms(pparms, pparms + 3), mode(m)
{
}

ActivationDescriptor::ActivationDescriptor(miopenActivationMode_t m,
                                           double alpha,
                                           double beta,
                                           double gamma)
    : parms({alpha, beta, gamma}), mode(m)
{
}

miopenActivationMode_t ActivationDescriptor::GetMode() const { return this->mode; }

double ActivationDescriptor::GetAlpha() const { return this->parms[0]; }

double ActivationDescriptor::GetBeta() const { return this->parms[1]; }

double ActivationDescriptor::GetGamma() const { return this->parms[2]; }
std::ostream& operator<<(std::ostream& stream, const ActivationDescriptor& x)
{
    MIOPEN_LOG_ENUM(stream,
                    x.mode,
                    miopenActivationPATHTRU,
                    miopenActivationLOGISTIC,
                    miopenActivationTANH,
                    miopenActivationRELU,
                    miopenActivationSOFTRELU,
                    miopenActivationABS,
                    miopenActivationPOWER
                    // miopenActivationBRELU,
                    // miopenActivationSQUARE,
                    // miopenActivationSQR,
                    // miopenActivationLINEAR
                    )
        << ", ";
    LogRange(stream, x.parms, ", ") << ", ";
    return stream;
}
} // namespace miopen
<commit_msg>update activation numerater in activ.cpp<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <cassert>
#include <miopen/activ.hpp>
#include <miopen/logger.hpp>

namespace miopen {

ActivationDescriptor::ActivationDescriptor() {}

ActivationDescriptor::ActivationDescriptor(miopenActivationMode_t m, const double* pparms)
    : parms(pparms, pparms + 3), mode(m)
{
}

ActivationDescriptor::ActivationDescriptor(miopenActivationMode_t m,
                                           double alpha,
                                           double beta,
                                           double gamma)
    : parms({alpha, beta, gamma}), mode(m)
{
}

miopenActivationMode_t ActivationDescriptor::GetMode() const { return this->mode; }

double ActivationDescriptor::GetAlpha() const { return this->parms[0]; }

double ActivationDescriptor::GetBeta() const { return this->parms[1]; }

double ActivationDescriptor::GetGamma() const { return this->parms[2]; }
std::ostream& operator<<(std::ostream& stream, const ActivationDescriptor& x)
{
    MIOPEN_LOG_ENUM(stream,
                    x.mode,
                    miopenActivationPATHTRU,
                    miopenActivationLOGISTIC,
                    miopenActivationTANH,
                    miopenActivationRELU,
                    miopenActivationSOFTRELU,
                    miopenActivationABS,
                    miopenActivationPOWER,
                    miopenActivationCLIPPEDRELU,
                    miopenActivationLEAKYRELU,
                    miopenActivationELU,
                    )
        << ", ";
    LogRange(stream, x.parms, ", ") << ", ";
    return stream;
}
} // namespace miopen
<|endoftext|>


<commit_before>#include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <nan.h>
#include <cstddef>
#include <cassert>
#include <cstring>

#include "KeccakNISTInterface.h"

#define MAX_DIGEST_SIZE 64
#define ASSERT_IS_STRING_OR_BUFFER(val) \
	if (!val->IsString() && !Buffer::HasInstance(val)) { \
		return Nan::ThrowTypeError("Not a string or buffer"); \
	}

using namespace node;
using namespace v8;
using namespace Node_SHA3;

static void toHex(const char *data_buf, size_t size, char *output);

class SHA3Hash: public ObjectWrap {
private:
	SHA3Hash()
	{}

	~SHA3Hash()
	{}

	static
	NAN_METHOD(New) {
		SHA3Hash *obj;
		int32_t hashlen;

		hashlen = info[0]->IsUndefined() ? 512 : info[0]->Int32Value();
		switch (hashlen) {
			case 224:
			case 256:
			case 384:
			case 512:
				break;
			default:
				return Nan::ThrowTypeError("Unsupported hash length");
		}

		if (info.IsConstructCall()) {
			// Invoked as constructor.
			obj = new SHA3Hash();
			obj->Wrap(info.This());
			obj->bitlen = hashlen;
			::Init(&obj->state, hashlen);
			info.GetReturnValue().Set(info.This());
		} else {
			// Invoked as a plain function.
			const int argc = 1;
			Local<Value> argv[argc] = { Nan::New<Number>(hashlen) };
			Local<Function> cons = Nan::New<Function>(constructor);
			info.GetReturnValue().Set(cons->NewInstance(argc, argv));
		}
	}

public:
	hashState state;
	int32_t bitlen;

	static
	NAN_MODULE_INIT(Init) {
		Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
		t->SetClassName(Nan::New<String>("SHA3Hash").ToLocalChecked());
		t->InstanceTemplate()->SetInternalFieldCount(1);

		Nan::SetPrototypeMethod(t, "update", Update);
		Nan::SetPrototypeMethod(t, "digest", Digest);

		constructor.Reset(t->GetFunction());
		target->Set(Nan::New<String>("SHA3Hash").ToLocalChecked(), t->GetFunction());
	}

	static
	NAN_METHOD(Update) {
		SHA3Hash *obj = ObjectWrap::Unwrap<SHA3Hash>(info.This());

		ASSERT_IS_STRING_OR_BUFFER(info[0]);
		enum Nan::Encoding enc = static_cast<Nan::Encoding>(ParseEncoding(Isolate::GetCurrent(), info[1]));
		ssize_t len = Nan::DecodeBytes(info[0], enc);

		if (len < 0) {
			return Nan::ThrowError("Bad argument");
		}

		if (Buffer::HasInstance(info[0])) {
			Local<Object> buffer_obj = info[0]->ToObject();
			const char *buffer_data = Buffer::Data(buffer_obj);
			size_t buffer_length = Buffer::Length(buffer_obj);
			::Update(&obj->state, (const BitSequence *) buffer_data, buffer_length * 8);
		} else {
			char *buf = new char[len];
			ssize_t written = Nan::DecodeWrite(buf, len, info[0], enc);
			assert(written == len);
			::Update(&obj->state, (const BitSequence *) buf, len * 8);
			delete[] buf;
		}

		info.GetReturnValue().Set(info.This());
	}

	static
	NAN_METHOD(Digest) {
		SHA3Hash *obj = ObjectWrap::Unwrap<SHA3Hash>(info.This());
		hashState state2;
		unsigned char digest[MAX_DIGEST_SIZE];

		memcpy(&state2, &obj->state, sizeof(hashState));
		Final(&state2, digest);

		Local<Value> outString;
		enum Nan::Encoding enc = static_cast<Nan::Encoding>(ParseEncoding(Isolate::GetCurrent(), info[0], node::encoding::BINARY));
		if (enc == Nan::Encoding::HEX) {
			// Hex encoding
			char hexdigest[MAX_DIGEST_SIZE * 2];
			toHex((const char *) digest, obj->bitlen / 8, hexdigest);
			outString = Nan::Encode(hexdigest, obj->bitlen / 4, Nan::Encoding::BINARY);
		} else if (enc == Nan::Encoding::BINARY /* || enc == BUFFER */) {
			outString = Nan::Encode(digest, obj->bitlen / 8, enc);
		} else {
			return Nan::ThrowError("Unsupported output encoding");
		}

		info.GetReturnValue().Set(outString);
	}

private:
	static Nan::Persistent<Function> constructor;
};

Nan::Persistent<Function> SHA3Hash::constructor;

static const char hex_chars[] = {
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
	'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
	'u', 'v', 'w', 'x', 'y', 'z'
};

static void
toHex(const char *data_buf, size_t size, char *output) {
	size_t i;

	for (i = 0; i < size; i++) {
		output[i * 2] = hex_chars[(unsigned char) data_buf[i] / 16];
		output[i * 2 + 1] = hex_chars[(unsigned char) data_buf[i] % 16];
	}
}

NODE_MODULE(sha3, SHA3Hash::Init)
<commit_msg>support classic enum syntax<commit_after>#include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <nan.h>
#include <cstddef>
#include <cassert>
#include <cstring>

#include "KeccakNISTInterface.h"

#define MAX_DIGEST_SIZE 64
#define ASSERT_IS_STRING_OR_BUFFER(val) \
	if (!val->IsString() && !Buffer::HasInstance(val)) { \
		return Nan::ThrowTypeError("Not a string or buffer"); \
	}

using namespace node;
using namespace v8;
using namespace Node_SHA3;

static void toHex(const char *data_buf, size_t size, char *output);

class SHA3Hash: public ObjectWrap {
private:
	SHA3Hash()
	{}

	~SHA3Hash()
	{}

	static
	NAN_METHOD(New) {
		SHA3Hash *obj;
		int32_t hashlen;

		hashlen = info[0]->IsUndefined() ? 512 : info[0]->Int32Value();
		switch (hashlen) {
			case 224:
			case 256:
			case 384:
			case 512:
				break;
			default:
				return Nan::ThrowTypeError("Unsupported hash length");
		}

		if (info.IsConstructCall()) {
			// Invoked as constructor.
			obj = new SHA3Hash();
			obj->Wrap(info.This());
			obj->bitlen = hashlen;
			::Init(&obj->state, hashlen);
			info.GetReturnValue().Set(info.This());
		} else {
			// Invoked as a plain function.
			const int argc = 1;
			Local<Value> argv[argc] = { Nan::New<Number>(hashlen) };
			Local<Function> cons = Nan::New<Function>(constructor);
			info.GetReturnValue().Set(cons->NewInstance(argc, argv));
		}
	}

public:
	hashState state;
	int32_t bitlen;

	static
	NAN_MODULE_INIT(Init) {
		Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
		t->SetClassName(Nan::New<String>("SHA3Hash").ToLocalChecked());
		t->InstanceTemplate()->SetInternalFieldCount(1);

		Nan::SetPrototypeMethod(t, "update", Update);
		Nan::SetPrototypeMethod(t, "digest", Digest);

		constructor.Reset(t->GetFunction());
		target->Set(Nan::New<String>("SHA3Hash").ToLocalChecked(), t->GetFunction());
	}

	static
	NAN_METHOD(Update) {
		SHA3Hash *obj = ObjectWrap::Unwrap<SHA3Hash>(info.This());

		ASSERT_IS_STRING_OR_BUFFER(info[0]);
		enum Nan::Encoding enc = static_cast<Nan::Encoding>(ParseEncoding(Isolate::GetCurrent(), info[1]));
		ssize_t len = Nan::DecodeBytes(info[0], enc);

		if (len < 0) {
			return Nan::ThrowError("Bad argument");
		}

		if (Buffer::HasInstance(info[0])) {
			Local<Object> buffer_obj = info[0]->ToObject();
			const char *buffer_data = Buffer::Data(buffer_obj);
			size_t buffer_length = Buffer::Length(buffer_obj);
			::Update(&obj->state, (const BitSequence *) buffer_data, buffer_length * 8);
		} else {
			char *buf = new char[len];
			ssize_t written = Nan::DecodeWrite(buf, len, info[0], enc);
			assert(written == len);
			::Update(&obj->state, (const BitSequence *) buf, len * 8);
			delete[] buf;
		}

		info.GetReturnValue().Set(info.This());
	}

	static
	NAN_METHOD(Digest) {
		SHA3Hash *obj = ObjectWrap::Unwrap<SHA3Hash>(info.This());
		hashState state2;
		unsigned char digest[MAX_DIGEST_SIZE];

		memcpy(&state2, &obj->state, sizeof(hashState));
		Final(&state2, digest);

		Local<Value> outString;
		enum Nan::Encoding enc = static_cast<Nan::Encoding>(ParseEncoding(Isolate::GetCurrent(), info[0], node::BINARY));
		if (enc == Nan::HEX) {
			// Hex encoding
			char hexdigest[MAX_DIGEST_SIZE * 2];
			toHex((const char *) digest, obj->bitlen / 8, hexdigest);
			outString = Nan::Encode(hexdigest, obj->bitlen / 4, Nan::BINARY);
		} else if (enc == Nan::BINARY /* || enc == BUFFER */) {
			outString = Nan::Encode(digest, obj->bitlen / 8, enc);
		} else {
			return Nan::ThrowError("Unsupported output encoding");
		}

		info.GetReturnValue().Set(outString);
	}

private:
	static Nan::Persistent<Function> constructor;
};

Nan::Persistent<Function> SHA3Hash::constructor;

static const char hex_chars[] = {
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
	'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
	'u', 'v', 'w', 'x', 'y', 'z'
};

static void
toHex(const char *data_buf, size_t size, char *output) {
	size_t i;

	for (i = 0; i < size; i++) {
		output[i * 2] = hex_chars[(unsigned char) data_buf[i] / 16];
		output[i * 2 + 1] = hex_chars[(unsigned char) data_buf[i] % 16];
	}
}

NODE_MODULE(sha3, SHA3Hash::Init)
<|endoftext|>


<commit_before>#include "ics3/angle.hpp"

#define _USE_MATH_DEFINES
#include <cmath>

ics::Angle ics::Angle::newDegree() noexcept {
  static const double limit = 130;
  static const Angle DEGREE(-limit, limit, 800.0 / 27.0);
  return DEGREE;
}

ics::Angle ics::Angle::newRadian() noexcept {
  static const double limit = 130 * M_PI / 180;
  static const Angle RADIAN(-limit, limit, 16000.0 / 3.0 / M_PI);
  return RADIAN;
}

double ics::Angle::get() const noexcept {
  return data;
}

void ics::Angle::set(double angle) throw(std::invalid_argument) {
  if (angle < min) throw std::invalid_argument("Too small angle");
  if (max < angle) throw std::invalid_argument("Too big angle");
  data = angle;
}

uint16_t ics::Angle::getRaw() const noexcept {
  return static_cast<uint16_t>(data * rawCalibration + 7500);
}

void ics::Angle::setRaw(uint16_t raw) throw(std::invalid_argument) {
  try {
    set((raw - 7500) / rawCalibration);
  } catch (std::invalid_argument e) {
    throw e;
  }
}

ics::Angle::Angle(double min, double max, double calibration) noexcept
: min(min),
  max(max),
  rawCalibration(calibration),
  data(0)
{}
<commit_msg>Update angle.cpp<commit_after>#include "ics3/angle.hpp"

#define _USE_MATH_DEFINES
#include <cmath>

ics::Angle ics::Angle::newDegree() noexcept {
  static const double limit = 130;
  static const Angle DEGREE(-limit, limit, 800.0 / 27.0);
  return DEGREE;
}

ics::Angle ics::Angle::newRadian() noexcept {
  static const double limit = 130 * M_PI / 180;
  static const Angle RADIAN(-limit, limit, 16000.0 / 3.0 / M_PI);
  return RADIAN;
}

double ics::Angle::get() const noexcept {
  return data;
}

void ics::Angle::set(double angle) throw(std::invalid_argument) {
  if (angle < min) throw std::invalid_argument("Too small angle");
  if (max < angle) throw std::invalid_argument("Too big angle");
  data = angle;
}

uint16_t ics::Angle::getRaw() const noexcept {
  return static_cast<uint16_t>(data * rawCalibration + 7500);
}

void ics::Angle::setRaw(uint16_t raw) throw(std::invalid_argument) {
  try {
    set((raw - 7500) / rawCalibration);
  } catch (std::invalid_argument &e) {
    throw;
  }
}

ics::Angle::Angle(double min, double max, double calibration) noexcept
: min(min),
  max(max),
  rawCalibration(calibration),
  data(0)
{}
<|endoftext|>


<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pal.h"
#include "utils.h"
#include "trace.h"

#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>

#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif

#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif

bool pal::find_coreclr(pal::string_t& recv)
{
    pal::string_t candidate;
    pal::string_t test;

    // Try /usr/share/dotnet and /usr/local/share/dotnet
    candidate.assign("/usr/share/dotnet/runtime/coreclr");
    if (coreclr_exists_in_dir(candidate)) {
        recv.assign(candidate);
        return true;
    }

    candidate.assign("/usr/local/share/dotnet/runtime/coreclr");
    if (coreclr_exists_in_dir(candidate)) {
        recv.assign(candidate);
        return true;
    }
    return false;
}

bool pal::load_library(const char_t* path, dll_t& dll)
{
    dll = dlopen(path, RTLD_LAZY);
    if (dll == nullptr)
    {
        trace::error(_X("failed to load %s, error: %s"), path, dlerror());
        return false;
    }
    return true;
}

pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
    auto result = dlsym(library, name);
    if (result == nullptr)
    {
        trace::error(_X("failed to resolve library symbol %s, error: %s"), name, dlerror());
    }
    return result;
}

void pal::unload_library(dll_t library)
{
    if (dlclose(library) != 0)
    {
        trace::warning(_X("failed to unload library, error: %s"), dlerror());
    }
}

int pal::xtoi(const char_t* input)
{
    return atoi(input);
}

bool pal::is_path_rooted(const pal::string_t& path)
{
    return path.front() == '/';
}

bool pal::get_default_packages_directory(pal::string_t& recv)
{
    if (!pal::getenv("HOME", recv))
    {
        return false;
    }
    append_path(recv, _X(".dnx"));
    append_path(recv, _X("packages"));
    return true;
}

#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t& recv)
{
    uint32_t path_length = 0;
    if (_NSGetExecutablePath(nullptr, &path_length) == -1)
    {
        char path_buf[path_length];
        if (_NSGetExecutablePath(path_buf, &path_length) == 0)
        {
            recv.assign(path_buf);
            return true;
        }
    }
    return false;
}
#else
bool pal::get_own_executable_path(pal::string_t& recv)
{
    // Just return the symlink to the exe from /proc
    // We'll call realpath on it later
    recv.assign(symlinkEntrypointExecutable);
    return true;
}
#endif

bool pal::getenv(const pal::char_t* name, pal::string_t& recv)
{
    auto result = ::getenv(name);
    if (result != nullptr)
    {
        recv.assign(result);
    }

    // We don't return false. Windows does have a concept of an error reading the variable,
    // but Unix just returns null, which we treat as the variable not existing.
    return true;
}

bool pal::realpath(pal::string_t& path)
{
    pal::char_t buf[PATH_MAX];
    auto resolved = ::realpath(path.c_str(), buf);
    if (resolved == nullptr)
    {
        if (errno == ENOENT)
        {
            return false;
        }
        perror("realpath()");
        return false;
    }
    path.assign(resolved);
    return true;
}

bool pal::file_exists(const pal::string_t& path)
{
    struct stat buffer;
    return (::stat(path.c_str(), &buffer) == 0);
}

std::vector<pal::string_t> pal::readdir(const pal::string_t& path)
{
    std::vector<pal::string_t> files;

    auto dir = opendir(path.c_str());
    if (dir != nullptr)
    {
        struct dirent* entry = nullptr;
        while((entry = readdir(dir)) != nullptr)
        {
            // We are interested in files only
            switch (entry->d_type)
            {
            case DT_REG:
                break;

            // Handle symlinks and file systems that do not support d_type
            case DT_LNK:
            case DT_UNKNOWN:
                {
                    std::string fullFilename;

                    fullFilename.append(path);
                    fullFilename.push_back(DIR_SEPARATOR);
                    fullFilename.append(entry->d_name);

                    struct stat sb;
                    if (stat(fullFilename.c_str(), &sb) == -1)
                    {
                        continue;
                    }

                    if (!S_ISREG(sb.st_mode))
                    {
                        continue;
                    }
                }
                break;

            default:
                continue;
            }

            files.push_back(pal::string_t(entry->d_name));
        }
    }

    return files;
}
<commit_msg>Changes for corehost default path resolution on mac<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pal.h"
#include "utils.h"
#include "trace.h"

#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>

#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif

#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif

bool pal::find_coreclr(pal::string_t& recv)
{
    pal::string_t candidate;
    pal::string_t test;

    // Try /usr/share/dotnet and /usr/local/share/dotnet/cli
    // TODO: These paths should be consistent
    candidate.assign("/usr/share/dotnet/runtime/coreclr");
    if (coreclr_exists_in_dir(candidate)) {
        recv.assign(candidate);
        return true;
    }

    candidate.assign("/usr/local/share/dotnet/cli/runtime/coreclr");
    if (coreclr_exists_in_dir(candidate)) {
        recv.assign(candidate);
        return true;
    }
    return false;
}

bool pal::load_library(const char_t* path, dll_t& dll)
{
    dll = dlopen(path, RTLD_LAZY);
    if (dll == nullptr)
    {
        trace::error(_X("failed to load %s, error: %s"), path, dlerror());
        return false;
    }
    return true;
}

pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
    auto result = dlsym(library, name);
    if (result == nullptr)
    {
        trace::error(_X("failed to resolve library symbol %s, error: %s"), name, dlerror());
    }
    return result;
}

void pal::unload_library(dll_t library)
{
    if (dlclose(library) != 0)
    {
        trace::warning(_X("failed to unload library, error: %s"), dlerror());
    }
}

int pal::xtoi(const char_t* input)
{
    return atoi(input);
}

bool pal::is_path_rooted(const pal::string_t& path)
{
    return path.front() == '/';
}

bool pal::get_default_packages_directory(pal::string_t& recv)
{
    if (!pal::getenv("HOME", recv))
    {
        return false;
    }
    append_path(recv, _X(".dnx"));
    append_path(recv, _X("packages"));
    return true;
}

#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t& recv)
{
    uint32_t path_length = 0;
    if (_NSGetExecutablePath(nullptr, &path_length) == -1)
    {
        char path_buf[path_length];
        if (_NSGetExecutablePath(path_buf, &path_length) == 0)
        {
            recv.assign(path_buf);
            return true;
        }
    }
    return false;
}
#else
bool pal::get_own_executable_path(pal::string_t& recv)
{
    // Just return the symlink to the exe from /proc
    // We'll call realpath on it later
    recv.assign(symlinkEntrypointExecutable);
    return true;
}
#endif

bool pal::getenv(const pal::char_t* name, pal::string_t& recv)
{
    auto result = ::getenv(name);
    if (result != nullptr)
    {
        recv.assign(result);
    }

    // We don't return false. Windows does have a concept of an error reading the variable,
    // but Unix just returns null, which we treat as the variable not existing.
    return true;
}

bool pal::realpath(pal::string_t& path)
{
    pal::char_t buf[PATH_MAX];
    auto resolved = ::realpath(path.c_str(), buf);
    if (resolved == nullptr)
    {
        if (errno == ENOENT)
        {
            return false;
        }
        perror("realpath()");
        return false;
    }
    path.assign(resolved);
    return true;
}

bool pal::file_exists(const pal::string_t& path)
{
    struct stat buffer;
    return (::stat(path.c_str(), &buffer) == 0);
}

std::vector<pal::string_t> pal::readdir(const pal::string_t& path)
{
    std::vector<pal::string_t> files;

    auto dir = opendir(path.c_str());
    if (dir != nullptr)
    {
        struct dirent* entry = nullptr;
        while((entry = readdir(dir)) != nullptr)
        {
            // We are interested in files only
            switch (entry->d_type)
            {
            case DT_REG:
                break;

            // Handle symlinks and file systems that do not support d_type
            case DT_LNK:
            case DT_UNKNOWN:
                {
                    std::string fullFilename;

                    fullFilename.append(path);
                    fullFilename.push_back(DIR_SEPARATOR);
                    fullFilename.append(entry->d_name);

                    struct stat sb;
                    if (stat(fullFilename.c_str(), &sb) == -1)
                    {
                        continue;
                    }

                    if (!S_ISREG(sb.st_mode))
                    {
                        continue;
                    }
                }
                break;

            default:
                continue;
            }

            files.push_back(pal::string_t(entry->d_name));
        }
    }

    return files;
}
<|endoftext|>


<commit_before>#ifndef __itkLabelImageGenericInterpolateImageFunction_hxx
#define __itkLabelImageGenericInterpolateImageFunction_hxx

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include <itkImageRegionConstIterator.h>

namespace itk
{

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::LabelImageGenericInterpolateImageFunction()
{
}

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
void LabelImageGenericInterpolateImageFunction<TInputImage,TInterpolator, TCoordRep>
::SetInputImage( const TInputImage *image ) {
	/** We have one adaptor and one interpolator per label to keep the class thread-safe:
	 *  changing the adaptor's accepted value wouldn't work when called from a multi-threaded filter */
	if (image) {
		m_Labels.clear();
		typedef itk::ImageRegionConstIterator<TInputImage> IteratorType;
		IteratorType it(image,image->GetLargestPossibleRegion());
		it.GoToBegin();
		for (; !it.IsAtEnd(); ++it) {
			m_Labels.insert(it.Get());
		}
		m_InternalInterpolators.clear();
		m_LabelSelectionAdaptors.clear();
		for(typename LabelSetType::const_iterator i=m_Labels.begin(); i != m_Labels.end(); ++i) {
			typename LabelSelectionAdaptorType::Pointer adapt = LabelSelectionAdaptorType::New();
			// This adaptor doesn't implement Set() so this should be safe
			adapt->SetImage(const_cast<TInputImage*>(image));
			adapt->SetAcceptedValue(*i);
			m_LabelSelectionAdaptors.push_back(adapt);
			typename InternalInterpolatorType::Pointer interp = InternalInterpolatorType::New();
			interp->SetInputImage(adapt);
			m_InternalInterpolators.push_back(interp);
		}
	}
	Superclass::SetInputImage(image);
}

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
typename LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::OutputType
LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::EvaluateAtContinuousIndex( const ContinuousIndexType & cindex, OutputType * grad ) const
{
	/** Interpolate the binary mask corresponding to each label and return the label
	 * with the highest value */
	double value=0;
	typename TInputImage::PixelType best_label=0;
	typename LabelSetType::const_iterator it;
	int i;
	for(it=m_Labels.begin(), i = 0;
		it != m_Labels.end(); ++it, ++i) {
		double tmp = m_InternalInterpolators[i]->EvaluateAtContinuousIndex(cindex);
		if( tmp > value) {
			value = tmp;
			best_label = (*it);
		}
	}
		return best_label;
}

} // namespace itk

#endif
<commit_msg>COMP:  Unused variable warning.<commit_after>#ifndef __itkLabelImageGenericInterpolateImageFunction_hxx
#define __itkLabelImageGenericInterpolateImageFunction_hxx

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include <itkImageRegionConstIterator.h>

namespace itk
{

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::LabelImageGenericInterpolateImageFunction()
{
}

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
void LabelImageGenericInterpolateImageFunction<TInputImage,TInterpolator, TCoordRep>
::SetInputImage( const TInputImage *image ) {
	/** We have one adaptor and one interpolator per label to keep the class thread-safe:
	 *  changing the adaptor's accepted value wouldn't work when called from a multi-threaded filter */
	if (image) {
		m_Labels.clear();
		typedef itk::ImageRegionConstIterator<TInputImage> IteratorType;
		IteratorType it(image,image->GetLargestPossibleRegion());
		it.GoToBegin();
		for (; !it.IsAtEnd(); ++it) {
			m_Labels.insert(it.Get());
		}
		m_InternalInterpolators.clear();
		m_LabelSelectionAdaptors.clear();
		for(typename LabelSetType::const_iterator i=m_Labels.begin(); i != m_Labels.end(); ++i) {
			typename LabelSelectionAdaptorType::Pointer adapt = LabelSelectionAdaptorType::New();
			// This adaptor doesn't implement Set() so this should be safe
			adapt->SetImage(const_cast<TInputImage*>(image));
			adapt->SetAcceptedValue(*i);
			m_LabelSelectionAdaptors.push_back(adapt);
			typename InternalInterpolatorType::Pointer interp = InternalInterpolatorType::New();
			interp->SetInputImage(adapt);
			m_InternalInterpolators.push_back(interp);
		}
	}
	Superclass::SetInputImage(image);
}

template<typename TInputImage, template<class, typename> class TInterpolator , typename TCoordRep>
typename LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::OutputType
LabelImageGenericInterpolateImageFunction<TInputImage, TInterpolator, TCoordRep>
::EvaluateAtContinuousIndex( const ContinuousIndexType & cindex, OutputType * itkNotUsed( grad ) ) const
{
	/** Interpolate the binary mask corresponding to each label and return the label
	 * with the highest value */
	double value=0;
	typename TInputImage::PixelType best_label=0;
	typename LabelSetType::const_iterator it;
	int i;
	for(it=m_Labels.begin(), i = 0;
		it != m_Labels.end(); ++it, ++i) {
		double tmp = m_InternalInterpolators[i]->EvaluateAtContinuousIndex(cindex);
		if( tmp > value) {
			value = tmp;
			best_label = (*it);
		}
	}
		return best_label;
}

} // namespace itk

#endif
<|endoftext|>


<commit_before>// Copyright 2016 Etix Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "server.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>

// If time overlay is enabled, add it to the pipeline
std::string time_overlay(std::shared_ptr<t_config> &config) {
  if (config->time) {
    return " ! timeoverlay halignment=left valignment=top "
           "shaded-background=true "
           "font-desc=\"Sans 10\" ! "
           "clockoverlay halignment=right valignment=top "
           "shaded-background=true "
           "font-desc=\"Sans 10\"";
  }
  return "";
}

// Take raw, change caps according to conf and transcode in h264
std::string encode(std::shared_ptr<t_config> &config) {
  std::cout << "H264 encoding with:" << std::endl
            << "Framerate:\t" << config->framerate << std::endl
            << "Resolution:\t" << config->scale.first << "x"
            << config->scale.second << std::endl
            << std::endl;

  std::string launchCmd = "";

  // Change caps & encode
  launchCmd += " ! videoscale ! video/x-raw,width=";
  launchCmd += config->scale.first;
  launchCmd += ",height=";
  launchCmd += config->scale.second;
  launchCmd += " ! videorate ! video/x-raw,framerate=";
  launchCmd += config->framerate;
  launchCmd += "/1";
  launchCmd += " ! capsfilter ! queue"
               " ! x264enc speed-preset=superfast "
               "tune=zerolatency";

  return launchCmd;
}

// Rtsp input pipeline
std::string create_rtsp_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  // Receive & depay
  launchCmd += "rtspsrc latency=0 auto-start=true location=";
  launchCmd += config->input;
  launchCmd += " ! rtph264depay";

  // If user request modification in framerate or scale -> encode
  if (config->framerate != DEFAULT_FRAMERATE ||
      config->scale.first != DEFAULT_WIDTH ||
      config->scale.second != DEFAULT_HEIGHT) {
    launchCmd += " ! h264parse ! avdec_h264"; // Decode

    launchCmd += time_overlay(config);
    launchCmd += encode(config);
  }
  return launchCmd;
}

// Videosrc input pipeline
std::string create_videotestsrc_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  launchCmd += "videotestsrc ";
  if (config->input.compare(0, 8, "pattern:") == 0) {
    launchCmd += "pattern=";
    launchCmd += config->input.substr(8);
  }

  launchCmd += time_overlay(config);
  launchCmd += encode(config);
  return launchCmd;
}

// File input pipeline
std::string create_file_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  launchCmd += "appsrc name=mysrc";
  launchCmd += " ! decodebin";

  launchCmd += time_overlay(config);
  launchCmd += encode(config);
  return launchCmd;
}

/* Create pipeline according to config */
std::string create_pipeline(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "( ";

  if (config->input_type == RTSP_INPUT) {
    launchCmd += create_rtsp_input(config);
  } else if (config->input_type == VIDEOTESTSRC_INPUT) {
    launchCmd += create_videotestsrc_input(config);
  } else if (config->input_type == FILE_INPUT) {
    launchCmd += create_file_input(config);
  } else if (config->input_type == DEVICE_INPUT) {
    launchCmd += create_device_input(config);
  }

  launchCmd += " ! rtph264pay name=pay0 pt=96 ";
  launchCmd += " )";
  return launchCmd;
}
<commit_msg>add create_device_input function<commit_after>// Copyright 2016 Etix Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "server.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>

// If time overlay is enabled, add it to the pipeline
std::string time_overlay(std::shared_ptr<t_config> &config) {
  if (config->time) {
    return " ! timeoverlay halignment=left valignment=top "
           "shaded-background=true "
           "font-desc=\"Sans 10\" ! "
           "clockoverlay halignment=right valignment=top "
           "shaded-background=true "
           "font-desc=\"Sans 10\"";
  }
  return "";
}

// Take raw, change caps according to conf and transcode in h264
std::string encode(std::shared_ptr<t_config> &config) {
  std::cout << "H264 encoding with:" << std::endl
            << "Framerate:\t" << config->framerate << std::endl
            << "Resolution:\t" << config->scale.first << "x"
            << config->scale.second << std::endl
            << std::endl;

  std::string launchCmd = "";

  // Change caps & encode
  launchCmd += " ! videoscale ! video/x-raw,width=";
  launchCmd += config->scale.first;
  launchCmd += ",height=";
  launchCmd += config->scale.second;
  launchCmd += " ! videorate ! video/x-raw,framerate=";
  launchCmd += config->framerate;
  launchCmd += "/1";
  launchCmd += " ! capsfilter ! queue"
               " ! x264enc speed-preset=superfast "
               "tune=zerolatency";

  return launchCmd;
}

// Rtsp input pipeline
std::string create_rtsp_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  // Receive & depay
  launchCmd += "rtspsrc latency=0 auto-start=true location=";
  launchCmd += config->input;
  launchCmd += " ! rtph264depay";

  // If user request modification in framerate or scale -> encode
  if (config->framerate != DEFAULT_FRAMERATE ||
      config->scale.first != DEFAULT_WIDTH ||
      config->scale.second != DEFAULT_HEIGHT) {
    launchCmd += " ! h264parse ! avdec_h264"; // Decode

    launchCmd += time_overlay(config);
    launchCmd += encode(config);
  }
  return launchCmd;
}

// Videosrc input pipeline
std::string create_videotestsrc_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  launchCmd += "videotestsrc ";
  if (config->input.compare(0, 8, "pattern:") == 0) {
    launchCmd += "pattern=";
    launchCmd += config->input.substr(8);
  }

  launchCmd += time_overlay(config);
  launchCmd += encode(config);
  return launchCmd;
}

// File input pipeline
std::string create_file_input(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "";

  launchCmd += "appsrc name=mysrc";
  launchCmd += " ! decodebin";

  launchCmd += time_overlay(config);
  launchCmd += encode(config);
  return launchCmd;
}

// Device input pipeline
std::string create_device_input(std::shared_ptr<t_config> &config) {
  // std::string launchCmd = "";

  // launchCmd += "appsrc name=mysrc";
  // launchCmd += " ! decodebin";

  // launchCmd += time_overlay(config);
  // launchCmd += encode(config);
  // return launchCmd;
}

/* Create pipeline according to config */
std::string create_pipeline(std::shared_ptr<t_config> &config) {
  std::string launchCmd = "( ";

  if (config->input_type == RTSP_INPUT) {
    launchCmd += create_rtsp_input(config);
  } else if (config->input_type == VIDEOTESTSRC_INPUT) {
    launchCmd += create_videotestsrc_input(config);
  } else if (config->input_type == FILE_INPUT) {
    launchCmd += create_file_input(config);
  } else if (config->input_type == DEVICE_INPUT) {
    launchCmd += create_device_input(config);
  }

  launchCmd += " ! rtph264pay name=pay0 pt=96 ";
  launchCmd += " )";
  return launchCmd;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015-2019 Dubalu LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "chaipp.h"

#if XAPIAND_CHAISCRIPT

#include <functional>                             // for std::hash
#include <string_view>

#include "database/handler.h"                     // for DatabaseHandler
#include "exception.h"                            // for chaipp::Error
#include "log.h"                                  // for L_EXC
#include "lru.h"                                  // for lru::LRU
#include "manager.h"                              // for XapiandManager::*
#include "module.h"                               // for chaipp::Module
#include "msgpack.h"                              // for MsgPack
#include "repr.hh"                                // for repr
#include "url_parser.h"                           // for urldecode

namespace chaipp {

namespace internal {

class ScriptLRU : public lru::LRU<std::string, std::shared_ptr<Processor>> {
public:
	explicit ScriptLRU(ssize_t max_size)
		: LRU(max_size) { }
};

class Engine {
	ScriptLRU script_lru;
	std::mutex mtx;

public:
	explicit Engine(ssize_t max_size);

	std::shared_ptr<Processor> compile(const Script& script);

	static Engine& engine();
};

Engine::Engine(ssize_t max_size) :
	script_lru(max_size)
{
}

std::shared_ptr<Processor>
Engine::compile(const Script& script)
{
	std::string_view script_name;
	std::string_view script_body;

	auto sep_type = script.get_types();

	if (sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
		script_name = script.get_endpoint();
	} else {
		auto name_body = script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
	}

	std::shared_ptr<Processor> processor;

	std::unique_lock<std::mutex> lk(mtx);
	auto it = script_lru.find(std::string(script_name));  // FIXME: This copies script_name as LRU's std::unordered_map cannot find std::string_view
	if (it != script_lru.end()) {
		processor = it->second;
	}
	lk.unlock();

	if (processor) {
		if (script_body.empty()) {
			return processor;
		}
		std::hash<std::string_view> hash_fn;
		if (processor->get_hash() == hash_fn(script_body)) {
			return processor;
		}
	}

	processor = std::make_shared<Processor>(script);

	L_INFO("Script {} ({:x}) compiled and ready.", repr(script_name), processor->get_hash());

	lk.lock();
	return script_lru.emplace(std::string(script_name), processor).first->second;
}

Engine&
Engine::engine() {
	static Engine* engine = new Engine(opts.scripts_cache_size);
	return *engine;
}

}; // End namespace internal

Processor::Processor(const Script& script) :
	chai(Module::library(),
	std::make_unique<chaiscript::parser::ChaiScript_Parser<chaiscript::eval::Noop_Tracer, chaiscript::optimizer::Optimizer_Default>>())
{
	auto sep_type = script.get_types();

	std::string script_name;
	std::string script_body;

	if (sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
		std::string foreign_path, foreign_id;
		auto foreign_uri = script.get_endpoint();
		std::string_view foreign_path_view, foreign_id_view;
		split_path_id(foreign_uri, foreign_path_view, foreign_id_view);
		foreign_path = urldecode(foreign_path_view);
		foreign_id = urldecode(foreign_id_view);
		std::string_view selector;
		auto needle = foreign_id.find_first_of(".{", 1);  // Find first of either '.' (Drill Selector) or '{' (Field selector)
		if (needle != std::string_view::npos) {
			selector = foreign_id.substr(foreign_id[needle] == '.' ? needle + 1 : needle);
			foreign_id = foreign_id.substr(0, needle);
		}
		MsgPack o;
		try {
			Endpoint endpoint{foreign_path};
			auto endpoints = XapiandManager::resolve_index_endpoints(endpoint, true);
			if (endpoints.empty()) {
				THROW(ClientError, "Cannot resolve endpoint: {}", endpoint.to_string());
			}
			DatabaseHandler _db_handler(endpoints, DB_OPEN);
			auto doc = _db_handler.get_document(foreign_id);
			o = doc.get_obj();
		} catch (const Xapian::DocNotFoundError&) {
			THROW(ClientError, "Foreign script {}/{} doesn't exist", foreign_path, foreign_id);
		} catch (const Xapian::DatabaseNotFoundError& exc) {
			THROW(ClientError, "Foreign script database {} doesn't exist", repr(foreign_path));
		}
		if (selector.empty()) {
			// If there's no selector use "script" (to be consistent with "schema" field):
			o = o[SCRIPT_FIELD_NAME];
		} else {
			o = o.select(selector);
		}
		Script foreign_script(o);
		auto foreign_sep_type = foreign_script.get_types();
		if (foreign_sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
			THROW(ClientError, "Nested foreign scripts not supported!");
		}
		auto name_body = foreign_script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
		script_params = foreign_script.get_params();
		script_params.update(script.get_params());
	} else {
		auto name_body = script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
		script_params = script.get_params();
	}

	script_params.lock();

	ast = chai.get_parser().parse(script_body, script_name);
	// L_MAGENTA(ast->to_string());

	std::hash<std::string_view> hash_fn;
	hash = hash_fn(script_body);
}

void
Processor::operator()(std::string_view method, MsgPack& doc, const MsgPack& old_doc, const MsgPack& params)
{
	chai.add(chaiscript::const_var(std::ref(method)), "_method");

	chai.add(chaiscript::var(std::ref(doc)), "_doc");
	chai.add(chaiscript::const_var(std::ref(old_doc)), "_old_doc");

	auto merged_params = script_params;
	merged_params.update(params);
	for (auto it = merged_params.begin(); it != merged_params.end(); ++it) {
		chai.add(chaiscript::const_var(std::ref(it.value())), it->str());
	}

	try {
		chai.eval(*ast);
	} catch (chaiscript::Boxed_Value &bv) {
		try {
			auto exc = chai.boxed_cast<chaiscript::exception::eval_error>(bv);
			L_ERR(exc.pretty_print());
		} catch (const chaiscript::exception::bad_boxed_cast &) {
			try {
				auto exc = chai.boxed_cast<std::exception>(bv);
				L_ERR("Exception: {}", exc.what());
			} catch (const chaiscript::exception::bad_boxed_cast &exc) {
				L_ERR("Exception (bad_boxed_cast): {}", exc.what());
				throw;
			}
		}
	}
}

std::shared_ptr<Processor>
Processor::compile(const Script& script)
{
	return internal::Engine::engine().compile(script);
}

}; // End namespace chaipp

#endif
<commit_msg>Scripts: Resolve non-writable endpoints, for reading<commit_after>/*
 * Copyright (c) 2015-2019 Dubalu LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "chaipp.h"

#if XAPIAND_CHAISCRIPT

#include <functional>                             // for std::hash
#include <string_view>

#include "database/handler.h"                     // for DatabaseHandler
#include "exception.h"                            // for chaipp::Error
#include "log.h"                                  // for L_EXC
#include "lru.h"                                  // for lru::LRU
#include "manager.h"                              // for XapiandManager::*
#include "module.h"                               // for chaipp::Module
#include "msgpack.h"                              // for MsgPack
#include "repr.hh"                                // for repr
#include "url_parser.h"                           // for urldecode

namespace chaipp {

namespace internal {

class ScriptLRU : public lru::LRU<std::string, std::shared_ptr<Processor>> {
public:
	explicit ScriptLRU(ssize_t max_size)
		: LRU(max_size) { }
};

class Engine {
	ScriptLRU script_lru;
	std::mutex mtx;

public:
	explicit Engine(ssize_t max_size);

	std::shared_ptr<Processor> compile(const Script& script);

	static Engine& engine();
};

Engine::Engine(ssize_t max_size) :
	script_lru(max_size)
{
}

std::shared_ptr<Processor>
Engine::compile(const Script& script)
{
	std::string_view script_name;
	std::string_view script_body;

	auto sep_type = script.get_types();

	if (sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
		script_name = script.get_endpoint();
	} else {
		auto name_body = script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
	}

	std::shared_ptr<Processor> processor;

	std::unique_lock<std::mutex> lk(mtx);
	auto it = script_lru.find(std::string(script_name));  // FIXME: This copies script_name as LRU's std::unordered_map cannot find std::string_view
	if (it != script_lru.end()) {
		processor = it->second;
	}
	lk.unlock();

	if (processor) {
		if (script_body.empty()) {
			return processor;
		}
		std::hash<std::string_view> hash_fn;
		if (processor->get_hash() == hash_fn(script_body)) {
			return processor;
		}
	}

	processor = std::make_shared<Processor>(script);

	L_INFO("Script {} ({:x}) compiled and ready.", repr(script_name), processor->get_hash());

	lk.lock();
	return script_lru.emplace(std::string(script_name), processor).first->second;
}

Engine&
Engine::engine() {
	static Engine* engine = new Engine(opts.scripts_cache_size);
	return *engine;
}

}; // End namespace internal

Processor::Processor(const Script& script) :
	chai(Module::library(),
	std::make_unique<chaiscript::parser::ChaiScript_Parser<chaiscript::eval::Noop_Tracer, chaiscript::optimizer::Optimizer_Default>>())
{
	auto sep_type = script.get_types();

	std::string script_name;
	std::string script_body;

	if (sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
		std::string foreign_path, foreign_id;
		auto foreign_uri = script.get_endpoint();
		std::string_view foreign_path_view, foreign_id_view;
		split_path_id(foreign_uri, foreign_path_view, foreign_id_view);
		foreign_path = urldecode(foreign_path_view);
		foreign_id = urldecode(foreign_id_view);
		std::string_view selector;
		auto needle = foreign_id.find_first_of(".{", 1);  // Find first of either '.' (Drill Selector) or '{' (Field selector)
		if (needle != std::string_view::npos) {
			selector = foreign_id.substr(foreign_id[needle] == '.' ? needle + 1 : needle);
			foreign_id = foreign_id.substr(0, needle);
		}
		MsgPack o;
		try {
			Endpoint endpoint{foreign_path};
			auto endpoints = XapiandManager::resolve_index_endpoints(endpoint);
			if (endpoints.empty()) {
				THROW(ClientError, "Cannot resolve endpoint: {}", endpoint.to_string());
			}
			DatabaseHandler _db_handler(endpoints, DB_OPEN);
			auto doc = _db_handler.get_document(foreign_id);
			o = doc.get_obj();
		} catch (const Xapian::DocNotFoundError&) {
			THROW(ClientError, "Foreign script {}/{} doesn't exist", foreign_path, foreign_id);
		} catch (const Xapian::DatabaseNotFoundError& exc) {
			THROW(ClientError, "Foreign script database {} doesn't exist", repr(foreign_path));
		}
		if (selector.empty()) {
			// If there's no selector use "script" (to be consistent with "schema" field):
			o = o[SCRIPT_FIELD_NAME];
		} else {
			o = o.select(selector);
		}
		Script foreign_script(o);
		auto foreign_sep_type = foreign_script.get_types();
		if (foreign_sep_type[SPC_FOREIGN_TYPE] == FieldType::foreign) {
			THROW(ClientError, "Nested foreign scripts not supported!");
		}
		auto name_body = foreign_script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
		script_params = foreign_script.get_params();
		script_params.update(script.get_params());
	} else {
		auto name_body = script.get_name_body();
		script_name = name_body.first;
		script_body = name_body.second;
		script_params = script.get_params();
	}

	script_params.lock();

	ast = chai.get_parser().parse(script_body, script_name);
	// L_MAGENTA(ast->to_string());

	std::hash<std::string_view> hash_fn;
	hash = hash_fn(script_body);
}

void
Processor::operator()(std::string_view method, MsgPack& doc, const MsgPack& old_doc, const MsgPack& params)
{
	chai.add(chaiscript::const_var(std::ref(method)), "_method");

	chai.add(chaiscript::var(std::ref(doc)), "_doc");
	chai.add(chaiscript::const_var(std::ref(old_doc)), "_old_doc");

	auto merged_params = script_params;
	merged_params.update(params);
	for (auto it = merged_params.begin(); it != merged_params.end(); ++it) {
		chai.add(chaiscript::const_var(std::ref(it.value())), it->str());
	}

	try {
		chai.eval(*ast);
	} catch (chaiscript::Boxed_Value &bv) {
		try {
			auto exc = chai.boxed_cast<chaiscript::exception::eval_error>(bv);
			L_ERR(exc.pretty_print());
		} catch (const chaiscript::exception::bad_boxed_cast &) {
			try {
				auto exc = chai.boxed_cast<std::exception>(bv);
				L_ERR("Exception: {}", exc.what());
			} catch (const chaiscript::exception::bad_boxed_cast &exc) {
				L_ERR("Exception (bad_boxed_cast): {}", exc.what());
				throw;
			}
		}
	}
}

std::shared_ptr<Processor>
Processor::compile(const Script& script)
{
	return internal::Engine::engine().compile(script);
}

}; // End namespace chaipp

#endif
<|endoftext|>


<commit_before>// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2009, 2010, 2011 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

//
// This file was derived from a random program generator written by Bryan
// Turner.  The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//

// ---------------------------------------
// Platform-Specific code to get a unique seed value (usually from the tick counter, etc)
//
#include <sys/types.h>
#include <sys/timeb.h>

#include "platform.h"

#if (TARGET_CPU_powerpc == 1 || TARGET_CPU_powerpc64 == 1)
/*For PPC, got from:
http://lists.ozlabs.org/pipermail/linuxppc-dev/1999-October/003889.html
*/
static unsigned long long read_time(void) {
	unsigned long long retval;
	unsigned long junk;
	__asm__ __volatile__ ("\n\
1:	mftbu %1\n\
	mftb %L0\n\
	mftbu %0\n\
	cmpw %0,%1\n\
	bne 1b"
	: "=r" (retval), "=r" (junk));
	return retval;
}
#else
#ifdef WIN32
static unsigned __int64 read_time(void) {
        unsigned l, h;
        _asm {rdtsc
        mov l, eax
        mov h, edx
        }
        return (h << 32) + l ;
}
#else
static long long read_time(void) {
        long long l;
        asm volatile(   "rdtsc\n\t"
                : "=A" (l)
        );
        return l;
}
#endif
#endif

unsigned long platform_gen_seed()
{
	return (long) read_time();
}

//////////// platform specific mkdir /////////////////
#ifndef WIN32
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#else
#include <direct.h>
#include <cerrno>
#endif

bool create_dir(const char *dir)
{
#ifndef WIN32
	if (mkdir(dir, 0770) == -1) {
#else
	if (mkdir(dir) == -1) {
#endif
		return (errno == EEXIST) ? true : false;
	}
	return true;
}

///////////////////////////////////////////////////////////////////////////////

// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:

// End of file.
<commit_msg>Fix PowerPC read_time()<commit_after>// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2009, 2010, 2011 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

//
// This file was derived from a random program generator written by Bryan
// Turner.  The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//

// ---------------------------------------
// Platform-Specific code to get a unique seed value (usually from the tick counter, etc)
//
#include <sys/types.h>
#include <sys/timeb.h>

#include "platform.h"

#if (TARGET_CPU_powerpc == 1 || TARGET_CPU_powerpc64 == 1)
static inline unsigned long read_time(void)
{
	unsigned long a;

	asm volatile("mftb %0" : "=r" (a));

	return a;
}
#else
#ifdef WIN32
static unsigned __int64 read_time(void) {
        unsigned l, h;
        _asm {rdtsc
        mov l, eax
        mov h, edx
        }
        return (h << 32) + l ;
}
#else
static long long read_time(void) {
        long long l;
        asm volatile(   "rdtsc\n\t"
                : "=A" (l)
        );
        return l;
}
#endif
#endif

unsigned long platform_gen_seed()
{
	return (long) read_time();
}

//////////// platform specific mkdir /////////////////
#ifndef WIN32
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#else
#include <direct.h>
#include <cerrno>
#endif

bool create_dir(const char *dir)
{
#ifndef WIN32
	if (mkdir(dir, 0770) == -1) {
#else
	if (mkdir(dir) == -1) {
#endif
		return (errno == EEXIST) ? true : false;
	}
	return true;
}

///////////////////////////////////////////////////////////////////////////////

// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:

// End of file.
<|endoftext|>


<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**   * Neither the name of the chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "bond.h"

#include "atom.h"
#include "ring.h"
#include "foreach.h"
#include "geometry.h"
#include "molecule.h"
#include "moleculeprivate.h"

namespace chemkit {

// === Bond ================================================================ //
/// \class Bond bond.h chemkit/bond.h
/// \ingroup chemkit
/// \brief The Bond class represents a bond between two atoms in a
///        molecule.
///
/// Bond objects are created with the Molecule::addBond() method and
/// destroyed with the Molecule::removeBond() method.

/// \enum Bond::BondType
/// Provides names for the different bond orders:
///     - \c Single = \c 1
///     - \c Double = \c 2
///     - \c Triple = \c 3
///     - \c Quadruple = \c 4

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new bond object for \p molecule at \p index.
Bond::Bond(Molecule *molecule, int index)
    : m_molecule(molecule),
      m_index(index)
{
}

/// Destroys the bond object.
Bond::~Bond()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the atom at \p index in the bond. Index must be either
/// \c 0 or \c 1.
Atom* Bond::atom(int index) const
{
    return index == 0 ? atom1() : atom2();
}

/// Returns the first atom in the bond.
Atom* Bond::atom1() const
{
    return m_molecule->d->bondAtoms[m_index].first;
}

/// Returns the second atom in the bond.
Atom* Bond::atom2() const
{
    return m_molecule->d->bondAtoms[m_index].second;
}

/// Returns a list containing both atoms in the bond.
std::vector<Atom *> Bond::atoms() const
{
    std::vector<Atom *> atoms(2);
    atoms[0] = atom1();
    atoms[1] = atom2();
    return atoms;
}

/// Returns the other atom in the bond. The given atom must be a
/// part of the bond.
Atom* Bond::otherAtom(const Atom *atom) const
{
    const std::pair<Atom *, Atom *> &pair = m_molecule->d->bondAtoms[m_index];

    return atom == pair.first ? pair.second : pair.first;
}

/// Sets the bond order for the bond to \p order.
void Bond::setOrder(int order)
{
    m_molecule->d->bondOrders[m_index] = order;

    molecule()->notifyWatchers(this, Molecule::BondOrderChanged);
}

/// Returns the bond order.
int Bond::order() const
{
    return m_molecule->d->bondOrders[m_index];
}

/// Returns the polarity of the bond. This is calculated as the
/// absolute value of the difference in electronegativity between the
/// two atoms in the bond.
Real Bond::polarity() const
{
    if(atom1()->atomicNumber() == atom2()->atomicNumber()){
        return 0;
    }

    return std::abs(atom1()->electronegativity() - atom2()->electronegativity());
}

/// Returns the dipole moment for the bond.
Vector3 Bond::dipoleMoment() const
{
    Point3 a = atom1()->position();
    Point3 b = atom2()->position();
    Real qa = atom1()->partialCharge();
    Real qb = atom2()->partialCharge();

    return (a - b) * (qa - qb);
}

/// Returns the fragment the bond is a part of.
Fragment* Bond::fragment() const
{
    return atom1()->fragment();
}

// --- Structure ----------------------------------------------------------- //
/// Returns \c true if the bond contains atom.
bool Bond::contains(const Atom *atom) const
{
    return atom1() == atom || atom2() == atom;
}

/// Returns \c true if the bond contains an atom of the given
/// \p element.
bool Bond::contains(const Element &element) const
{
    return atom1()->is(element) || atom2()->is(element);
}

/// Returns \c true if the bond contains both atom \p a and atom
/// \p b.
bool Bond::containsBoth(const Atom *a, const Atom *b) const
{
    return contains(a) && contains(b);
}

/// Returns \c true if the bond contains an atom of the element \p a
/// and an atom of the element \p b.
///
/// For example, to check if this is a carbonyl bond you could use:
/// \code
/// if(bond->containsBoth(Atom::Carbon, Atom::Oxygen) && bond->order() == Bond::Double){
///     // it is a carbonyl
/// }
/// \endcode
bool Bond::containsBoth(const Element &a, const Element &b) const
{
    return (atom1()->is(a) && atom2()->is(b)) || (atom2()->is(a) && atom1()->is(b));
}

/// Returns \c true if either of the two atoms in the bond are
/// terminal.
bool Bond::isTerminal() const
{
    return (atom1()->isTerminal() || atom2()->isTerminal());
}

// --- Ring Perception ----------------------------------------------------- //
/// Returns a list of rings the bond is a member of.
std::vector<Ring *> Bond::rings() const
{
    std::vector<Ring *> rings;

    foreach(Ring *ring, molecule()->rings()){
        if(ring->contains(this)){
            rings.push_back(ring);
        }
    }

    return rings;
}

/// Returns the number of rings the bond is a member of.
int Bond::ringCount() const
{
    return rings().size();
}

/// Returns \c true if the bond is a member of at least one ring.
/// (i.e. ringCount() >= 1).
bool Bond::isInRing() const
{
    foreach(const Ring *ring, molecule()->rings()){
        if(ring->contains(this)){
            return true;
        }
    }

    return false;
}

/// Returns \c true if the bond is in a ring of given size.
bool Bond::isInRing(int size) const
{
    foreach(const Ring *ring, molecule()->rings()){
        if(ring->size() == size && ring->contains(this)){
            return true;
        }
    }

    return false;
}

/// Returns the smallest ring the bond is a member of or \c 0 if the
/// bond is not in a ring.
Ring* Bond::smallestRing() const
{
    Ring *smallest = 0;

    foreach(Ring *ring, rings()){
        if(!smallest || ring->size() < smallest->size()){
            smallest = ring;
        }
    }

    return smallest;
}

/// Returns \c true if the bond is in an aromatic ring.
///
/// \see Ring::isAromatic()
bool Bond::isAromatic() const
{
    foreach(const Ring *ring, rings()){
        if(ring->isAromatic()){
            return true;
        }
    }

    return false;
}

// --- Geometry ------------------------------------------------------------ //
/// Returns the center point of the bond. The center is equal to the
/// midpoint between the two atoms in the bond.
Point3 Bond::center() const
{
    return chemkit::geometry::midpoint(atom1()->position(),
                                       atom2()->position());
}

/// Returns the length of the bond. Length is in Angstroms.
Real Bond::length() const
{
    return atom1()->distance(atom2());
}

} // end chemkit namespace
<commit_msg>Remove unneeded parentheses in Bond::isTerminal()<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**   * Neither the name of the chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "bond.h"

#include "atom.h"
#include "ring.h"
#include "foreach.h"
#include "geometry.h"
#include "molecule.h"
#include "moleculeprivate.h"

namespace chemkit {

// === Bond ================================================================ //
/// \class Bond bond.h chemkit/bond.h
/// \ingroup chemkit
/// \brief The Bond class represents a bond between two atoms in a
///        molecule.
///
/// Bond objects are created with the Molecule::addBond() method and
/// destroyed with the Molecule::removeBond() method.

/// \enum Bond::BondType
/// Provides names for the different bond orders:
///     - \c Single = \c 1
///     - \c Double = \c 2
///     - \c Triple = \c 3
///     - \c Quadruple = \c 4

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new bond object for \p molecule at \p index.
Bond::Bond(Molecule *molecule, int index)
    : m_molecule(molecule),
      m_index(index)
{
}

/// Destroys the bond object.
Bond::~Bond()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the atom at \p index in the bond. Index must be either
/// \c 0 or \c 1.
Atom* Bond::atom(int index) const
{
    return index == 0 ? atom1() : atom2();
}

/// Returns the first atom in the bond.
Atom* Bond::atom1() const
{
    return m_molecule->d->bondAtoms[m_index].first;
}

/// Returns the second atom in the bond.
Atom* Bond::atom2() const
{
    return m_molecule->d->bondAtoms[m_index].second;
}

/// Returns a list containing both atoms in the bond.
std::vector<Atom *> Bond::atoms() const
{
    std::vector<Atom *> atoms(2);
    atoms[0] = atom1();
    atoms[1] = atom2();
    return atoms;
}

/// Returns the other atom in the bond. The given atom must be a
/// part of the bond.
Atom* Bond::otherAtom(const Atom *atom) const
{
    const std::pair<Atom *, Atom *> &pair = m_molecule->d->bondAtoms[m_index];

    return atom == pair.first ? pair.second : pair.first;
}

/// Sets the bond order for the bond to \p order.
void Bond::setOrder(int order)
{
    m_molecule->d->bondOrders[m_index] = order;

    molecule()->notifyWatchers(this, Molecule::BondOrderChanged);
}

/// Returns the bond order.
int Bond::order() const
{
    return m_molecule->d->bondOrders[m_index];
}

/// Returns the polarity of the bond. This is calculated as the
/// absolute value of the difference in electronegativity between the
/// two atoms in the bond.
Real Bond::polarity() const
{
    if(atom1()->atomicNumber() == atom2()->atomicNumber()){
        return 0;
    }

    return std::abs(atom1()->electronegativity() - atom2()->electronegativity());
}

/// Returns the dipole moment for the bond.
Vector3 Bond::dipoleMoment() const
{
    Point3 a = atom1()->position();
    Point3 b = atom2()->position();
    Real qa = atom1()->partialCharge();
    Real qb = atom2()->partialCharge();

    return (a - b) * (qa - qb);
}

/// Returns the fragment the bond is a part of.
Fragment* Bond::fragment() const
{
    return atom1()->fragment();
}

// --- Structure ----------------------------------------------------------- //
/// Returns \c true if the bond contains atom.
bool Bond::contains(const Atom *atom) const
{
    return atom1() == atom || atom2() == atom;
}

/// Returns \c true if the bond contains an atom of the given
/// \p element.
bool Bond::contains(const Element &element) const
{
    return atom1()->is(element) || atom2()->is(element);
}

/// Returns \c true if the bond contains both atom \p a and atom
/// \p b.
bool Bond::containsBoth(const Atom *a, const Atom *b) const
{
    return contains(a) && contains(b);
}

/// Returns \c true if the bond contains an atom of the element \p a
/// and an atom of the element \p b.
///
/// For example, to check if this is a carbonyl bond you could use:
/// \code
/// if(bond->containsBoth(Atom::Carbon, Atom::Oxygen) && bond->order() == Bond::Double){
///     // it is a carbonyl
/// }
/// \endcode
bool Bond::containsBoth(const Element &a, const Element &b) const
{
    return (atom1()->is(a) && atom2()->is(b)) || (atom2()->is(a) && atom1()->is(b));
}

/// Returns \c true if either of the two atoms in the bond are
/// terminal.
bool Bond::isTerminal() const
{
    return atom1()->isTerminal() || atom2()->isTerminal();
}

// --- Ring Perception ----------------------------------------------------- //
/// Returns a list of rings the bond is a member of.
std::vector<Ring *> Bond::rings() const
{
    std::vector<Ring *> rings;

    foreach(Ring *ring, molecule()->rings()){
        if(ring->contains(this)){
            rings.push_back(ring);
        }
    }

    return rings;
}

/// Returns the number of rings the bond is a member of.
int Bond::ringCount() const
{
    return rings().size();
}

/// Returns \c true if the bond is a member of at least one ring.
/// (i.e. ringCount() >= 1).
bool Bond::isInRing() const
{
    foreach(const Ring *ring, molecule()->rings()){
        if(ring->contains(this)){
            return true;
        }
    }

    return false;
}

/// Returns \c true if the bond is in a ring of given size.
bool Bond::isInRing(int size) const
{
    foreach(const Ring *ring, molecule()->rings()){
        if(ring->size() == size && ring->contains(this)){
            return true;
        }
    }

    return false;
}

/// Returns the smallest ring the bond is a member of or \c 0 if the
/// bond is not in a ring.
Ring* Bond::smallestRing() const
{
    Ring *smallest = 0;

    foreach(Ring *ring, rings()){
        if(!smallest || ring->size() < smallest->size()){
            smallest = ring;
        }
    }

    return smallest;
}

/// Returns \c true if the bond is in an aromatic ring.
///
/// \see Ring::isAromatic()
bool Bond::isAromatic() const
{
    foreach(const Ring *ring, rings()){
        if(ring->isAromatic()){
            return true;
        }
    }

    return false;
}

// --- Geometry ------------------------------------------------------------ //
/// Returns the center point of the bond. The center is equal to the
/// midpoint between the two atoms in the bond.
Point3 Bond::center() const
{
    return chemkit::geometry::midpoint(atom1()->position(),
                                       atom2()->position());
}

/// Returns the length of the bond. Length is in Angstroms.
Real Bond::length() const
{
    return atom1()->distance(atom2());
}

} // end chemkit namespace
<|endoftext|>