<commit_before>/*************************************************************************/
/*  lightmap_raycaster.cpp                                               */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "lightmap_raycaster.h"

// From Embree.
#include <math/vec2.h>
#include <math/vec3.h>

using namespace embree;

LightmapRaycaster *LightmapRaycasterEmbree::create_embree_raycaster() {
	return memnew(LightmapRaycasterEmbree);
}

void LightmapRaycasterEmbree::make_default_raycaster() {
	create_function = create_embree_raycaster;
}

void LightmapRaycasterEmbree::filter_function(const struct RTCFilterFunctionNArguments *p_args) {

	RTCHit *hit = (RTCHit *)p_args->hit;

	unsigned int geomID = hit->geomID;
	float u = hit->u;
	float v = hit->v;

	LightmapRaycasterEmbree *scene = (LightmapRaycasterEmbree *)p_args->geometryUserPtr;
	RTCGeometry geom = rtcGetGeometry(scene->embree_scene, geomID);

	rtcInterpolate0(geom, hit->primID, hit->u, hit->v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, &hit->u, 2);

	if (scene->alpha_textures.has(geomID)) {
		const AlphaTextureData &alpha_texture = scene->alpha_textures[geomID];

		if (alpha_texture.sample(hit->u, hit->v) < 128) {
			p_args->valid[0] = 0;
			return;
		}
	}

	rtcInterpolate0(geom, hit->primID, u, v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, &hit->Ng_x, 3);
}

bool LightmapRaycasterEmbree::intersect(Ray &r_ray) {
	RTCIntersectContext context;

	rtcInitIntersectContext(&context);

	rtcIntersect1(embree_scene, &context, (RTCRayHit *)&r_ray);
	return r_ray.geomID != RTC_INVALID_GEOMETRY_ID;
}

void LightmapRaycasterEmbree::intersect(Vector<Ray> &r_rays) {
	Ray *rays = r_rays.ptrw();
	for (int i = 0; i < r_rays.size(); ++i) {
		intersect(rays[i]);
	}
}

void LightmapRaycasterEmbree::set_mesh_alpha_texture(Ref<Image> p_alpha_texture, unsigned int p_id) {
	if (p_alpha_texture.is_valid() && p_alpha_texture->get_size() != Vector2i()) {
		AlphaTextureData tex;
		tex.size = p_alpha_texture->get_size();
		tex.data.resize(tex.size.x * tex.size.y);

		{
			PoolVector<uint8_t>::Read r = p_alpha_texture->get_data().read();
			uint8_t *ptrw = tex.data.ptrw();
			for (int i = 0; i < tex.size.x * tex.size.y; ++i) {
				ptrw[i] = r[i];
			}
		}

		alpha_textures.insert(p_id, tex);
	}
}

float blerp(float c00, float c10, float c01, float c11, float tx, float ty) {
	return Math::lerp(Math::lerp(c00, c10, tx), Math::lerp(c01, c11, tx), ty);
}

uint8_t LightmapRaycasterEmbree::AlphaTextureData::sample(float u, float v) const {
	float x = u * size.x;
	float y = v * size.y;
	int xi = (int)x;
	int yi = (int)y;

	uint8_t texels[4];

	for (int i = 0; i < 4; ++i) {
		int sample_x = CLAMP(xi + i % 2, 0, size.x - 1);
		int sample_y = CLAMP(yi + i / 2, 0, size.y - 1);
		texels[i] = data[sample_y * size.x + sample_x];
	}

	return Math::round(blerp(texels[0], texels[1], texels[2], texels[3], x - xi, y - yi));
}

void LightmapRaycasterEmbree::add_mesh(const Vector<Vector3> &p_vertices, const Vector<Vector3> &p_normals, const Vector<Vector2> &p_uv2s, unsigned int p_id) {

	RTCGeometry embree_mesh = rtcNewGeometry(embree_device, RTC_GEOMETRY_TYPE_TRIANGLE);

	rtcSetGeometryVertexAttributeCount(embree_mesh, 2);

	int vertex_count = p_vertices.size();

	ERR_FAIL_COND(vertex_count % 3 != 0);
	ERR_FAIL_COND(vertex_count != p_uv2s.size());

	Vec3fa *embree_vertices = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count);
	Vec2fa *embree_light_uvs = (Vec2fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vec2fa), vertex_count);
	uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3);

	Vec3fa *embree_normals = nullptr;
	if (!p_normals.empty()) {
		embree_normals = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count);
	}

	for (uint32_t i = 0; i < vertex_count; i++) {
		embree_vertices[i] = Vec3fa(p_vertices[i].x, p_vertices[i].y, p_vertices[i].z);
		embree_light_uvs[i] = Vec2fa(p_uv2s[i].x, p_uv2s[i].y);
		if (embree_normals != nullptr) {
			embree_normals[i] = Vec3fa(p_normals[i].x, p_normals[i].y, p_normals[i].z);
		}
		embree_triangles[i] = i;
	}

	rtcCommitGeometry(embree_mesh);
	rtcSetGeometryIntersectFilterFunction(embree_mesh, filter_function);
	rtcSetGeometryUserData(embree_mesh, this);
	rtcAttachGeometryByID(embree_scene, embree_mesh, p_id);
	rtcReleaseGeometry(embree_mesh);
}

void LightmapRaycasterEmbree::commit() {
	rtcCommitScene(embree_scene);
}

void LightmapRaycasterEmbree::set_mesh_filter(const Set<int> &p_mesh_ids) {
	for (Set<int>::Element *E = p_mesh_ids.front(); E; E = E->next()) {
		rtcDisableGeometry(rtcGetGeometry(embree_scene, E->get()));
	}
	rtcCommitScene(embree_scene);
	filter_meshes = p_mesh_ids;
}

void LightmapRaycasterEmbree::clear_mesh_filter() {
	for (Set<int>::Element *E = filter_meshes.front(); E; E = E->next()) {
		rtcEnableGeometry(rtcGetGeometry(embree_scene, E->get()));
	}
	rtcCommitScene(embree_scene);
	filter_meshes.clear();
}

void embree_error_handler(void *p_user_data, RTCError p_code, const char *p_str) {
	print_error("Embree error: " + String(p_str));
}

LightmapRaycasterEmbree::LightmapRaycasterEmbree() {
	embree_device = rtcNewDevice(nullptr);
	rtcSetDeviceErrorFunction(embree_device, &embree_error_handler, nullptr);
	embree_scene = rtcNewScene(embree_device);
}

LightmapRaycasterEmbree::~LightmapRaycasterEmbree() {
	if (embree_scene != nullptr)
		rtcReleaseScene(embree_scene);
	if (embree_device != nullptr)
		rtcReleaseDevice(embree_device);
}
<commit_msg>Fix sign comparison error in lightmap_raycaster.cpp<commit_after>/*************************************************************************/
/*  lightmap_raycaster.cpp                                               */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "lightmap_raycaster.h"

// From Embree.
#include <math/vec2.h>
#include <math/vec3.h>

using namespace embree;

LightmapRaycaster *LightmapRaycasterEmbree::create_embree_raycaster() {
	return memnew(LightmapRaycasterEmbree);
}

void LightmapRaycasterEmbree::make_default_raycaster() {
	create_function = create_embree_raycaster;
}

void LightmapRaycasterEmbree::filter_function(const struct RTCFilterFunctionNArguments *p_args) {

	RTCHit *hit = (RTCHit *)p_args->hit;

	unsigned int geomID = hit->geomID;
	float u = hit->u;
	float v = hit->v;

	LightmapRaycasterEmbree *scene = (LightmapRaycasterEmbree *)p_args->geometryUserPtr;
	RTCGeometry geom = rtcGetGeometry(scene->embree_scene, geomID);

	rtcInterpolate0(geom, hit->primID, hit->u, hit->v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, &hit->u, 2);

	if (scene->alpha_textures.has(geomID)) {
		const AlphaTextureData &alpha_texture = scene->alpha_textures[geomID];

		if (alpha_texture.sample(hit->u, hit->v) < 128) {
			p_args->valid[0] = 0;
			return;
		}
	}

	rtcInterpolate0(geom, hit->primID, u, v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, &hit->Ng_x, 3);
}

bool LightmapRaycasterEmbree::intersect(Ray &r_ray) {
	RTCIntersectContext context;

	rtcInitIntersectContext(&context);

	rtcIntersect1(embree_scene, &context, (RTCRayHit *)&r_ray);
	return r_ray.geomID != RTC_INVALID_GEOMETRY_ID;
}

void LightmapRaycasterEmbree::intersect(Vector<Ray> &r_rays) {
	Ray *rays = r_rays.ptrw();
	for (int i = 0; i < r_rays.size(); ++i) {
		intersect(rays[i]);
	}
}

void LightmapRaycasterEmbree::set_mesh_alpha_texture(Ref<Image> p_alpha_texture, unsigned int p_id) {
	if (p_alpha_texture.is_valid() && p_alpha_texture->get_size() != Vector2i()) {
		AlphaTextureData tex;
		tex.size = p_alpha_texture->get_size();
		tex.data.resize(tex.size.x * tex.size.y);

		{
			PoolVector<uint8_t>::Read r = p_alpha_texture->get_data().read();
			uint8_t *ptrw = tex.data.ptrw();
			for (int i = 0; i < tex.size.x * tex.size.y; ++i) {
				ptrw[i] = r[i];
			}
		}

		alpha_textures.insert(p_id, tex);
	}
}

float blerp(float c00, float c10, float c01, float c11, float tx, float ty) {
	return Math::lerp(Math::lerp(c00, c10, tx), Math::lerp(c01, c11, tx), ty);
}

uint8_t LightmapRaycasterEmbree::AlphaTextureData::sample(float u, float v) const {
	float x = u * size.x;
	float y = v * size.y;
	int xi = (int)x;
	int yi = (int)y;

	uint8_t texels[4];

	for (int i = 0; i < 4; ++i) {
		int sample_x = CLAMP(xi + i % 2, 0, size.x - 1);
		int sample_y = CLAMP(yi + i / 2, 0, size.y - 1);
		texels[i] = data[sample_y * size.x + sample_x];
	}

	return Math::round(blerp(texels[0], texels[1], texels[2], texels[3], x - xi, y - yi));
}

void LightmapRaycasterEmbree::add_mesh(const Vector<Vector3> &p_vertices, const Vector<Vector3> &p_normals, const Vector<Vector2> &p_uv2s, unsigned int p_id) {

	RTCGeometry embree_mesh = rtcNewGeometry(embree_device, RTC_GEOMETRY_TYPE_TRIANGLE);

	rtcSetGeometryVertexAttributeCount(embree_mesh, 2);

	int vertex_count = p_vertices.size();

	ERR_FAIL_COND(vertex_count % 3 != 0);
	ERR_FAIL_COND(vertex_count != p_uv2s.size());

	Vec3fa *embree_vertices = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count);
	Vec2fa *embree_light_uvs = (Vec2fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vec2fa), vertex_count);
	uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3);

	Vec3fa *embree_normals = nullptr;
	if (!p_normals.empty()) {
		embree_normals = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count);
	}

	for (int i = 0; i < vertex_count; i++) {
		embree_vertices[i] = Vec3fa(p_vertices[i].x, p_vertices[i].y, p_vertices[i].z);
		embree_light_uvs[i] = Vec2fa(p_uv2s[i].x, p_uv2s[i].y);
		if (embree_normals != nullptr) {
			embree_normals[i] = Vec3fa(p_normals[i].x, p_normals[i].y, p_normals[i].z);
		}
		embree_triangles[i] = i;
	}

	rtcCommitGeometry(embree_mesh);
	rtcSetGeometryIntersectFilterFunction(embree_mesh, filter_function);
	rtcSetGeometryUserData(embree_mesh, this);
	rtcAttachGeometryByID(embree_scene, embree_mesh, p_id);
	rtcReleaseGeometry(embree_mesh);
}

void LightmapRaycasterEmbree::commit() {
	rtcCommitScene(embree_scene);
}

void LightmapRaycasterEmbree::set_mesh_filter(const Set<int> &p_mesh_ids) {
	for (Set<int>::Element *E = p_mesh_ids.front(); E; E = E->next()) {
		rtcDisableGeometry(rtcGetGeometry(embree_scene, E->get()));
	}
	rtcCommitScene(embree_scene);
	filter_meshes = p_mesh_ids;
}

void LightmapRaycasterEmbree::clear_mesh_filter() {
	for (Set<int>::Element *E = filter_meshes.front(); E; E = E->next()) {
		rtcEnableGeometry(rtcGetGeometry(embree_scene, E->get()));
	}
	rtcCommitScene(embree_scene);
	filter_meshes.clear();
}

void embree_error_handler(void *p_user_data, RTCError p_code, const char *p_str) {
	print_error("Embree error: " + String(p_str));
}

LightmapRaycasterEmbree::LightmapRaycasterEmbree() {
	embree_device = rtcNewDevice(nullptr);
	rtcSetDeviceErrorFunction(embree_device, &embree_error_handler, nullptr);
	embree_scene = rtcNewScene(embree_device);
}

LightmapRaycasterEmbree::~LightmapRaycasterEmbree() {
	if (embree_scene != nullptr)
		rtcReleaseScene(embree_scene);
	if (embree_device != nullptr)
		rtcReleaseDevice(embree_device);
}
<|endoftext|>


<commit_before>#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/foreach.hpp>
#include "CurlHelpers.h"
#include "MHEMobileNotify.h"

MHEMobileNotify::MHEMobileNotify(std::string gcmAppId, MHEDatabase *db, SpeechRecognize *sr) : _gcmAppId(gcmAppId), _db(db), _sr(sr)
{
    _log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("MHEMobileNotify"));
}

MHEMobileNotify::~MHEMobileNotify()
{
}

void MHEMobileNotify::notifyDevices(const std::string &event, const std::string &type, const std::string &msg)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify(event, -1);

    if (devices.size() > 0)
        notifyDevices(devices, type, msg);
}

void MHEMobileNotify::notifyDevices(MHEMobileNotifyType type, DBCondition &condition)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify("condition", condition.id);

    if (devices.size() > 0)
    {
        std::string typeStr = (type == conditionEnter ? "conditionEnter" : "conditionLeave");
        std::string msg;

        if (_sr != NULL)
        {
            std::stringstream ssMsg1, ssMsg2;

            ssMsg1 << "condition_" << typeStr << "_" << condition.id;
            ssMsg2 << "condition_" << typeStr;
            msg = _sr->getResponse(ssMsg1.str(), ssMsg2.str());
        }
        else
            msg = typeStr;
        notifyDevices(devices, typeStr, msg);
    }
}

void MHEMobileNotify::notifyDevices(MHEMobileNotifyType type, MHEDevice &device)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify("device", device.getId());

    if (devices.size() > 0)
    {
        std::string typeStr = (type == conditionEnter ? "deviceActivated" : "deviceDesactivated");
        std::string msg;

        if (_sr != NULL)
        {
            std::stringstream ssMsg1, ssMsg2;

            ssMsg1 << "device_" << typeStr << "_" << device.getId();
            ssMsg2 << "device_" << typeStr;
            msg = _sr->getResponse(ssMsg1.str(), ssMsg2.str());
        }
        else
            msg = typeStr;
        notifyDevices(devices, typeStr, msg);
    }
}

void MHEMobileNotify::notifyDevices(std::vector<DBMobile> &devices, const std::string &type, const std::string &msg)
{
    LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notifyDevices - devices[]=" << devices.size() << " type=" << type << " msg=" << msg));
    BOOST_FOREACH(DBMobile &device, devices)
    {
        notifyDevice(device, type, msg);
    }
}

void MHEMobileNotify::notifyDevice(DBMobile &device, const std::string &type, const std::string &msg)
{
    LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notityDevice - device=" << (std::string)device << " type=" << type << " msg=" << msg));
    if (device.type == "gcm")
    {
        std::vector<std::string> headers;
        std::stringstream ss, ssOut;
        std::string postData;
        std::string url = "https://android.googleapis.com/gcm/send";

        ss << "Authorization: key=" << _gcmAppId;
        headers.push_back(ss.str());
        headers.push_back("Content-Type: application/json");
        ss.str(std::string());
        ss << "{"
                << "to: \"" << device.token << "\","
                << "data: {"
                    << "type: \"" << type << "\","
                    << "msg: \"" << msg << "\""
                << "}"
            << "}";
        postData = ss.str();
        if (curlExecute(url, &headers, &postData, &ssOut))
        {
            boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
            boost::gregorian::date currentDate = now.date();
            long dateYYYYMMDD = (long)currentDate.year() * 10000L + (long)currentDate.month() * 100L + (long)currentDate.day();
            long currentHHMMM = now.time_of_day().hours() * 100L + now.time_of_day().minutes();

            LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notityDevice - success post=" << ss.str() << " return: " << ssOut));
            device.lastSuccessYYYYMMDDHHSS = dateYYYYMMDD * 10000L + currentHHMMM;
            _db->updateMobileLastSuccess(device);
        }
        else
            LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("notityDevice - failed post=" << ss.str()));
    }
    else
        LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("notityDevice - unkown type of device - " << (std::string)device));
}
<commit_msg>Improve text notification.<commit_after>#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/foreach.hpp>
#include "CurlHelpers.h"
#include "MHEMobileNotify.h"

MHEMobileNotify::MHEMobileNotify(std::string gcmAppId, MHEDatabase *db, SpeechRecognize *sr) : _gcmAppId(gcmAppId), _db(db), _sr(sr)
{
    _log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("MHEMobileNotify"));
}

MHEMobileNotify::~MHEMobileNotify()
{
}

void MHEMobileNotify::notifyDevices(const std::string &event, const std::string &type, const std::string &msg)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify(event, -1);

    if (devices.size() > 0)
        notifyDevices(devices, type, msg);
}

void MHEMobileNotify::notifyDevices(MHEMobileNotifyType type, DBCondition &condition)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify("condition", condition.id);

    if (devices.size() > 0)
    {
        std::string typeStr = (type == conditionEnter ? "conditionEnter" : "conditionLeave");
        std::string msg;

        if (_sr != NULL)
        {
            std::stringstream ssMsg1, ssMsg2;

            ssMsg1 << "condition_" << typeStr << "_" << condition.id;
            ssMsg2 << "condition_" << typeStr;
            msg = _sr->getResponse(ssMsg1.str(), ssMsg2.str());
            boost::replace_all(msg, "%name%", condition.name);
        }
        else
            msg = typeStr;
        notifyDevices(devices, typeStr, msg);
    }
}

void MHEMobileNotify::notifyDevices(MHEMobileNotifyType type, MHEDevice &device)
{
    std::vector<DBMobile> devices = _db->getMobileActivatedToNotify("device", device.getId());

    if (devices.size() > 0)
    {
        std::string typeStr = (type == conditionEnter ? "deviceActivated" : "deviceDesactivated");
        std::string msg;

        if (_sr != NULL)
        {
            std::stringstream ssMsg1, ssMsg2;

            ssMsg1 << "device_" << typeStr << "_" << device.getId();
            ssMsg2 << "device_" << typeStr;
            msg = _sr->getResponse(ssMsg1.str(), ssMsg2.str());
            boost::replace_all(msg, "%name%", device.getName());
        }
        else
            msg = typeStr;
        notifyDevices(devices, typeStr, msg);
    }
}

void MHEMobileNotify::notifyDevices(std::vector<DBMobile> &devices, const std::string &type, const std::string &msg)
{
    LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notifyDevices - devices[]=" << devices.size() << " type=" << type << " msg=" << msg));
    BOOST_FOREACH(DBMobile &device, devices)
    {
        notifyDevice(device, type, msg);
    }
}

void MHEMobileNotify::notifyDevice(DBMobile &device, const std::string &type, const std::string &msg)
{
    LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notityDevice - device=" << (std::string)device << " type=" << type << " msg=" << msg));
    if (device.type == "gcm")
    {
        std::vector<std::string> headers;
        std::stringstream ss, ssOut;
        std::string postData;
        std::string url = "https://android.googleapis.com/gcm/send";

        ss << "Authorization: key=" << _gcmAppId;
        headers.push_back(ss.str());
        headers.push_back("Content-Type: application/json");
        ss.str(std::string());
        ss << "{"
                << "to: \"" << device.token << "\","
                << "data: {"
                    << "type: \"" << type << "\","
                    << "msg: \"" << msg << "\""
                << "}"
            << "}";
        postData = ss.str();
        if (curlExecute(url, &headers, &postData, &ssOut))
        {
            boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
            boost::gregorian::date currentDate = now.date();
            long dateYYYYMMDD = (long)currentDate.year() * 10000L + (long)currentDate.month() * 100L + (long)currentDate.day();
            long currentHHMMM = now.time_of_day().hours() * 100L + now.time_of_day().minutes();

            LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("notityDevice - success post=" << ss.str() << " return: " << ssOut));
            device.lastSuccessYYYYMMDDHHSS = dateYYYYMMDD * 10000L + currentHHMMM;
            _db->updateMobileLastSuccess(device);
        }
        else
            LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("notityDevice - failed post=" << ss.str()));
    }
    else
        LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("notityDevice - unkown type of device - " << (std::string)device));
}
<|endoftext|>


<commit_before>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <qimessaging/datastream.hpp>
#include <qimessaging/functiontype.hpp>

namespace qi
{
  inline GenericValue FunctionType::call(void* func,
    const std::vector<GenericValue>& args)
  {
    const std::vector<Type*> target = argumentsType();
    std::vector<GenericValue> toDestroy;
    std::vector<void*> convertedArgs;
    for (unsigned i=0; i<target.size(); ++i)
    {
      qiLogDebug("meta") << "argument " << i << " " << args[i].value;
      if (args[i].type->info() == target[i]->info())
        convertedArgs.push_back(args[i].value);
      else
      {
        qiLogDebug("meta") << "needs conversion "
        << args[i].type->infoString() << " -> "
        << target[i]->infoString();
        GenericValue v = args[i].convert(*target[i]);
        toDestroy.push_back(v);
        convertedArgs.push_back(v.value);
      }
    }
    void* res = call(func, convertedArgs);
    GenericValue result;
    result.type = resultType();
    result.value = res;
    for (unsigned i=0; i<toDestroy.size(); ++i)
      toDestroy[i].destroy();
    return result;
  }

  GenericFunction::GenericFunction()
  : type(type), value(value) {}

  GenericFunction::GenericFunction(const GenericValue & v)
  {
    type = dynamic_cast<FunctionType*>(v.type);
    value = type?v.value:0;
  }

  GenericValue GenericFunction::call(const std::vector<GenericValue>& args)
  {
    return type->call(value, args);
  }

  std::string FunctionType::signature() const
  {
    std::string res("(");
    for (unsigned i=0; i<_argumentsType.size(); ++i)
      res += _argumentsType[i]->signature();
    res += ')';
    return res;
  }

  std::string FunctionType::sigreturn() const
  {
    return _resultType->signature();
  }
}
<commit_msg>Fix release build: remove extra inline in .cpp .<commit_after>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <qimessaging/datastream.hpp>
#include <qimessaging/functiontype.hpp>

namespace qi
{
  GenericValue FunctionType::call(void* func,
    const std::vector<GenericValue>& args)
  {
    const std::vector<Type*> target = argumentsType();
    std::vector<GenericValue> toDestroy;
    std::vector<void*> convertedArgs;
    for (unsigned i=0; i<target.size(); ++i)
    {
      qiLogDebug("meta") << "argument " << i << " " << args[i].value;
      if (args[i].type->info() == target[i]->info())
        convertedArgs.push_back(args[i].value);
      else
      {
        qiLogDebug("meta") << "needs conversion "
        << args[i].type->infoString() << " -> "
        << target[i]->infoString();
        GenericValue v = args[i].convert(*target[i]);
        toDestroy.push_back(v);
        convertedArgs.push_back(v.value);
      }
    }
    void* res = call(func, convertedArgs);
    GenericValue result;
    result.type = resultType();
    result.value = res;
    for (unsigned i=0; i<toDestroy.size(); ++i)
      toDestroy[i].destroy();
    return result;
  }

  GenericFunction::GenericFunction()
  : type(type), value(value) {}

  GenericFunction::GenericFunction(const GenericValue & v)
  {
    type = dynamic_cast<FunctionType*>(v.type);
    value = type?v.value:0;
  }

  GenericValue GenericFunction::call(const std::vector<GenericValue>& args)
  {
    return type->call(value, args);
  }

  std::string FunctionType::signature() const
  {
    std::string res("(");
    for (unsigned i=0; i<_argumentsType.size(); ++i)
      res += _argumentsType[i]->signature();
    res += ')';
    return res;
  }

  std::string FunctionType::sigreturn() const
  {
    return _resultType->signature();
  }
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_FUN_IDENTITY_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_IDENTITY_CONSTRAIN_HPP

#include <stan/math/prim/meta.hpp>

namespace stan {
namespace math {

/**
 * Returns the result of applying the identity constraint
 * transform to the input.
 *
 *
This method is effectively a no-op and is mainly useful as a
 * placeholder in auto-generated code.
 *
 * @tparam T Type of scalar.
 * @param[in] x free scalar
 * @return transformed input
 */
template <typename T>
inline T identity_constrain(const T& x) {
  return x;
}

/**
 * Returns the result of applying the identity constraint
 * transform to the input and increments the log probability
 * reference with the log absolute Jacobian determinant.
 *
 *
This method is effectively a no-op and mainly useful as a
 * placeholder in auto-generated code.
 *
 * @tparam T type of scalar
 * @tparam S type of log probability
 * @param[in] x scalar
 * @return transformed input
 */
template <typename T, typename S>
inline T identity_constrain(const T& x, S& lp) {
  return x;
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Document unused parameter to silence doxygen warning.<commit_after>#ifndef STAN_MATH_PRIM_FUN_IDENTITY_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_IDENTITY_CONSTRAIN_HPP

#include <stan/math/prim/meta.hpp>

namespace stan {
namespace math {

/**
 * Returns the result of applying the identity constraint
 * transform to the input.
 *
 *
This method is effectively a no-op and is mainly useful as a
 * placeholder in auto-generated code.
 *
 * @tparam T Type of scalar.
 * @param[in] x free scalar
 * @return transformed input
 */
template <typename T>
inline T identity_constrain(const T& x) {
  return x;
}

/**
 * Returns the result of applying the identity constraint
 * transform to the input and increments the log probability
 * reference with the log absolute Jacobian determinant.
 *
 *
This method is effectively a no-op and mainly useful as a
 * placeholder in auto-generated code.
 *
 * @tparam T type of scalar
 * @tparam S type of log probability
 * @param[in] x scalar
 * @param[in] lp log density reference
 * @return transformed input
 */
template <typename T, typename S>
inline T identity_constrain(const T& x, S& lp) {
  return x;
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}
<commit_msg>CPP: Add missing license in cpp/test/phonenumbers/run_tests.cc.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// 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 <gtest/gtest.h>

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2010 Christian Van Brussel, Communications and Remote
      Sensing Laboratory of the School of Engineering at the
      Universite catholique de Louvain, Belgium
      http://www.tele.ucl.ac.be

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"

#include "basic.h"
#include "ivaria/reporter.h"
#include "csgeom/math.h"

CS_PLUGIN_NAMESPACE_BEGIN(BasicNodes)
{

  /********************
   *  BasicNodesManager
   ********************/

  SCF_IMPLEMENT_FACTORY(BasicNodesManager);

  CS_LEAKGUARD_IMPLEMENT(BasicNodesManager);

  BasicNodesManager::BasicNodesManager (iBase* parent)
    : scfImplementationType (this, parent)
  {
  }

  iSkeletonSpeedNodeFactory2* BasicNodesManager::CreateSpeedNodeFactory (const char* name)
  {
    csRef<iSkeletonSpeedNodeFactory2> newFact;
    newFact.AttachNew (new SpeedNodeFactory (this, name));

    return speedFactories.PutUnique (name, newFact);
  }

  iSkeletonSpeedNodeFactory2* BasicNodesManager::FindSpeedNodeFactory (const char* name)
  {
   return speedFactories.Get (name, 0);
  }

  void BasicNodesManager::ClearSpeedNodeFactories ()
  {
    speedFactories.DeleteAll ();
  }

  bool BasicNodesManager::Initialize (iObjectRegistry*)
  {
    this->object_reg = object_reg;
    return true;
  }

  void BasicNodesManager::Report (int severity, const char* msg, ...) const
  {
    va_list arg;
    va_start (arg, msg);
    csRef<iReporter> rep (csQueryRegistry<iReporter> (object_reg));
    if (rep)
      rep->ReportV (severity,
		    "crystalspace.mesh.animesh.controllers.basic",
		    msg, arg);
    else
      {
	csPrintfV (msg, arg);
	csPrintf ("\n");
      }
    va_end (arg);
  }

  /********************
   *  SpeedNodeFactory
   ********************/

  CS_LEAKGUARD_IMPLEMENT(SpeedNodeFactory);

  SpeedNodeFactory::SpeedNodeFactory (BasicNodesManager* manager, const char *name)
    : scfImplementationType (this), manager (manager), name (name)
  {
  }

  void SpeedNodeFactory::AddNode (iSkeletonAnimNodeFactory2* factory, float speed)
  {
    // user help: set it cyclic if it is an animnode, otherwise it has to be made by the user
    csRef<iSkeletonAnimationNodeFactory2> fact =
      scfQueryInterface<iSkeletonAnimationNodeFactory2> (factory);
    if (fact)
      fact->SetCyclic (true);

    // insert node in sorted position
    size_t index = speedList.InsertSorted (speed);
    subFactories.Insert (index, factory);
  }

  csPtr<iSkeletonAnimNode2> SpeedNodeFactory::CreateInstance (iSkeletonAnimPacket2* packet,
							      iSkeleton2* skeleton)
  {
    csRef<SpeedNode> newP;
    newP.AttachNew (new SpeedNode (this, skeleton));

    for (size_t i = 0; i < subFactories.GetSize (); i++)
    {
      csRef<iSkeletonAnimNode2> node =
	subFactories[i]->CreateInstance (packet, skeleton);
      newP->subNodes.Push (node);
    }

    return csPtr<iSkeletonAnimNode2> (newP);
  }

  const char* SpeedNodeFactory::GetNodeName () const
  {
    return name;
  }

  iSkeletonAnimNodeFactory2* SpeedNodeFactory::FindNode (const char* name)
  {
    if (this->name == name)
      return this;

    for (size_t i = 0; i < subFactories.GetSize (); i++)
    {
      iSkeletonAnimNodeFactory2* r = subFactories[i]->FindNode (name);
      if (r)
        return r;
    }

    return 0;
  }

  /********************
   *  SpeedNode
   ********************/

  CS_LEAKGUARD_IMPLEMENT(SpeedNode);

  SpeedNode::SpeedNode (SpeedNodeFactory* factory, iSkeleton2* skeleton)
    : scfImplementationType (this), factory (factory), skeleton (skeleton),
    speed (0.0f), slowNode (0), fastNode (0), currentPosition (0.0f), speedRatio (1.0f),
    isPlaying (false)
  {
  }

  void SpeedNode::SetSpeed (float speed)
  {
    if (isPlaying)
      UpdateNewSpeed (speed);

    else
    {
      if (subNodes.GetSize () != 0)
      {
	// bound value
	if (speed < factory->speedList[0])
	  speed = factory->speedList[0];
	else if (speed > factory->speedList[factory->speedList.GetSize () - 1])
	  speed = factory->speedList[factory->speedList.GetSize () - 1];
      }

      this->speed = speed;
    }
  }

  void SpeedNode::UpdateNewSpeed (float speed)
  {
    // bound value
    if (speed < factory->speedList[0])
      speed = factory->speedList[0];
    else if (speed > factory->speedList[factory->speedList.GetSize () - 1])
      speed = factory->speedList[factory->speedList.GetSize () - 1];

    // check if speed has changed
    if (this->speed == speed)
      return;

    // check if the speed was 0
    if (fabs (this->speed) < EPSILON)
      currentPosition = 0.0f;

    this->speed = speed;

    // check if there is only one node
    if (factory->speedList.GetSize () == 1)
    {
      slowNode = fastNode = 0;
      if (!subNodes[0]->IsActive ())
	subNodes[0]->Play ();

      return;
    }

    // find the anims bounding that speed value
    size_t newSlowNode, newFastNode;
    for (size_t i = 0; i < factory->speedList.GetSize () - 1; i++)
    {
      if (speed == factory->speedList[i])
      {
	newSlowNode = newFastNode = i;
	break;
      }

      if (speed > factory->speedList[i]
	  && speed < factory->speedList[i + 1])
      {
	newSlowNode = i;
	newFastNode = i + 1;
	break;
      }

      if (i == factory->speedList.GetSize () - 2)
      {
	newSlowNode = newFastNode = i + 1;
	break;
      }
    }

    // stop previous anims and play the new ones
    if (slowNode != newSlowNode && slowNode != newFastNode)
      subNodes[slowNode]->Stop ();
    if (fastNode != slowNode && fastNode != newSlowNode && fastNode != newFastNode)
      subNodes[fastNode]->Stop ();
    if (!subNodes[newSlowNode]->IsActive ())
      subNodes[newSlowNode]->Play ();
    if (!subNodes[newFastNode]->IsActive ())
      subNodes[newFastNode]->Play ();

    // compute playback speed & position of anims
    if (newSlowNode == newFastNode)
    {
      subNodes[newSlowNode]->SetPlaybackSpeed (1.0f);

      if (fabs (factory->speedList[newSlowNode]) < EPSILON)
	subNodes[newSlowNode]->SetPlaybackPosition (0.0f);
      else
	subNodes[newSlowNode]->SetPlaybackPosition (currentPosition *
						    subNodes[newSlowNode]->GetDuration ());
    }

    else
    {
      float speedDifference = factory->speedList[newFastNode] - factory->speedList[newSlowNode];
      speedRatio = (speed - factory->speedList[newSlowNode]) / speedDifference;
      cycleDuration = (1.0f - speedRatio) * subNodes[newSlowNode]->GetDuration ()
	+ speedRatio * subNodes[newFastNode]->GetDuration ();

      // apply new playback speeds
      subNodes[newSlowNode]->SetPlaybackSpeed
	(subNodes[newSlowNode]->GetDuration () / cycleDuration);
      subNodes[newFastNode]->SetPlaybackSpeed
	(subNodes[newFastNode]->GetDuration () / cycleDuration);

      // apply new playback positions
      subNodes[newSlowNode]->SetPlaybackPosition
	(currentPosition * subNodes[newSlowNode]->GetDuration ());
      subNodes[newFastNode]->SetPlaybackPosition
	(currentPosition * subNodes[newFastNode]->GetDuration ());
    }

    // save new anim indexes
    slowNode = newSlowNode;
    fastNode = newFastNode;
  }

  void SpeedNode::Play ()
  {
    if (isPlaying || subNodes.GetSize () == 0)
      return;

    isPlaying = true;
    currentPosition = 0.0f;
    speedRatio = 1.0f;

    // corrupt current speed to force the start
    float tempSpeed = speed;
    speed = factory->speedList[0] - 1.0f;

    // update to new speed
    UpdateNewSpeed (tempSpeed);
  }

  void SpeedNode::Stop ()
  {
    if (!isPlaying)
      return;

    isPlaying = false;

    // stop playing nodes
    subNodes[slowNode]->Stop ();
    if (slowNode != fastNode)
      subNodes[fastNode]->Stop ();
  }

  void SpeedNode::SetPlaybackPosition (float time)
  {
    // TODO?
  }

  float SpeedNode::GetPlaybackPosition () const
  {
    // TODO?
    return 0.0f;
  }

  float SpeedNode::GetDuration () const
  {
    // TODO?
    return 0.0f;
  }

  void SpeedNode::SetPlaybackSpeed (float speed)
  {
    // TODO!
  }

  float SpeedNode::GetPlaybackSpeed () const
  {
    // TODO!
    return 0.0f;
  }

  void SpeedNode::BlendState (csSkeletalState2* state, float baseWeight)
  {
    if (!isPlaying)
      return;

    if (slowNode == fastNode)
      subNodes[slowNode]->BlendState (state, baseWeight);

    else
    {
      // the blending should only be made by these two lines
      //subNodes[slowNode]->BlendState (state, baseWeight * (1.0f - speedRatio));
      //subNodes[fastNode]->BlendState (state, baseWeight * speedRatio);

      uint boneCount = skeleton->GetFactory ()->GetTopBoneID ();

      csRef<csSkeletalState2> slowState;
      slowState.AttachNew (new csSkeletalState2 ());
      slowState->Setup (boneCount + 1);

      csRef<csSkeletalState2> fastState;
      fastState.AttachNew (new csSkeletalState2 ());
      fastState->Setup (boneCount + 1);

      subNodes[slowNode]->BlendState (slowState, 1.0f);
      subNodes[fastNode]->BlendState (fastState, 1.0f);

      // TODO: this doesn't use the baseweight nor the previous state
      for (uint i = 0; i < boneCount; i++)
      {
	// if not both nodes use this bone then the pose can simply be copied
	if (!slowState->IsBoneUsed (i) && !fastState->IsBoneUsed (i))
	  continue;

	if (slowState->IsBoneUsed (i) && !fastState->IsBoneUsed (i))
	{
	  state->SetBoneUsed (i);
	  state->GetVector (i) = slowState->GetVector (i);
	  state->GetQuaternion (i) = slowState->GetQuaternion (i);
	  continue;
	}

	if (!slowState->IsBoneUsed (i) && fastState->IsBoneUsed (i))
	{
	  state->SetBoneUsed (i);
	  state->GetVector (i) = fastState->GetVector (i);
	  state->GetQuaternion (i) = fastState->GetQuaternion (i);
	  continue;
	}

	// put the transforms in bone space before blending them
	csQuaternion rotation;
	csVector3 offset;
	skeleton->GetFactory ()->GetTransformAbsSpace (i, rotation, offset);

	csQuaternion slowBoneQuaternion = slowState->GetQuaternion (i) * rotation.GetConjugate ();
	csQuaternion fastBoneQuaternion = fastState->GetQuaternion (i) * rotation.GetConjugate ();

	// blend the transforms then put them back in absolute space
	state->SetBoneUsed (i);
	state->GetVector (i) = csLerp (slowState->GetVector (i) - offset,
				       fastState->GetVector (i) - offset, speedRatio) + offset;
	state->GetQuaternion (i) =
	  slowBoneQuaternion.SLerp (fastBoneQuaternion, speedRatio) * rotation;
      }
    }
  }

  void SpeedNode::TickAnimation (float dt)
  {
    if (!isPlaying)
      return;

    // update current position
    currentPosition += dt / cycleDuration;
    if (currentPosition >= 1.0f)
      currentPosition = 0.0f;
    else if (currentPosition <= 0.0f)
      currentPosition = 1.0f;

    // tick the child nodes
    if (slowNode == fastNode)
      subNodes[slowNode]->TickAnimation (dt);

    else
    {
      subNodes[slowNode]->TickAnimation (dt);
      subNodes[fastNode]->TickAnimation (dt);
    }
  }

  bool SpeedNode::IsActive () const
  {
    return isPlaying;
  }

  iSkeletonAnimNodeFactory2* SpeedNode::GetFactory () const
  {
    return factory;
  }

  iSkeletonAnimNode2* SpeedNode::FindNode (const char* name)
  {
    if (factory->name == name)
      return this;

    for (size_t i = 0; i < subNodes.GetSize (); i++)
    {
      iSkeletonAnimNode2* r = subNodes[i]->FindNode (name);
      if (r)
        return r;
    }

    return 0;
  }

  void SpeedNode::AddAnimationCallback (iSkeletonAnimCallback2* callback)
  {
    // TODO?
  }

  void SpeedNode::RemoveAnimationCallback (iSkeletonAnimCallback2* callback)
  {
    // TODO?
  }

}
CS_PLUGIN_NAMESPACE_END(BasicNodes)
<commit_msg>Fixed the blending between two nodes in the 'speed' animation node<commit_after>/*
  Copyright (C) 2010 Christian Van Brussel, Communications and Remote
      Sensing Laboratory of the School of Engineering at the
      Universite catholique de Louvain, Belgium
      http://www.tele.ucl.ac.be

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"

#include "basic.h"
#include "ivaria/reporter.h"
#include "csgeom/math.h"

CS_PLUGIN_NAMESPACE_BEGIN(BasicNodes)
{

  /********************
   *  BasicNodesManager
   ********************/

  SCF_IMPLEMENT_FACTORY(BasicNodesManager);

  CS_LEAKGUARD_IMPLEMENT(BasicNodesManager);

  BasicNodesManager::BasicNodesManager (iBase* parent)
    : scfImplementationType (this, parent)
  {
  }

  iSkeletonSpeedNodeFactory2* BasicNodesManager::CreateSpeedNodeFactory (const char* name)
  {
    csRef<iSkeletonSpeedNodeFactory2> newFact;
    newFact.AttachNew (new SpeedNodeFactory (this, name));

    return speedFactories.PutUnique (name, newFact);
  }

  iSkeletonSpeedNodeFactory2* BasicNodesManager::FindSpeedNodeFactory (const char* name)
  {
   return speedFactories.Get (name, 0);
  }

  void BasicNodesManager::ClearSpeedNodeFactories ()
  {
    speedFactories.DeleteAll ();
  }

  bool BasicNodesManager::Initialize (iObjectRegistry*)
  {
    this->object_reg = object_reg;
    return true;
  }

  void BasicNodesManager::Report (int severity, const char* msg, ...) const
  {
    va_list arg;
    va_start (arg, msg);
    csRef<iReporter> rep (csQueryRegistry<iReporter> (object_reg));
    if (rep)
      rep->ReportV (severity,
		    "crystalspace.mesh.animesh.controllers.basic",
		    msg, arg);
    else
      {
	csPrintfV (msg, arg);
	csPrintf ("\n");
      }
    va_end (arg);
  }

  /********************
   *  SpeedNodeFactory
   ********************/

  CS_LEAKGUARD_IMPLEMENT(SpeedNodeFactory);

  SpeedNodeFactory::SpeedNodeFactory (BasicNodesManager* manager, const char *name)
    : scfImplementationType (this), manager (manager), name (name)
  {
  }

  void SpeedNodeFactory::AddNode (iSkeletonAnimNodeFactory2* factory, float speed)
  {
    // user help: set it cyclic if it is an animnode, otherwise it has to be made by the user
    csRef<iSkeletonAnimationNodeFactory2> fact =
      scfQueryInterface<iSkeletonAnimationNodeFactory2> (factory);
    if (fact)
      fact->SetCyclic (true);

    // insert node in sorted position
    size_t index = speedList.InsertSorted (speed);
    subFactories.Insert (index, factory);
  }

  csPtr<iSkeletonAnimNode2> SpeedNodeFactory::CreateInstance (iSkeletonAnimPacket2* packet,
							      iSkeleton2* skeleton)
  {
    csRef<SpeedNode> newP;
    newP.AttachNew (new SpeedNode (this, skeleton));

    for (size_t i = 0; i < subFactories.GetSize (); i++)
    {
      csRef<iSkeletonAnimNode2> node =
	subFactories[i]->CreateInstance (packet, skeleton);
      newP->subNodes.Push (node);
    }

    return csPtr<iSkeletonAnimNode2> (newP);
  }

  const char* SpeedNodeFactory::GetNodeName () const
  {
    return name;
  }

  iSkeletonAnimNodeFactory2* SpeedNodeFactory::FindNode (const char* name)
  {
    if (this->name == name)
      return this;

    for (size_t i = 0; i < subFactories.GetSize (); i++)
    {
      iSkeletonAnimNodeFactory2* r = subFactories[i]->FindNode (name);
      if (r)
        return r;
    }

    return 0;
  }

  /********************
   *  SpeedNode
   ********************/

  CS_LEAKGUARD_IMPLEMENT(SpeedNode);

  SpeedNode::SpeedNode (SpeedNodeFactory* factory, iSkeleton2* skeleton)
    : scfImplementationType (this), factory (factory), skeleton (skeleton),
    speed (0.0f), slowNode (0), fastNode (0), currentPosition (0.0f), speedRatio (1.0f),
    isPlaying (false)
  {
  }

  void SpeedNode::SetSpeed (float speed)
  {
    if (isPlaying)
      UpdateNewSpeed (speed);

    else
    {
      if (subNodes.GetSize () != 0)
      {
	// bound value
	if (speed < factory->speedList[0])
	  speed = factory->speedList[0];
	else if (speed > factory->speedList[factory->speedList.GetSize () - 1])
	  speed = factory->speedList[factory->speedList.GetSize () - 1];
      }

      this->speed = speed;
    }
  }

  void SpeedNode::UpdateNewSpeed (float speed)
  {
    // bound value
    if (speed < factory->speedList[0])
      speed = factory->speedList[0];
    else if (speed > factory->speedList[factory->speedList.GetSize () - 1])
      speed = factory->speedList[factory->speedList.GetSize () - 1];

    // check if speed has changed
    if (this->speed == speed)
      return;

    // check if the speed was 0
    if (fabs (this->speed) < EPSILON)
      currentPosition = 0.0f;

    this->speed = speed;

    // check if there is only one node
    if (factory->speedList.GetSize () == 1)
    {
      slowNode = fastNode = 0;
      if (!subNodes[0]->IsActive ())
	subNodes[0]->Play ();

      return;
    }

    // find the anims bounding that speed value
    size_t newSlowNode, newFastNode;
    for (size_t i = 0; i < factory->speedList.GetSize () - 1; i++)
    {
      if (speed == factory->speedList[i])
      {
	newSlowNode = newFastNode = i;
	break;
      }

      if (speed > factory->speedList[i]
	  && speed < factory->speedList[i + 1])
      {
	newSlowNode = i;
	newFastNode = i + 1;
	break;
      }

      if (i == factory->speedList.GetSize () - 2)
      {
	newSlowNode = newFastNode = i + 1;
	break;
      }
    }

    // stop previous anims and play the new ones
    if (slowNode != newSlowNode && slowNode != newFastNode)
      subNodes[slowNode]->Stop ();
    if (fastNode != slowNode && fastNode != newSlowNode && fastNode != newFastNode)
      subNodes[fastNode]->Stop ();
    if (!subNodes[newSlowNode]->IsActive ())
      subNodes[newSlowNode]->Play ();
    if (!subNodes[newFastNode]->IsActive ())
      subNodes[newFastNode]->Play ();

    // compute playback speed & position of anims
    if (newSlowNode == newFastNode)
    {
      subNodes[newSlowNode]->SetPlaybackSpeed (1.0f);

      if (fabs (factory->speedList[newSlowNode]) < EPSILON)
	subNodes[newSlowNode]->SetPlaybackPosition (0.0f);
      else
	subNodes[newSlowNode]->SetPlaybackPosition (currentPosition *
						    subNodes[newSlowNode]->GetDuration ());
    }

    else
    {
      float speedDifference = factory->speedList[newFastNode] - factory->speedList[newSlowNode];
      speedRatio = (speed - factory->speedList[newSlowNode]) / speedDifference;
      cycleDuration = (1.0f - speedRatio) * subNodes[newSlowNode]->GetDuration ()
	+ speedRatio * subNodes[newFastNode]->GetDuration ();

      // apply new playback speeds
      subNodes[newSlowNode]->SetPlaybackSpeed
	(subNodes[newSlowNode]->GetDuration () / cycleDuration);
      subNodes[newFastNode]->SetPlaybackSpeed
	(subNodes[newFastNode]->GetDuration () / cycleDuration);

      // apply new playback positions
      subNodes[newSlowNode]->SetPlaybackPosition
	(currentPosition * subNodes[newSlowNode]->GetDuration ());
      subNodes[newFastNode]->SetPlaybackPosition
	(currentPosition * subNodes[newFastNode]->GetDuration ());
    }

    // save new anim indexes
    slowNode = newSlowNode;
    fastNode = newFastNode;
  }

  void SpeedNode::Play ()
  {
    if (isPlaying || subNodes.GetSize () == 0)
      return;

    isPlaying = true;
    currentPosition = 0.0f;
    speedRatio = 1.0f;

    // corrupt current speed to force the start
    float tempSpeed = speed;
    speed = factory->speedList[0] - 1.0f;

    // update to new speed
    UpdateNewSpeed (tempSpeed);
  }

  void SpeedNode::Stop ()
  {
    if (!isPlaying)
      return;

    isPlaying = false;

    // stop playing nodes
    subNodes[slowNode]->Stop ();
    if (slowNode != fastNode)
      subNodes[fastNode]->Stop ();
  }

  void SpeedNode::SetPlaybackPosition (float time)
  {
    // TODO?
  }

  float SpeedNode::GetPlaybackPosition () const
  {
    // TODO?
    return 0.0f;
  }

  float SpeedNode::GetDuration () const
  {
    // TODO?
    return 0.0f;
  }

  void SpeedNode::SetPlaybackSpeed (float speed)
  {
    // TODO!
  }

  float SpeedNode::GetPlaybackSpeed () const
  {
    // TODO!
    return 0.0f;
  }

  void SpeedNode::BlendState (csSkeletalState2* state, float baseWeight)
  {
    if (!isPlaying)
      return;

    if (slowNode == fastNode)
      subNodes[slowNode]->BlendState (state, baseWeight);

    else
    {
      subNodes[slowNode]->BlendState (state, baseWeight);
      subNodes[fastNode]->BlendState (state, baseWeight * speedRatio);
    }
  }

  void SpeedNode::TickAnimation (float dt)
  {
    if (!isPlaying)
      return;

    // update current position
    currentPosition += dt / cycleDuration;
    if (currentPosition >= 1.0f)
      currentPosition = 0.0f;
    else if (currentPosition <= 0.0f)
      currentPosition = 1.0f;

    // tick the child nodes
    if (slowNode == fastNode)
      subNodes[slowNode]->TickAnimation (dt);

    else
    {
      subNodes[slowNode]->TickAnimation (dt);
      subNodes[fastNode]->TickAnimation (dt);
    }
  }

  bool SpeedNode::IsActive () const
  {
    return isPlaying;
  }

  iSkeletonAnimNodeFactory2* SpeedNode::GetFactory () const
  {
    return factory;
  }

  iSkeletonAnimNode2* SpeedNode::FindNode (const char* name)
  {
    if (factory->name == name)
      return this;

    for (size_t i = 0; i < subNodes.GetSize (); i++)
    {
      iSkeletonAnimNode2* r = subNodes[i]->FindNode (name);
      if (r)
        return r;
    }

    return 0;
  }

  void SpeedNode::AddAnimationCallback (iSkeletonAnimCallback2* callback)
  {
    // TODO?
  }

  void SpeedNode::RemoveAnimationCallback (iSkeletonAnimCallback2* callback)
  {
    // TODO?
  }

}
CS_PLUGIN_NAMESPACE_END(BasicNodes)
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    int partitionArray(vector<int> &nums, int k) {
        int left = 0;
        int right = nums.size() - 1;

        while (left <= right) {
            while (left <= right && nums[left] < k) {
                ++left;
            }
            while (left <= right && nums[right] >= k) {
                --right;
            }
            if (left <= right) {
               swap(nums[left++], nums[right--]);
            }
        }

        return left;
    }
};

class Solution2 {
public:
    int partitionArray(vector<int> &nums, int k) {
        int left = 0;
        int right = nums.size();

        while (left < right) {
            if (nums[left] < k) {  // Increase left boundary.
                ++left;
            } else {  // Put every element > k to the right.
                swap(nums[left], nums[--right]);
            }
        }

        return left;
    }
};
<commit_msg>Update partition-array.cpp<commit_after>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    /**
     * @param nums: a vector of integers
     * @return: nothing
     */
    void partitionArray(vector<int> &nums) {
        for (int left = 0, right = nums.size() - 1; left < right;) {
            if (nums[left] % 2 == 1) {
                ++left;
            } else if  (nums[right] % 2 == 0) {
                --right;
            } else {
               swap(nums[left++], nums[right--]);
            }
        }
    }
};

class Solution2 {
public:
    int partitionArray(vector<int> &nums, int k) {
        int left = 0;
        int right = nums.size();

        while (left < right) {
            if (nums[left] < k) {  // Increase left boundary.
                ++left;
            } else {  // Put every element > k to the right.
                swap(nums[left], nums[--right]);
            }
        }

        return left;
    }
};
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_MULTI_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_MULTI_NORMAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log_determinant_ldlt.hpp>
#include <stan/math/prim/fun/max_size_mvt.hpp>
#include <stan/math/prim/fun/size_mvt.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/trace_inv_quad_form_ldlt.hpp>

namespace stan {
namespace math {

template <bool propto, typename T_y, typename T_loc, typename T_covar>
return_type_t<T_y, T_loc, T_covar> multi_normal_lpdf(const T_y& y,
                                                     const T_loc& mu,
                                                     const T_covar& Sigma) {
  using T_covar_elem = typename scalar_type<T_covar>::type;
  using lp_type = return_type_t<T_y, T_loc, T_covar>;
  using Eigen::Dynamic;
  static const char* function = "multi_normal_lpdf";
  check_positive(function, "Covariance matrix rows", Sigma.rows());
  ;

  check_consistent_sizes_mvt(function, "y", y, "mu", mu);
  size_t number_of_y = size_mvt(y);
  size_t number_of_mu = size_mvt(mu);
  if (number_of_y == 0 || number_of_mu == 0) {
    return 0.0;
  }

  lp_type lp(0.0);
  vector_seq_view<T_y> y_vec(y);
  vector_seq_view<T_loc> mu_vec(mu);
  size_t size_vec = max_size_mvt(y, mu);

  int size_y = y_vec[0].size();
  int size_mu = mu_vec[0].size();
  if (size_vec > 1) {
    for (size_t i = 1, size_mvt_y = size_mvt(y); i < size_mvt_y; i++) {
      check_size_match(function,
                       "Size of one of the vectors of "
                       "the random variable",
                       y_vec[i].size(),
                       "Size of the first vector of the "
                       "random variable",
                       size_y);
    }
    for (size_t i = 1, size_mvt_mu = size_mvt(mu); i < size_mvt_mu; i++) {
      check_size_match(function,
                       "Size of one of the vectors of "
                       "the location variable",
                       mu_vec[i].size(),
                       "Size of the first vector of the "
                       "location variable",
                       size_mu);
    }
  }

  check_size_match(function, "Size of random variable", size_y,
                   "size of location parameter", size_mu);
  check_size_match(function, "Size of random variable", size_y,
                   "rows of covariance parameter", Sigma.rows());
  check_size_match(function, "Size of random variable", size_y,
                   "columns of covariance parameter", Sigma.cols());

  for (size_t i = 0; i < size_vec; i++) {
    check_finite(function, "Location parameter", mu_vec[i]);
    check_not_nan(function, "Random variable", y_vec[i]);
  }
  const auto& Sigma_ref = to_ref(Sigma);
  check_symmetric(function, "Covariance matrix", Sigma_ref);

  LDLT_factor<T_covar_elem, Dynamic, Dynamic> ldlt_Sigma(Sigma_ref);
  check_ldlt_factor(function, "LDLT_Factor of covariance parameter",
                    ldlt_Sigma);

  if (size_y == 0) {
    return lp;
  }

  if (include_summand<propto>::value) {
    lp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec;
  }

  if (include_summand<propto, T_covar_elem>::value) {
    lp -= 0.5 * log_determinant_ldlt(ldlt_Sigma) * size_vec;
  }

  if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) {
    lp_type sum_lp_vec(0.0);
    for (size_t i = 0; i < size_vec; i++) {
      const auto& y_col = as_column_vector_or_scalar(y_vec[i]);
      const auto& mu_col = as_column_vector_or_scalar(mu_vec[i]);
      sum_lp_vec += trace_inv_quad_form_ldlt(ldlt_Sigma, y_col - mu_col);
    }
    lp -= 0.5 * sum_lp_vec;
  }
  return lp;
}

template <typename T_y, typename T_loc, typename T_covar>
inline return_type_t<T_y, T_loc, T_covar> multi_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_covar& Sigma) {
  return multi_normal_lpdf<false>(y, mu, Sigma);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>fixed cpplint<commit_after>#ifndef STAN_MATH_PRIM_PROB_MULTI_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_MULTI_NORMAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log_determinant_ldlt.hpp>
#include <stan/math/prim/fun/max_size_mvt.hpp>
#include <stan/math/prim/fun/size_mvt.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/trace_inv_quad_form_ldlt.hpp>

namespace stan {
namespace math {

template <bool propto, typename T_y, typename T_loc, typename T_covar>
return_type_t<T_y, T_loc, T_covar> multi_normal_lpdf(const T_y& y,
                                                     const T_loc& mu,
                                                     const T_covar& Sigma) {
  using T_covar_elem = typename scalar_type<T_covar>::type;
  using lp_type = return_type_t<T_y, T_loc, T_covar>;
  using Eigen::Dynamic;
  static const char* function = "multi_normal_lpdf";
  check_positive(function, "Covariance matrix rows", Sigma.rows());

  check_consistent_sizes_mvt(function, "y", y, "mu", mu);
  size_t number_of_y = size_mvt(y);
  size_t number_of_mu = size_mvt(mu);
  if (number_of_y == 0 || number_of_mu == 0) {
    return 0.0;
  }

  lp_type lp(0.0);
  vector_seq_view<T_y> y_vec(y);
  vector_seq_view<T_loc> mu_vec(mu);
  size_t size_vec = max_size_mvt(y, mu);

  int size_y = y_vec[0].size();
  int size_mu = mu_vec[0].size();
  if (size_vec > 1) {
    for (size_t i = 1, size_mvt_y = size_mvt(y); i < size_mvt_y; i++) {
      check_size_match(function,
                       "Size of one of the vectors of "
                       "the random variable",
                       y_vec[i].size(),
                       "Size of the first vector of the "
                       "random variable",
                       size_y);
    }
    for (size_t i = 1, size_mvt_mu = size_mvt(mu); i < size_mvt_mu; i++) {
      check_size_match(function,
                       "Size of one of the vectors of "
                       "the location variable",
                       mu_vec[i].size(),
                       "Size of the first vector of the "
                       "location variable",
                       size_mu);
    }
  }

  check_size_match(function, "Size of random variable", size_y,
                   "size of location parameter", size_mu);
  check_size_match(function, "Size of random variable", size_y,
                   "rows of covariance parameter", Sigma.rows());
  check_size_match(function, "Size of random variable", size_y,
                   "columns of covariance parameter", Sigma.cols());

  for (size_t i = 0; i < size_vec; i++) {
    check_finite(function, "Location parameter", mu_vec[i]);
    check_not_nan(function, "Random variable", y_vec[i]);
  }
  const auto& Sigma_ref = to_ref(Sigma);
  check_symmetric(function, "Covariance matrix", Sigma_ref);

  LDLT_factor<T_covar_elem, Dynamic, Dynamic> ldlt_Sigma(Sigma_ref);
  check_ldlt_factor(function, "LDLT_Factor of covariance parameter",
                    ldlt_Sigma);

  if (size_y == 0) {
    return lp;
  }

  if (include_summand<propto>::value) {
    lp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec;
  }

  if (include_summand<propto, T_covar_elem>::value) {
    lp -= 0.5 * log_determinant_ldlt(ldlt_Sigma) * size_vec;
  }

  if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) {
    lp_type sum_lp_vec(0.0);
    for (size_t i = 0; i < size_vec; i++) {
      const auto& y_col = as_column_vector_or_scalar(y_vec[i]);
      const auto& mu_col = as_column_vector_or_scalar(mu_vec[i]);
      sum_lp_vec += trace_inv_quad_form_ldlt(ldlt_Sigma, y_col - mu_col);
    }
    lp -= 0.5 * sum_lp_vec;
  }
  return lp;
}

template <typename T_y, typename T_loc, typename T_covar>
inline return_type_t<T_y, T_loc, T_covar> multi_normal_lpdf(
    const T_y& y, const T_loc& mu, const T_covar& Sigma) {
  return multi_normal_lpdf<false>(y, mu, Sigma);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/app.h>
#include <vespa/fastos/thread.h>
#include <vespa/log/bufferedlogger.h>
#include <array>
#include <iostream>
#include <thread>
#include <chrono>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cstdlib>

using std::string;
using namespace std::chrono_literals;
using namespace std::chrono;

LOG_SETUP(".threadtest");

class FileThread : public FastOS_Runnable
{
    bool _done;
    string _file;
public:
    FileThread(string file) : _done(false), _file(file) {}
    void Run(FastOS_ThreadInterface *thread, void *arg) override;
    void stop() {_done = true; }
};

class LoggerThread : public FastOS_Runnable
{
    bool _done;
public:
    bool _useLogBuffer;
    LoggerThread() : _done(false), _useLogBuffer(false) {}
    void Run(FastOS_ThreadInterface *thread, void *arg) override;
    void stop() {_done = true; }
};

void
FileThread::Run(FastOS_ThreadInterface *, void *)
{
    unlink(_file.c_str());
    while (!_done) {
        int fd = open(_file.c_str(), O_RDWR | O_CREAT | O_APPEND, 0644);
        if (fd == -1) {
            fprintf(stderr, "open failed: %s\n", strerror(errno));
            std::_Exit(1);
        }
        std::this_thread::sleep_for(5ms);
        struct stat buf;
        fstat(fd, &buf);
        if (buf.st_size != 0) {
            fprintf(stderr, "%s isn't empty anymore\n", _file.c_str());
            std::_Exit(1);
        }
        if (close(fd) != 0) {
            fprintf(stderr, "close of %d failed: %s\n", fd, strerror(errno));
            std::_Exit(1);
        }
    }
}

void
LoggerThread::Run(FastOS_ThreadInterface *, void *)
{
    int counter = 0;
    while (!_done) {
        if (_useLogBuffer) {
            LOGBM(info, "bla bla bla %u", ++counter);
        } else {
            LOG(info, "bla bla bla");
        }
    }
}

class ThreadTester : public FastOS_Application
{
public:
    int Main() override;
};

int
ThreadTester::Main()
{
    std::cerr << "Testing that logging is threadsafe. 5 sec test.\n";
    FastOS_ThreadPool pool(128 * 1024);

    const int numWriters = 30;
    const int numLoggers = 10;

    auto writers = std::array<std::unique_ptr<FileThread>, numWriters>();
    auto loggers = std::array<std::unique_ptr<LoggerThread>, numLoggers>();

    for (int i = 0; i < numWriters; i++) {
        char filename[100];
        sprintf(filename, "empty.%d", i);
        writers[i] = std::make_unique<FileThread>(filename);
        pool.NewThread(writers[i].get());
    }
    for (int i = 0; i < numLoggers; i++) {
        loggers[i] = std::make_unique<LoggerThread>();
        pool.NewThread(loggers[i].get());
    }

    steady_clock::time_point start = steady_clock::now();
    // Reduced runtime to half as the test now repeats itself to test with
    // buffering. (To avoid test taking 5 seconds)
    while ((steady_clock::now() - start) < 2.5s) {
        unlink(_argv[1]);
        std::this_thread::sleep_for(1ms);
    }
        // Then set to use logbuffer and continue
    for (int i = 0; i < numLoggers; i++) {
        loggers[i]->_useLogBuffer = true;
    }
    start = steady_clock::now();
    while ((steady_clock::now() - start) < 2.5s) {
        unlink(_argv[1]);
        std::this_thread::sleep_for(1ms);
    }

    for (int i = 0; i < numLoggers; i++) {
        loggers[i]->stop();
    }
    for (int i = 0; i < numWriters; i++) {
        writers[i]->stop();
    }

    pool.Close();

    return 0;
}

int main(int argc, char **argv)
{
    ThreadTester app;
    return app.Entry(argc, argv);
}

<commit_msg>fix tsan warnings<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/app.h>
#include <vespa/fastos/thread.h>
#include <vespa/log/bufferedlogger.h>
#include <array>
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cstdlib>

using std::string;
using namespace std::chrono_literals;
using namespace std::chrono;

LOG_SETUP(".threadtest");

class FileThread : public FastOS_Runnable
{
    std::atomic<bool> _done;
    string _file;
public:
    FileThread(string file) : _done(false), _file(file) {}
    void Run(FastOS_ThreadInterface *thread, void *arg) override;
    void stop() { _done.store(true, std::memory_order_relaxed); }
};

class LoggerThread : public FastOS_Runnable
{
    std::atomic<bool> _done;
public:
    std::atomic<bool> _useLogBuffer;
    LoggerThread() : _done(false), _useLogBuffer(false) {}
    void Run(FastOS_ThreadInterface *thread, void *arg) override;
    void stop() { _done.store(true, std::memory_order_relaxed); }
};

void
FileThread::Run(FastOS_ThreadInterface *, void *)
{
    unlink(_file.c_str());
    while (!_done.load(std::memory_order_relaxed)) {
        int fd = open(_file.c_str(), O_RDWR | O_CREAT | O_APPEND, 0644);
        if (fd == -1) {
            fprintf(stderr, "open failed: %s\n", strerror(errno));
            std::_Exit(1);
        }
        std::this_thread::sleep_for(5ms);
        struct stat buf;
        fstat(fd, &buf);
        if (buf.st_size != 0) {
            fprintf(stderr, "%s isn't empty anymore\n", _file.c_str());
            std::_Exit(1);
        }
        if (close(fd) != 0) {
            fprintf(stderr, "close of %d failed: %s\n", fd, strerror(errno));
            std::_Exit(1);
        }
    }
}

void
LoggerThread::Run(FastOS_ThreadInterface *, void *)
{
    int counter = 0;
    while (!_done.load(std::memory_order_relaxed)) {
        if (_useLogBuffer.load(std::memory_order_relaxed)) {
            LOGBM(info, "bla bla bla %u", ++counter);
        } else {
            LOG(info, "bla bla bla");
        }
    }
}

class ThreadTester : public FastOS_Application
{
public:
    int Main() override;
};

int
ThreadTester::Main()
{
    std::cerr << "Testing that logging is threadsafe. 5 sec test.\n";
    FastOS_ThreadPool pool(128 * 1024);

    const int numWriters = 30;
    const int numLoggers = 10;

    auto writers = std::array<std::unique_ptr<FileThread>, numWriters>();
    auto loggers = std::array<std::unique_ptr<LoggerThread>, numLoggers>();

    for (int i = 0; i < numWriters; i++) {
        char filename[100];
        sprintf(filename, "empty.%d", i);
        writers[i] = std::make_unique<FileThread>(filename);
        pool.NewThread(writers[i].get());
    }
    for (int i = 0; i < numLoggers; i++) {
        loggers[i] = std::make_unique<LoggerThread>();
        pool.NewThread(loggers[i].get());
    }

    steady_clock::time_point start = steady_clock::now();
    // Reduced runtime to half as the test now repeats itself to test with
    // buffering. (To avoid test taking 5 seconds)
    while ((steady_clock::now() - start) < 2.5s) {
        unlink(_argv[1]);
        std::this_thread::sleep_for(1ms);
    }
        // Then set to use logbuffer and continue
    for (int i = 0; i < numLoggers; i++) {
        loggers[i]->_useLogBuffer.store(true, std::memory_order_relaxed);
    }
    start = steady_clock::now();
    while ((steady_clock::now() - start) < 2.5s) {
        unlink(_argv[1]);
        std::this_thread::sleep_for(1ms);
    }

    for (int i = 0; i < numLoggers; i++) {
        loggers[i]->stop();
    }
    for (int i = 0; i < numWriters; i++) {
        writers[i]->stop();
    }

    pool.Close();

    return 0;
}

int main(int argc, char **argv)
{
    ThreadTester app;
    return app.Entry(argc, argv);
}

<|endoftext|>


<commit_before>// Time:  O(logn)
// Space: O(1)

class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while (x) {
            auto prev = result;
            result *= 10;
            result += x % 10;
            if (result / 10 != prev) {
                result = 0;
                break;
            }
            x /= 10;
        }
        return result;
    }
};
<commit_msg>Update reverse-integer.cpp<commit_after>// Time:  O(logn) = O(1)
// Space: O(1)

class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while (x) {
            auto prev = result;
            result *= 10;
            result += x % 10;
            if (result / 10 != prev) {
                result = 0;
                break;
            }
            x /= 10;
        }
        return result;
    }
};
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP
#define STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP

#include <stan/math/prim/fun/add_diag.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/fun/inverse.hpp>

namespace stan {
namespace math {

namespace internal {
/*
 * Reverse mode specialization of calculating the generalized inverse of a
 * matrix.
 *

 Golub, G.H. and Pereyra, V. The Differentiation of Pseudo-Inverses
 * and Nonlinear Least Squares Problems Whose Variables Separate. SIAM
 * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp.
 * 413-432

 */
template <typename T1, typename T2>
inline auto generalized_inverse_lambda(T1& G_arena, T2& inv_G) {
  return [G_arena, inv_G]() mutable {
     G_arena.adj()
        += -(inv_G.val_op().transpose() * inv_G.adj_op()
             * inv_G.val_op().transpose())
           + (-G_arena.val_op() * inv_G.val_op()
              + Eigen::MatrixXd::Identity(G_arena.rows(), inv_G.cols()))
                 * inv_G.adj_op().transpose() * inv_G.val_op()
                 * inv_G.val_op().transpose()
           + inv_G.val_op().transpose() * inv_G.val_op()
                 * inv_G.adj_op().transpose()
                 * (-inv_G.val_op() * G_arena.val_op()
                    + Eigen::MatrixXd::Identity(inv_G.rows(), G_arena.cols()));
  };
}
}  // namespace internal

/*
 * Reverse mode specialization of calculating the generalized inverse of a
 * matrix.
 *
 * @param G specified matrix
 * @return Generalized inverse of the matrix (an empty matrix if the specified
 * matrix has size zero).
 *
 * @note For the derivatives of this function to exist the matrix must be
 * of constant rank.
 * Reverse mode differentiation algorithm reference:
 *
 *

 Golub, G.H. and Pereyra, V. The Differentiation of Pseudo-Inverses
 * and Nonlinear Least Squares Problems Whose Variables Separate. SIAM
 * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp.
 * 413-432

 *
 * Equation 4.12 in the paper
 *
 *  See also
 *  http://mathoverflow.net/questions/25778/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse
 *
 */
template <typename VarMat, require_rev_matrix_t<VarMat>* = nullptr>
inline auto generalized_inverse(const VarMat& G) {
  using ret_type = promote_var_matrix_t<VarMat, VarMat>;

  if (G.size() == 0)
    return ret_type(G);

  if (G.rows() == G.cols()) {
    arena_t<VarMat> G_arena(G);
    Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd>
        complete_ortho_decomp_G
        = G_arena.val().completeOrthogonalDecomposition();
    if (!(complete_ortho_decomp_G.rank() < G.rows())) {
      return ret_type(inverse(G_arena));
    } else {
      arena_t<ret_type> inv_G(complete_ortho_decomp_G.pseudoInverse());
      reverse_pass_callback(
          internal::generalized_inverse_lambda(G_arena, inv_G));
      return ret_type(inv_G);
    }
  } else if (G.rows() < G.cols()) {
    arena_t<VarMat> G_arena(G);
    arena_t<ret_type> inv_G((G_arena.val_op() * G_arena.val_op().transpose())
                                .ldlt()
                                .solve(G_arena.val_op())
                                .transpose());
    reverse_pass_callback(internal::generalized_inverse_lambda(G_arena, inv_G));
    return ret_type(inv_G);
  } else {
    arena_t<VarMat> G_arena(G);
    arena_t<ret_type> inv_G((G_arena.val_op().transpose() * G_arena.val_op())
                                .ldlt()
                                .solve(G_arena.val_op().transpose()));
    reverse_pass_callback(internal::generalized_inverse_lambda(G_arena, inv_G));
    return ret_type(inv_G);
  }
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP
#define STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP

#include <stan/math/prim/fun/add_diag.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/fun/inverse.hpp>

namespace stan {
namespace math {

namespace internal {
/*
 * Reverse mode specialization of calculating the generalized inverse of a
 * matrix.
 *

 Golub, G.H. and Pereyra, V. The Differentiation of Pseudo-Inverses
 * and Nonlinear Least Squares Problems Whose Variables Separate. SIAM
 * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp.
 * 413-432

 */
template <typename T1, typename T2>
inline auto generalized_inverse_lambda(T1& G_arena, T2& inv_G) {
  return [G_arena, inv_G]() mutable {
    G_arena.adj()
        += -(inv_G.val_op().transpose() * inv_G.adj_op()
             * inv_G.val_op().transpose())
           + (-G_arena.val_op() * inv_G.val_op()
              + Eigen::MatrixXd::Identity(G_arena.rows(), inv_G.cols()))
                 * inv_G.adj_op().transpose() * inv_G.val_op()
                 * inv_G.val_op().transpose()
           + inv_G.val_op().transpose() * inv_G.val_op()
                 * inv_G.adj_op().transpose()
                 * (-inv_G.val_op() * G_arena.val_op()
                    + Eigen::MatrixXd::Identity(inv_G.rows(), G_arena.cols()));
  };
}
}  // namespace internal

/*
 * Reverse mode specialization of calculating the generalized inverse of a
 * matrix.
 *
 * @param G specified matrix
 * @return Generalized inverse of the matrix (an empty matrix if the specified
 * matrix has size zero).
 *
 * @note For the derivatives of this function to exist the matrix must be
 * of constant rank.
 * Reverse mode differentiation algorithm reference:
 *
 *

 Golub, G.H. and Pereyra, V. The Differentiation of Pseudo-Inverses
 * and Nonlinear Least Squares Problems Whose Variables Separate. SIAM
 * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp.
 * 413-432

 *
 * Equation 4.12 in the paper
 *
 *  See also
 *  http://mathoverflow.net/questions/25778/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse
 *
 */
template <typename VarMat, require_rev_matrix_t<VarMat>* = nullptr>
inline auto generalized_inverse(const VarMat& G) {
  using ret_type = promote_var_matrix_t<VarMat, VarMat>;

  if (G.size() == 0)
    return ret_type(G);

  if (G.rows() == G.cols()) {
    arena_t<VarMat> G_arena(G);
    Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd>
        complete_ortho_decomp_G
        = G_arena.val().completeOrthogonalDecomposition();
    if (!(complete_ortho_decomp_G.rank() < G.rows())) {
      return ret_type(inverse(G_arena));
    } else {
      arena_t<ret_type> inv_G(complete_ortho_decomp_G.pseudoInverse());
      reverse_pass_callback(
          internal::generalized_inverse_lambda(G_arena, inv_G));
      return ret_type(inv_G);
    }
  } else if (G.rows() < G.cols()) {
    arena_t<VarMat> G_arena(G);
    arena_t<ret_type> inv_G((G_arena.val_op() * G_arena.val_op().transpose())
                                .ldlt()
                                .solve(G_arena.val_op())
                                .transpose());
    reverse_pass_callback(internal::generalized_inverse_lambda(G_arena, inv_G));
    return ret_type(inv_G);
  } else {
    arena_t<VarMat> G_arena(G);
    arena_t<ret_type> inv_G((G_arena.val_op().transpose() * G_arena.val_op())
                                .ldlt()
                                .solve(G_arena.val_op().transpose()));
    reverse_pass_callback(internal::generalized_inverse_lambda(G_arena, inv_G));
    return ret_type(inv_G);
  }
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  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 Willow Garage, Inc. 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.
 *
 * Author: Nico Blodow (blodow@cs.tum.edu)
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/octree/octree.h>
#include <pcl/filters/extract_indices.h>

class OpenNIChangeViewer
{
  public:
    OpenNIChangeViewer (double resolution)
      : viewer ("PCL OpenNI Viewer")
    {
      octree = new pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGB>(resolution);
    }

    void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
    {
      std::cerr << cloud->points.size() << " -- ";

      // assign point cloud to octree
      octree->setInputCloud (cloud);

      // add points from cloud to octree
      octree->addPointsFromInputCloud ();

      std::cerr << octree->getLeafCount() << " -- ";
      boost::shared_ptr<std::vector<int> > newPointIdxVector (new std::vector<int>);

      // get a vector of new points, which did not exist in previous buffer
      octree->getPointIndicesFromNewVoxels (*newPointIdxVector, 7);

      std::cerr << newPointIdxVector->size() << std::endl;

      //// extract points from pointcloud
      pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered_cloud (new pcl::PointCloud<pcl::PointXYZRGB> (*cloud));
      //pcl::ExtractIndices<pcl::PointXYZRGB> ei;
      //ei.setInputCloud (cloud);
      //ei.setIndices (newPointIdxVector);
      //ei.filter (filtered_cloud);

      for (std::vector<int>::iterator it = newPointIdxVector->begin (); it != newPointIdxVector->end (); it++)
        filtered_cloud->points[*it].rgb = 255<<16;

      if (!viewer.wasStopped())
        viewer.showCloud (filtered_cloud);

      // switch buffers - reset tree
      octree->switchBuffers ();
    }

    void run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber();

      boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f =
        boost::bind (&OpenNIChangeViewer::cloud_cb_, this, _1);

      boost::signals2::connection c = interface->registerCallback (f);

      interface->start ();

      while (!viewer.wasStopped())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    }

    pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGB> *octree;
    pcl::visualization::CloudViewer viewer;
};

int
main (int argc, char* argv[])
{
  double resolution = 0.01;
  if (argc > 1)
    resolution = atof (argv[1]);

  OpenNIChangeViewer v (resolution);
  v.run ();
  return 0;
}

<commit_msg>extended openni_change_viewer with improved command line interface<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  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 Willow Garage, Inc. 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.
 *
 * Author: Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de)
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/octree/octree.h>
#include <pcl/filters/extract_indices.h>

#include <pcl/console/parse.h>

enum {
  REDDIFF_MODE,
  ONLYDIFF_MODE,

  MODE_COUNT
};

class OpenNIChangeViewer
{
  public:
    OpenNIChangeViewer (double resolution, int mode, int noise_filter)
      : viewer ("PCL OpenNI Viewer")
    {
      octree = new pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGB>(resolution);
      mode_ = mode;
      noise_filter_ = noise_filter;
    }

    void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
    {
      std::cerr << cloud->points.size() << " -- ";

      // assign point cloud to octree
      octree->setInputCloud (cloud);

      // add points from cloud to octree
      octree->addPointsFromInputCloud ();

      std::cerr << octree->getLeafCount() << " -- ";
      boost::shared_ptr<std::vector<int> > newPointIdxVector (new std::vector<int>);

      // get a vector of new points, which did not exist in previous buffer
      octree->getPointIndicesFromNewVoxels (*newPointIdxVector, noise_filter_);

      std::cerr << newPointIdxVector->size() << std::endl;

      pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered_cloud;

      switch (mode_) {
        case REDDIFF_MODE:
          filtered_cloud = (pcl::PointCloud<pcl::PointXYZRGB>::Ptr) new pcl::PointCloud<pcl::PointXYZRGB> (*cloud);

          filtered_cloud->points.reserve(newPointIdxVector->size());

          for (std::vector<int>::iterator it = newPointIdxVector->begin (); it != newPointIdxVector->end (); it++)
            filtered_cloud->points[*it].rgb = 255<<16;

          if (!viewer.wasStopped())
            viewer.showCloud (filtered_cloud);

          break;
        case ONLYDIFF_MODE:
          filtered_cloud = (pcl::PointCloud<pcl::PointXYZRGB>::Ptr) new pcl::PointCloud<pcl::PointXYZRGB> ();

          filtered_cloud->points.reserve(newPointIdxVector->size());

          for (std::vector<int>::iterator it = newPointIdxVector->begin (); it != newPointIdxVector->end (); it++)
            filtered_cloud->points.push_back(cloud->points[*it]);

          if (!viewer.wasStopped())
            viewer.showCloud (filtered_cloud);
          break;
      }

      // switch buffers - reset tree
      octree->switchBuffers ();
    }

    void run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber();

      boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f =
        boost::bind (&OpenNIChangeViewer::cloud_cb_, this, _1);

      boost::signals2::connection c = interface->registerCallback (f);

      interface->start ();

      while (!viewer.wasStopped())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    }

    pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGB> *octree;
    pcl::visualization::CloudViewer viewer;

    int mode_;
    int noise_filter_;
};

int
main (int argc, char* argv[])
{

  std::cout << "Syntax is " << argv[0] << " [-r octree resolution] [-d] [-n noise_filter intensity] \n";

  int mode = REDDIFF_MODE;
  int noise_filter = 7;
  double resolution = 0.01;

  pcl::console::parse_argument (argc, argv, "-r", resolution);

  pcl::console::parse_argument (argc, argv, "-n", noise_filter);

  if (pcl::console::find_argument (argc, argv, "-d")>0) {
    mode = ONLYDIFF_MODE;
  }

  OpenNIChangeViewer v (resolution, mode, noise_filter);
  v.run ();
  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/tabbed_pane/tabbed_pane.h"

#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "views/controls/native/native_view_host.h"
#include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h"

namespace views {

// static
const char TabbedPane::kViewClassName[] = "views/TabbedPane";

TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) {
  SetFocusable(true);
}

TabbedPane::~TabbedPane() {
}

void TabbedPane::SetListener(Listener* listener) {
  listener_ = listener;
}

void TabbedPane::AddTab(const std::wstring& title, View* contents) {
  native_tabbed_pane_->AddTab(title, contents);
  PreferredSizeChanged();
}

void TabbedPane::AddTabAtIndex(int index,
                               const std::wstring& title,
                               View* contents,
                               bool select_if_first_tab) {
  native_tabbed_pane_->AddTabAtIndex(index, title, contents,
                                     select_if_first_tab);
  contents->SetAccessibleName(title);
  PreferredSizeChanged();
}

int TabbedPane::GetSelectedTabIndex() {
  return native_tabbed_pane_->GetSelectedTabIndex();
}

View* TabbedPane::GetSelectedTab() {
  return native_tabbed_pane_->GetSelectedTab();
}

View* TabbedPane::RemoveTabAtIndex(int index) {
  return native_tabbed_pane_->RemoveTabAtIndex(index);
  PreferredSizeChanged();
}

void TabbedPane::SelectTabAt(int index) {
  native_tabbed_pane_->SelectTabAt(index);
}

int TabbedPane::GetTabCount() {
  return native_tabbed_pane_->GetTabCount();
}

void TabbedPane::CreateWrapper() {
  native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this);
}

// View overrides:
std::string TabbedPane::GetClassName() const {
  return kViewClassName;
}

void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_tabbed_pane_) {
    CreateWrapper();
    AddChildView(native_tabbed_pane_->GetView());
    LoadAccelerators();
  }
}

bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) {
  // We only accept Ctrl+Tab keyboard events.
  DCHECK(accelerator.GetKeyCode() ==
      base::VKEY_TAB && accelerator.IsCtrlDown());

  int tab_count = GetTabCount();
  if (tab_count <= 1)
    return false;
  int selected_tab_index = GetSelectedTabIndex();
  int next_tab_index = accelerator.IsShiftDown() ?
      (selected_tab_index - 1) % tab_count :
      (selected_tab_index + 1) % tab_count;
  // Wrap around.
  if (next_tab_index < 0)
    next_tab_index += tab_count;
  SelectTabAt(next_tab_index);
  return true;
}

void TabbedPane::LoadAccelerators() {
  // Ctrl+Shift+Tab
  AddAccelerator(views::Accelerator(base::VKEY_TAB, true, true, false));
  // Ctrl+Tab
  AddAccelerator(views::Accelerator(base::VKEY_TAB, false, true, false));
}

void TabbedPane::Layout() {
  if (native_tabbed_pane_)
    native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height());
}

void TabbedPane::Focus() {
  // Forward the focus to the wrapper.
  if (native_tabbed_pane_) {
    native_tabbed_pane_->SetFocus();

    View* selected_tab = GetSelectedTab();
    if (selected_tab)
       selected_tab->NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS);
  }
  else
    View::Focus();  // Will focus the RootView window (so we still get keyboard
                    // messages).
}

void TabbedPane::PaintFocusBorder(gfx::Canvas* canvas) {
  if (NativeViewHost::kRenderNativeControlFocus)
    View::PaintFocusBorder(canvas);
}

bool TabbedPane::GetAccessibleRole(AccessibilityTypes::Role* role) {
  DCHECK(role);

  *role = AccessibilityTypes::ROLE_PAGETABLIST;
  return true;
}

gfx::Size TabbedPane::GetPreferredSize() {
  return native_tabbed_pane_ ?
      native_tabbed_pane_->GetPreferredSize() : gfx::Size();
}

}  // namespace views
<commit_msg>Fix code path in TabbedPane::RemoveTabAtIndex()<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/tabbed_pane/tabbed_pane.h"

#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "views/controls/native/native_view_host.h"
#include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h"

namespace views {

// static
const char TabbedPane::kViewClassName[] = "views/TabbedPane";

TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) {
  SetFocusable(true);
}

TabbedPane::~TabbedPane() {
}

void TabbedPane::SetListener(Listener* listener) {
  listener_ = listener;
}

void TabbedPane::AddTab(const std::wstring& title, View* contents) {
  native_tabbed_pane_->AddTab(title, contents);
  PreferredSizeChanged();
}

void TabbedPane::AddTabAtIndex(int index,
                               const std::wstring& title,
                               View* contents,
                               bool select_if_first_tab) {
  native_tabbed_pane_->AddTabAtIndex(index, title, contents,
                                     select_if_first_tab);
  contents->SetAccessibleName(title);
  PreferredSizeChanged();
}

int TabbedPane::GetSelectedTabIndex() {
  return native_tabbed_pane_->GetSelectedTabIndex();
}

View* TabbedPane::GetSelectedTab() {
  return native_tabbed_pane_->GetSelectedTab();
}

View* TabbedPane::RemoveTabAtIndex(int index) {
  View* tab = native_tabbed_pane_->RemoveTabAtIndex(index);
  PreferredSizeChanged();
  return tab;
}

void TabbedPane::SelectTabAt(int index) {
  native_tabbed_pane_->SelectTabAt(index);
}

int TabbedPane::GetTabCount() {
  return native_tabbed_pane_->GetTabCount();
}

void TabbedPane::CreateWrapper() {
  native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this);
}

// View overrides:
std::string TabbedPane::GetClassName() const {
  return kViewClassName;
}

void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_tabbed_pane_) {
    CreateWrapper();
    AddChildView(native_tabbed_pane_->GetView());
    LoadAccelerators();
  }
}

bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) {
  // We only accept Ctrl+Tab keyboard events.
  DCHECK(accelerator.GetKeyCode() ==
      base::VKEY_TAB && accelerator.IsCtrlDown());

  int tab_count = GetTabCount();
  if (tab_count <= 1)
    return false;
  int selected_tab_index = GetSelectedTabIndex();
  int next_tab_index = accelerator.IsShiftDown() ?
      (selected_tab_index - 1) % tab_count :
      (selected_tab_index + 1) % tab_count;
  // Wrap around.
  if (next_tab_index < 0)
    next_tab_index += tab_count;
  SelectTabAt(next_tab_index);
  return true;
}

void TabbedPane::LoadAccelerators() {
  // Ctrl+Shift+Tab
  AddAccelerator(views::Accelerator(base::VKEY_TAB, true, true, false));
  // Ctrl+Tab
  AddAccelerator(views::Accelerator(base::VKEY_TAB, false, true, false));
}

void TabbedPane::Layout() {
  if (native_tabbed_pane_)
    native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height());
}

void TabbedPane::Focus() {
  // Forward the focus to the wrapper.
  if (native_tabbed_pane_) {
    native_tabbed_pane_->SetFocus();

    View* selected_tab = GetSelectedTab();
    if (selected_tab)
       selected_tab->NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS);
  }
  else
    View::Focus();  // Will focus the RootView window (so we still get keyboard
                    // messages).
}

void TabbedPane::PaintFocusBorder(gfx::Canvas* canvas) {
  if (NativeViewHost::kRenderNativeControlFocus)
    View::PaintFocusBorder(canvas);
}

bool TabbedPane::GetAccessibleRole(AccessibilityTypes::Role* role) {
  DCHECK(role);

  *role = AccessibilityTypes::ROLE_PAGETABLIST;
  return true;
}

gfx::Size TabbedPane::GetPreferredSize() {
  return native_tabbed_pane_ ?
      native_tabbed_pane_->GetPreferredSize() : gfx::Size();
}

}  // namespace views
<|endoftext|>