<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Sergey Lisitsyn
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/preprocessor/HessianLocallyLinearEmbedding.h>
#ifdef HAVE_LAPACK
#include <shogun/mathematics/arpack.h>
#include <shogun/mathematics/lapack.h>
#include <shogun/lib/common.h>
#include <shogun/mathematics/Math.h>
#include <shogun/io/SGIO.h>
#include <shogun/distance/EuclidianDistance.h>
#include <shogun/lib/Signal.h>

using namespace shogun;

CHessianLocallyLinearEmbedding::CHessianLocallyLinearEmbedding() :
		CLocallyLinearEmbedding()
{
}

CHessianLocallyLinearEmbedding::~CHessianLocallyLinearEmbedding()
{
}

bool CHessianLocallyLinearEmbedding::init(CFeatures* features)
{
	return true;
}

void CHessianLocallyLinearEmbedding::cleanup()
{
}

SGMatrix<float64_t> CHessianLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* features)
{
	// shorthand for simplefeatures
	CSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*) features;
	ASSERT(simple_features);

	// get dimensionality and number of vectors of data
	int32_t dim = simple_features->get_num_features();
	ASSERT(m_target_dim<=dim);
	int32_t N = simple_features->get_num_vectors();
	ASSERT(m_k<N);

	// loop variables
	int32_t i,j,k,l;

	int32_t dp = m_target_dim*(m_target_dim+1)/2;
	ASSERT(m_k>=(1+m_target_dim+dp));

	// compute distance matrix
	CDistance* distance = new CEuclidianDistance(simple_features,simple_features);
	SGMatrix<int32_t> neighborhood_matrix = get_neighborhood_matrix(distance);

	// init W (weight) matrix
	float64_t* W_matrix = SG_MALLOC(float64_t, N*N);
	for (i=0; i<N*N; i++)
		W_matrix[i] = 0.0;

	// init matrices and norm factor to be used
	float64_t* local_feature_matrix = SG_MALLOC(float64_t, m_k*dim);
	float64_t* s_values_vector = SG_MALLOC(float64_t, dim);
	float64_t* tau = SG_MALLOC(float64_t, CMath::min((1+m_target_dim+dp),m_k));
	float64_t* mean_vector = SG_MALLOC(float64_t, dim);
	float64_t* q_matrix = SG_MALLOC(float64_t, m_k*m_k);
	float64_t* w_sum_vector = SG_MALLOC(float64_t, dp);

	// Yi
	float64_t* Yi_matrix = SG_MALLOC(float64_t, m_k*(1+m_target_dim+dp));
	// get feature matrix
	SGMatrix<float64_t> feature_matrix = simple_features->get_feature_matrix();

	for (i=0; i<N && !(CSignal::cancel_computations()); i++)
	{
		// Yi(:,0) = 1
		for (j=0; j<m_k; j++)
			Yi_matrix[j] = 1.0;

		// fill mean vector with zeros
		for (j=0; j<dim; j++)
			mean_vector[j] = 0.0;

		// compute local feature matrix containing neighbors of i-th vector
		for (j=0; j<m_k; j++)
		{
			for (k=0; k<dim; k++)
			{
				local_feature_matrix[j*dim+k] = feature_matrix.matrix[neighborhood_matrix.matrix[j*N+i]*dim+k];
				mean_vector[k] += local_feature_matrix[j*dim+k];
			}
		}

		// compute mean
		for (j=0; j<dim; j++)
			mean_vector[j] /= m_k;

		// center feature vectors by mean
		for (j=0; j<m_k; j++)
		{
			for (k=0; k<dim; k++)
				local_feature_matrix[j*dim+k] -= mean_vector[k];
		}

		int32_t info = 0;
		// find right eigenvectors of local_feature_matrix
		wrap_dgesvd('N','O', dim,m_k,local_feature_matrix,dim,
		                     s_values_vector,
		                     NULL,1, NULL,1, &info);
		ASSERT(info==0);

		// Yi(0:m_k,1:1+m_target_dim) = Vh(0:m_k, 0:target_dim)
		for (j=0; j<m_target_dim; j++)
		{
			for (k=0; k<m_k; k++)
				Yi_matrix[(j+1)*m_k+k] = local_feature_matrix[k*dim+j];
		}

		int32_t ct = 0;

		// construct 2nd order hessian approx
		for (j=0; j<m_target_dim; j++)
		{
			for (k=0; k<m_target_dim-j; k++)
			{
				for (l=0; l<m_k; l++)
				{
					Yi_matrix[(ct+k+1+m_target_dim)*m_k+l] = Yi_matrix[(j+1)*m_k+l]*Yi_matrix[(j+k+1)*m_k+l];
				}
			}
			ct += ct + m_target_dim - j;
		}

		// perform QR factorization
		wrap_dgeqrf(m_k,(1+m_target_dim+dp),Yi_matrix,m_k,tau,&info);
		ASSERT(info==0);
		wrap_dorgqr(m_k,(1+m_target_dim+dp),CMath::min((1+m_target_dim+dp),m_k),Yi_matrix,m_k,tau,&info);
		ASSERT(info==0);

		float64_t* Pii = (Yi_matrix+m_k*(1+m_target_dim));

		for (j=0; j<dp; j++)
		{
			w_sum_vector[j] = 0.0;
			for (k=0; k<m_k; k++)
			{
				w_sum_vector[j] += Pii[j*m_k+k];
			}
			if (w_sum_vector[j]<0.001)
				w_sum_vector[j] = 1.0;
			for (k=0; k<m_k; k++)
				Pii[j*m_k+k] /= w_sum_vector[j];
		}

		cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans,
		            m_k,m_k,dp,
		            1.0,Pii,m_k,
		                Pii,m_k,
		            0.0,q_matrix,m_k);

		for (j=0; j<m_k; j++)
		{
			for (k=0; k<m_k; k++)
				W_matrix[N*neighborhood_matrix.matrix[k*N+i]+neighborhood_matrix.matrix[j*N+i]] += q_matrix[j*m_k+k];
		}
	}

	// clean
	SG_FREE(Yi_matrix);
	SG_FREE(s_values_vector);
	SG_FREE(mean_vector);
	neighborhood_matrix.destroy_matrix();
	SG_FREE(local_feature_matrix);
	SG_FREE(q_matrix);

	// finally construct embedding
	SGMatrix<float64_t> W_sgmatrix = SGMatrix<float64_t>(W_matrix,N,N);
	simple_features->set_feature_matrix(find_null_space(W_sgmatrix,m_target_dim,false));
	W_sgmatrix.destroy_matrix();

	return simple_features->get_feature_matrix();
}

SGVector<float64_t> CHessianLocallyLinearEmbedding::apply_to_feature_vector(SGVector<float64_t> vector)
{
	SG_NOTIMPLEMENTED;
	return vector;
}

#endif /* HAVE_LAPACK */
<commit_msg>Fixed memleak in HLLE<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Sergey Lisitsyn
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/preprocessor/HessianLocallyLinearEmbedding.h>
#ifdef HAVE_LAPACK
#include <shogun/mathematics/arpack.h>
#include <shogun/mathematics/lapack.h>
#include <shogun/lib/common.h>
#include <shogun/mathematics/Math.h>
#include <shogun/io/SGIO.h>
#include <shogun/distance/EuclidianDistance.h>
#include <shogun/lib/Signal.h>

using namespace shogun;

CHessianLocallyLinearEmbedding::CHessianLocallyLinearEmbedding() :
		CLocallyLinearEmbedding()
{
}

CHessianLocallyLinearEmbedding::~CHessianLocallyLinearEmbedding()
{
}

bool CHessianLocallyLinearEmbedding::init(CFeatures* features)
{
	return true;
}

void CHessianLocallyLinearEmbedding::cleanup()
{
}

SGMatrix<float64_t> CHessianLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* features)
{
	// shorthand for simplefeatures
	CSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*) features;
	ASSERT(simple_features);

	// get dimensionality and number of vectors of data
	int32_t dim = simple_features->get_num_features();
	ASSERT(m_target_dim<=dim);
	int32_t N = simple_features->get_num_vectors();
	ASSERT(m_k<N);

	// loop variables
	int32_t i,j,k,l;

	int32_t dp = m_target_dim*(m_target_dim+1)/2;
	ASSERT(m_k>=(1+m_target_dim+dp));

	// compute distance matrix
	CDistance* distance = new CEuclidianDistance(simple_features,simple_features);
	SGMatrix<int32_t> neighborhood_matrix = get_neighborhood_matrix(distance);

	// init W (weight) matrix
	float64_t* W_matrix = SG_MALLOC(float64_t, N*N);
	for (i=0; i<N*N; i++)
		W_matrix[i] = 0.0;

	// init matrices and norm factor to be used
	float64_t* local_feature_matrix = SG_MALLOC(float64_t, m_k*dim);
	float64_t* s_values_vector = SG_MALLOC(float64_t, dim);
	float64_t* tau = SG_MALLOC(float64_t, CMath::min((1+m_target_dim+dp),m_k));
	float64_t* mean_vector = SG_MALLOC(float64_t, dim);
	float64_t* q_matrix = SG_MALLOC(float64_t, m_k*m_k);
	float64_t* w_sum_vector = SG_MALLOC(float64_t, dp);

	// Yi
	float64_t* Yi_matrix = SG_CALLOC(float64_t, m_k*(1+m_target_dim+dp));
	// get feature matrix
	SGMatrix<float64_t> feature_matrix = simple_features->get_feature_matrix();

	for (i=0; i<N && !(CSignal::cancel_computations()); i++)
	{
		// Yi(:,0) = 1
		for (j=0; j<m_k; j++)
			Yi_matrix[j] = 1.0;

		// fill mean vector with zeros
		for (j=0; j<dim; j++)
			mean_vector[j] = 0.0;

		// compute local feature matrix containing neighbors of i-th vector
		for (j=0; j<m_k; j++)
		{
			for (k=0; k<dim; k++)
			{
				local_feature_matrix[j*dim+k] = feature_matrix.matrix[neighborhood_matrix.matrix[j*N+i]*dim+k];
				mean_vector[k] += local_feature_matrix[j*dim+k];
			}
		}

		// compute mean
		for (j=0; j<dim; j++)
			mean_vector[j] /= m_k;

		// center feature vectors by mean
		for (j=0; j<m_k; j++)
		{
			for (k=0; k<dim; k++)
				local_feature_matrix[j*dim+k] -= mean_vector[k];
		}

		int32_t info = 0;
		// find right eigenvectors of local_feature_matrix
		wrap_dgesvd('N','O', dim,m_k,local_feature_matrix,dim,
		                     s_values_vector,
		                     NULL,1, NULL,1, &info);
		ASSERT(info==0);

		// Yi(0:m_k,1:1+m_target_dim) = Vh(0:m_k, 0:target_dim)
		for (j=0; j<m_target_dim; j++)
		{
			for (k=0; k<m_k; k++)
				Yi_matrix[(j+1)*m_k+k] = local_feature_matrix[k*dim+j];
		}

		int32_t ct = 0;

		// construct 2nd order hessian approx
		for (j=0; j<m_target_dim; j++)
		{
			for (k=0; k<m_target_dim-j; k++)
			{
				for (l=0; l<m_k; l++)
				{
					Yi_matrix[(ct+k+1+m_target_dim)*m_k+l] = Yi_matrix[(j+1)*m_k+l]*Yi_matrix[(j+k+1)*m_k+l];
				}
			}
			ct += ct + m_target_dim - j;
		}

		// perform QR factorization
		wrap_dgeqrf(m_k,(1+m_target_dim+dp),Yi_matrix,m_k,tau,&info);
		ASSERT(info==0);
		wrap_dorgqr(m_k,(1+m_target_dim+dp),CMath::min((1+m_target_dim+dp),m_k),Yi_matrix,m_k,tau,&info);
		ASSERT(info==0);

		float64_t* Pii = (Yi_matrix+m_k*(1+m_target_dim));

		for (j=0; j<dp; j++)
		{
			w_sum_vector[j] = 0.0;
			for (k=0; k<m_k; k++)
			{
				w_sum_vector[j] += Pii[j*m_k+k];
			}
			if (w_sum_vector[j]<0.001)
				w_sum_vector[j] = 1.0;
			for (k=0; k<m_k; k++)
				Pii[j*m_k+k] /= w_sum_vector[j];
		}

		cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans,
		            m_k,m_k,dp,
		            1.0,Pii,m_k,
		                Pii,m_k,
		            0.0,q_matrix,m_k);

		for (j=0; j<m_k; j++)
		{
			for (k=0; k<m_k; k++)
				W_matrix[N*neighborhood_matrix.matrix[k*N+i]+neighborhood_matrix.matrix[j*N+i]] += q_matrix[j*m_k+k];
		}
	}

	// clean
	SG_FREE(Yi_matrix);
	SG_FREE(s_values_vector);
	SG_FREE(mean_vector);
	SG_FREE(tau);
	SG_FREE(w_sum_vector);
	neighborhood_matrix.destroy_matrix();
	SG_FREE(local_feature_matrix);
	SG_FREE(q_matrix);

	// finally construct embedding
	SGMatrix<float64_t> W_sgmatrix = SGMatrix<float64_t>(W_matrix,N,N);
	simple_features->set_feature_matrix(find_null_space(W_sgmatrix,m_target_dim,false));
	W_sgmatrix.destroy_matrix();

	return simple_features->get_feature_matrix();
}

SGVector<float64_t> CHessianLocallyLinearEmbedding::apply_to_feature_vector(SGVector<float64_t> vector)
{
	SG_NOTIMPLEMENTED;
	return vector;
}

#endif /* HAVE_LAPACK */
<|endoftext|>


<commit_before>#include "apps/HelloTensorflowFreeRTOS/hello_world_model.h"
#include "libs/nxp/rt1176-sdk/board.h"
#include "libs/nxp/rt1176-sdk/peripherals.h"
#include "libs/nxp/rt1176-sdk/pin_mux.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/all_ops_resolver.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/micro_error_reporter.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/micro_interpreter.h"

#include <cstdio>

extern "C" void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName) {
    printf("Stack overflow in %s\r\n", pcTaskName);
}

namespace {
tflite::ErrorReporter *error_reporter = nullptr;
const tflite::Model *model = nullptr;
tflite::MicroInterpreter *interpreter = nullptr;
TfLiteTensor *input = nullptr;
TfLiteTensor *output = nullptr;

int inference_count = 0;
const int kInferencesPerCycle = 1000;
const float kXrange = 2.f * 3.14159265359f;

const int kModelArenaSize = 4096;
const int kExtraArenaSize = 4096;
const int kTensorArenaSize = kModelArenaSize + kExtraArenaSize;
uint8_t tensor_arena[kTensorArenaSize] __attribute__((aligned(16)));
}  // namespace

static void loop() {
    float position = static_cast<float>(inference_count) /
                     static_cast<float>(kInferencesPerCycle);
    float x_val = position * kXrange;

    input->data.f[0] = x_val;

    TfLiteStatus invoke_status = interpreter->Invoke();
    if (invoke_status != kTfLiteOk) {
        TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed on x_val: %f",
                static_cast<double>(x_val));
        return;
    }

    float y_val = output->data.f[0];

    TF_LITE_REPORT_ERROR(error_reporter, "x_val: %f y_val: %f",
        static_cast<double>(x_val),
        static_cast<double>(y_val));

    ++inference_count;
    if (inference_count >= kInferencesPerCycle) {
        inference_count = 0;
    }
}
static void hello_task(void *param) {
    printf("Starting inference task...\r\n");
    while (true) {
        loop();
        taskYIELD();
    }
}

extern "C" void app_main(void *param) {
    static tflite::MicroErrorReporter micro_error_reporter;
    error_reporter = &micro_error_reporter;
    TF_LITE_REPORT_ERROR(error_reporter, "HelloTensorflowFreeRTOS!");

    model = tflite::GetModel(g_model);
    if (model->version() != TFLITE_SCHEMA_VERSION) {
        TF_LITE_REPORT_ERROR(error_reporter,
            "Model schema version is %d, supported is %d",
            model->version(), TFLITE_SCHEMA_VERSION);
        vTaskSuspend(nullptr);
    }

    static tflite::MicroMutableOpResolver<3> resolver(error_reporter);
    resolver.AddQuantize();
    resolver.AddDequantize();
    resolver.AddFullyConnected();
    static tflite::MicroInterpreter static_interpreter(
        model, resolver, tensor_arena, kTensorArenaSize, error_reporter);
    interpreter = &static_interpreter;

    TfLiteStatus allocate_status = interpreter->AllocateTensors();
    if (allocate_status != kTfLiteOk) {
        TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors failed.");
        vTaskSuspend(nullptr);
    }

    input = interpreter->input(0);
    output = interpreter->output(0);

    int ret;
    // High water mark testing showed that this task consumes about 218 words.
    // Set our stack size sufficiently large to accomodate.
    ret = xTaskCreate(hello_task, "HelloTask", configMINIMAL_STACK_SIZE * 3, nullptr, configMAX_PRIORITIES - 1, nullptr);
    if (ret != pdPASS) {
        printf("Failed to start HelloTask\r\n");
    }
    while (true) {
        taskYIELD();
    }
}
<commit_msg>Format HelloTensorflowFreeRTOS app<commit_after>#include <cstdio>

#include "apps/HelloTensorflowFreeRTOS/hello_world_model.h"
#include "libs/nxp/rt1176-sdk/board.h"
#include "libs/nxp/rt1176-sdk/peripherals.h"
#include "libs/nxp/rt1176-sdk/pin_mux.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/all_ops_resolver.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/micro_error_reporter.h"
#include "third_party/tflite-micro/tensorflow/lite/micro/micro_interpreter.h"

extern "C" void vApplicationStackOverflowHook(TaskHandle_t xTask,
                                              char* pcTaskName) {
    printf("Stack overflow in %s\r\n", pcTaskName);
}

namespace {
tflite::ErrorReporter* error_reporter = nullptr;
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;

int inference_count = 0;
const int kInferencesPerCycle = 1000;
const float kXrange = 2.f * 3.14159265359f;

const int kModelArenaSize = 4096;
const int kExtraArenaSize = 4096;
const int kTensorArenaSize = kModelArenaSize + kExtraArenaSize;
uint8_t tensor_arena[kTensorArenaSize] __attribute__((aligned(16)));
}  // namespace

static void loop() {
    float position = static_cast<float>(inference_count) /
                     static_cast<float>(kInferencesPerCycle);
    float x_val = position * kXrange;

    input->data.f[0] = x_val;

    TfLiteStatus invoke_status = interpreter->Invoke();
    if (invoke_status != kTfLiteOk) {
        TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed on x_val: %f",
                             static_cast<double>(x_val));
        return;
    }

    float y_val = output->data.f[0];

    TF_LITE_REPORT_ERROR(error_reporter, "x_val: %f y_val: %f",
                         static_cast<double>(x_val),
                         static_cast<double>(y_val));

    ++inference_count;
    if (inference_count >= kInferencesPerCycle) {
        inference_count = 0;
    }
}
static void hello_task(void* param) {
    printf("Starting inference task...\r\n");
    while (true) {
        loop();
        taskYIELD();
    }
}

extern "C" void app_main(void* param) {
    static tflite::MicroErrorReporter micro_error_reporter;
    error_reporter = &micro_error_reporter;
    TF_LITE_REPORT_ERROR(error_reporter, "HelloTensorflowFreeRTOS!");

    model = tflite::GetModel(g_model);
    if (model->version() != TFLITE_SCHEMA_VERSION) {
        TF_LITE_REPORT_ERROR(error_reporter,
                             "Model schema version is %d, supported is %d",
                             model->version(), TFLITE_SCHEMA_VERSION);
        vTaskSuspend(nullptr);
    }

    static tflite::MicroMutableOpResolver<3> resolver(error_reporter);
    resolver.AddQuantize();
    resolver.AddDequantize();
    resolver.AddFullyConnected();
    static tflite::MicroInterpreter static_interpreter(
        model, resolver, tensor_arena, kTensorArenaSize, error_reporter);
    interpreter = &static_interpreter;

    TfLiteStatus allocate_status = interpreter->AllocateTensors();
    if (allocate_status != kTfLiteOk) {
        TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors failed.");
        vTaskSuspend(nullptr);
    }

    input = interpreter->input(0);
    output = interpreter->output(0);

    int ret;
    // High water mark testing showed that this task consumes about 218 words.
    // Set our stack size sufficiently large to accomodate.
    ret = xTaskCreate(hello_task, "HelloTask", configMINIMAL_STACK_SIZE * 3,
                      nullptr, configMAX_PRIORITIES - 1, nullptr);
    if (ret != pdPASS) {
        printf("Failed to start HelloTask\r\n");
    }
    while (true) {
        taskYIELD();
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

 /*
 * This sample implements a separable convolution filter
 * of a 2D image with an arbitrary kernel.
 */

// Utilities and system includes
#include <shrUtils.h>
#include <shrQATest.h>
#include <cutil_inline.h>

#include "convolutionSeparable_common.h"

////////////////////////////////////////////////////////////////////////////////
// Reference CPU convolution
////////////////////////////////////////////////////////////////////////////////
extern "C" void convolutionRowCPU(
    float *h_Result,
    float *h_Data,
    float *h_Kernel,
    int imageW,
    int imageH,
    int kernelR
);

extern "C" void convolutionColumnCPU(
    float *h_Result,
    float *h_Data,
    float *h_Kernel,
    int imageW,
    int imageH,
    int kernelR
);

void ParseArguments(int argc, char** argv, int& sizeW, int& sizeH)
{
    for (int i = 0; i < argc; ++i) {
        if (strcmp(argv[i], "--size") == 0 ||
            strcmp(argv[i], "-size") == 0)
        {
            sizeW = atoi(argv[i+1]);
            sizeH = sizeW;
        }
        if (strcmp(argv[i], "--sizeW") == 0 ||
            strcmp(argv[i], "-sizeW") == 0)
        {
            sizeW = atoi(argv[i+1]);
        }
        if (strcmp(argv[i], "--sizeH") == 0 ||
            strcmp(argv[i], "-sizeH") == 0)
        {
            sizeH = atoi(argv[i+1]);
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
// Main program
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    shrQAStart(argc, argv);

    // start logs
    shrSetLogFileName ("convolutionSeparable.txt");
    shrLog("%s Starting...\n\n", argv[0]);

    float
        *h_Kernel,
        *h_Input,
        *h_Buffer,
        *h_OutputCPU,
        *h_OutputGPU;

    float
        *d_Input,
        *d_Output,
        *d_Buffer;

    int sizeW = 3072/8;
    int sizeH = 3072/16;
    ParseArguments(argc,argv,sizeW,sizeH);

    const int imageW = sizeW;
    const int imageH = sizeH;
    const int iterations = 1;

    unsigned int hTimer;

    //Use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if ( shrCheckCmdLineFlag(argc, (const char **)argv, "device") )
        cutilDeviceInit(argc, argv);
    else
        cudaSetDevice( cutGetMaxGflopsDeviceId() );

    cutilCheckError(cutCreateTimer(&hTimer));

    shrLog("Image Width x Height = %i x %i\n\n", imageW, imageH);
    shrLog("Allocating and initializing host arrays...\n");
        h_Kernel    = (float *)malloc(KERNEL_LENGTH * sizeof(float));
        h_Input     = (float *)malloc(imageW * imageH * sizeof(float));
        h_Buffer    = (float *)malloc(imageW * imageH * sizeof(float));
        h_OutputCPU = (float *)malloc(imageW * imageH * sizeof(float));
        h_OutputGPU = (float *)malloc(imageW * imageH * sizeof(float));
        srand(200);
        for(unsigned int i = 0; i < KERNEL_LENGTH; i++)
            h_Kernel[i] = (float)(rand() % 16);
        for(unsigned i = 0; i < imageW * imageH; i++)
            h_Input[i] = (float)(rand() % 16);

    shrLog("Allocating and initializing CUDA arrays...\n");
        cutilSafeCall( cudaMalloc((void **)&d_Input,   imageW * imageH * sizeof(float)) );
        cutilSafeCall( cudaMalloc((void **)&d_Output,  imageW * imageH * sizeof(float)) );
        cutilSafeCall( cudaMalloc((void **)&d_Buffer , imageW * imageH * sizeof(float)) );

        setConvolutionKernel(h_Kernel);
        cutilSafeCall( cudaMemcpy(d_Input, h_Input, imageW * imageH * sizeof(float), cudaMemcpyHostToDevice) );

    shrLog("Running GPU convolution (%u identical iterations)...\n\n", iterations);
        for(int i = -1; i < iterations; i++){
            //i == -1 -- warmup iteration
            if(i == 0){
                cutilSafeCall( cutilDeviceSynchronize() );
                cutilCheckError( cutResetTimer(hTimer) );
                cutilCheckError( cutStartTimer(hTimer) );
            }

            convolutionRowsGPU(
                d_Buffer,
                d_Input,
                imageW,
                imageH
            );

            convolutionColumnsGPU(
                d_Output,
                d_Buffer,
                imageW,
                imageH
            );
        }
        cutilSafeCall( cutilDeviceSynchronize() );
        cutilCheckError(cutStopTimer(hTimer));
        double gpuTime = 0.001 * cutGetTimerValue(hTimer) / (double)iterations;
    shrLogEx(LOGBOTH | MASTER, 0, "convolutionSeparable, Throughput = %.4f MPixels/sec, Time = %.5f s, Size = %u Pixels, NumDevsUsed = %i, Workgroup = %u\n",
        (1.0e-6 * (double)(imageW * imageH)/ gpuTime), gpuTime, (imageW * imageH), 1, 0);

    shrLog("\nReading back GPU results...\n\n");
        cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, imageW * imageH * sizeof(float), cudaMemcpyDeviceToHost) );

    shrLog("Checking the results...\n");
        shrLog(" ...running convolutionRowCPU()\n");
        convolutionRowCPU(
            h_Buffer,
            h_Input,
            h_Kernel,
            imageW,
            imageH,
            KERNEL_RADIUS
        );

        shrLog(" ...running convolutionColumnCPU()\n");
        convolutionColumnCPU(
            h_OutputCPU,
            h_Buffer,
            h_Kernel,
            imageW,
            imageH,
            KERNEL_RADIUS
        );

        shrLog(" ...comparing the results\n");
        double sum = 0, delta = 0;
        for(unsigned i = 0; i < imageW * imageH; i++){
            delta += (h_OutputGPU[i] - h_OutputCPU[i]) * (h_OutputGPU[i] - h_OutputCPU[i]);
            sum   += h_OutputCPU[i] * h_OutputCPU[i];
        }
        double L2norm = sqrt(delta / sum);
        shrLog(" ...Relative L2 norm: %E\n\n", L2norm);
    shrLog((L2norm < 1e-6) ? "PASSED\n\n" : "FAILED\n\n");

    shrLog("Shutting down...\n");
        cutilSafeCall( cudaFree(d_Buffer ) );
        cutilSafeCall( cudaFree(d_Output) );
        cutilSafeCall( cudaFree(d_Input) );
        free(h_OutputGPU);
        free(h_OutputCPU);
        free(h_Buffer);
        free(h_Input);
        free(h_Kernel);

    cutilCheckError(cutDeleteTimer(hTimer));

    cutilDeviceReset();

    shrQAFinishExit(argc, (const char **)argv, ((L2norm < 1e-6) ? QA_PASSED : QA_FAILED) );
}
<commit_msg>making convolution seperabel identical<commit_after>/*
 * Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

 /*
 * This sample implements a separable convolution filter
 * of a 2D image with an arbitrary kernel.
 */

// Utilities and system includes
#include <shrUtils.h>
#include <shrQATest.h>
#include <cutil_inline.h>

#include "convolutionSeparable_common.h"

////////////////////////////////////////////////////////////////////////////////
// Reference CPU convolution
////////////////////////////////////////////////////////////////////////////////
extern "C" void convolutionRowCPU(
    float *h_Result,
    float *h_Data,
    float *h_Kernel,
    int imageW,
    int imageH,
    int kernelR
);

extern "C" void convolutionColumnCPU(
    float *h_Result,
    float *h_Data,
    float *h_Kernel,
    int imageW,
    int imageH,
    int kernelR
);

void ParseArguments(int argc, char** argv, int& sizeW, int& sizeH)
{
    for (int i = 0; i < argc; ++i) {
        if (strcmp(argv[i], "--size") == 0 ||
            strcmp(argv[i], "-size") == 0)
        {
            sizeW = atoi(argv[i+1]);
            sizeH = sizeW;
        }
        if (strcmp(argv[i], "--sizeW") == 0 ||
            strcmp(argv[i], "-sizeW") == 0)
        {
            sizeW = atoi(argv[i+1]);
        }
        if (strcmp(argv[i], "--sizeH") == 0 ||
            strcmp(argv[i], "-sizeH") == 0)
        {
            sizeH = atoi(argv[i+1]);
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
// Main program
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    shrQAStart(argc, argv);

    // start logs
    shrSetLogFileName ("convolutionSeparable.txt");
    shrLog("%s Starting...\n\n", argv[0]);

    float
        *h_Kernel,
        *h_Input,
        *h_Buffer,
        *h_OutputCPU,
        *h_OutputGPU;

    float
        *d_Input,
        *d_Output,
        *d_Buffer;

    int sizeW = 3072/8;
    int sizeH = 3072/16;
    ParseArguments(argc,argv,sizeW,sizeH);

    const int imageW = sizeW;
    const int imageH = sizeH;
    const int iterations = 1;

    unsigned int hTimer;

    //Use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if ( shrCheckCmdLineFlag(argc, (const char **)argv, "device") )
        cutilDeviceInit(argc, argv);
    else
        cudaSetDevice( cutGetMaxGflopsDeviceId() );

    cutilCheckError(cutCreateTimer(&hTimer));

    shrLog("Image Width x Height = %i x %i\n\n", imageW, imageH);
    shrLog("Allocating and initializing host arrays...\n");
        h_Kernel    = (float *)malloc(KERNEL_LENGTH * sizeof(float));
        h_Input     = (float *)malloc(imageW * imageH * sizeof(float));
        h_Buffer    = (float *)malloc(imageW * imageH * sizeof(float));
        h_OutputCPU = (float *)malloc(imageW * imageH * sizeof(float));
        h_OutputGPU = (float *)malloc(imageW * imageH * sizeof(float));
        srand(200);
        for(unsigned int i = 0; i < KERNEL_LENGTH; i++)
            h_Kernel[i] = (float)(rand() % 16);
        for(unsigned i = 0; i < imageW * imageH; i++)
            h_Input[i] = (float)(rand() % 16);

    shrLog("Allocating and initializing CUDA arrays...\n");
        cutilSafeCall( cudaMalloc((void **)&d_Input,   imageW * imageH * sizeof(float)) );
        cutilSafeCall( cudaMalloc((void **)&d_Output,  imageW * imageH * sizeof(float)) );
        cutilSafeCall( cudaMalloc((void **)&d_Buffer , imageW * imageH * sizeof(float)) );

        setConvolutionKernel(h_Kernel);
        cutilSafeCall( cudaMemcpy(d_Input, h_Input, imageW * imageH * sizeof(float), cudaMemcpyHostToDevice) );

    shrLog("Running GPU convolution (%u identical iterations)...\n\n", iterations);
        for(int i = 0; i < iterations; i++){
            //i == -1 -- warmup iteration
            if(i == 0){
                cutilSafeCall( cutilDeviceSynchronize() );
                cutilCheckError( cutResetTimer(hTimer) );
                cutilCheckError( cutStartTimer(hTimer) );
            }

            convolutionRowsGPU(
                d_Buffer,
                d_Input,
                imageW,
                imageH
            );

            convolutionColumnsGPU(
                d_Output,
                d_Buffer,
                imageW,
                imageH
            );
        }
        cutilSafeCall( cutilDeviceSynchronize() );
        cutilCheckError(cutStopTimer(hTimer));
        double gpuTime = 0.001 * cutGetTimerValue(hTimer) / (double)iterations;
    shrLogEx(LOGBOTH | MASTER, 0, "convolutionSeparable, Throughput = %.4f MPixels/sec, Time = %.5f s, Size = %u Pixels, NumDevsUsed = %i, Workgroup = %u\n",
        (1.0e-6 * (double)(imageW * imageH)/ gpuTime), gpuTime, (imageW * imageH), 1, 0);

    shrLog("\nReading back GPU results...\n\n");
        cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, imageW * imageH * sizeof(float), cudaMemcpyDeviceToHost) );

    shrLog("Checking the results...\n");
        shrLog(" ...running convolutionRowCPU()\n");
        convolutionRowCPU(
            h_Buffer,
            h_Input,
            h_Kernel,
            imageW,
            imageH,
            KERNEL_RADIUS
        );

        shrLog(" ...running convolutionColumnCPU()\n");
        convolutionColumnCPU(
            h_OutputCPU,
            h_Buffer,
            h_Kernel,
            imageW,
            imageH,
            KERNEL_RADIUS
        );

        shrLog(" ...comparing the results\n");
        double sum = 0, delta = 0;
        for(unsigned i = 0; i < imageW * imageH; i++){
            delta += (h_OutputGPU[i] - h_OutputCPU[i]) * (h_OutputGPU[i] - h_OutputCPU[i]);
            sum   += h_OutputCPU[i] * h_OutputCPU[i];
        }
        double L2norm = sqrt(delta / sum);
        shrLog(" ...Relative L2 norm: %E\n\n", L2norm);
    shrLog((L2norm < 1e-6) ? "PASSED\n\n" : "FAILED\n\n");

    shrLog("Shutting down...\n");
        cutilSafeCall( cudaFree(d_Buffer ) );
        cutilSafeCall( cudaFree(d_Output) );
        cutilSafeCall( cudaFree(d_Input) );
        free(h_OutputGPU);
        free(h_OutputCPU);
        free(h_Buffer);
        free(h_Input);
        free(h_Kernel);

    cutilCheckError(cutDeleteTimer(hTimer));

    cutilDeviceReset();

    shrQAFinishExit(argc, (const char **)argv, ((L2norm < 1e-6) ? QA_PASSED : QA_FAILED) );
}
<|endoftext|>


<commit_before>#include "processhelper.h"
#include <QtTest>

const char ProcessHelper::Stamp = '%';
bool ProcessHelper::allGreen = true;

ProcessHelper::ProcessHelper(QObject *parent) :
	QObject(parent),
	process(new QProcess(this)),
	exitCode(EXIT_SUCCESS)
{
	process->setProgram(QStringLiteral(OUTDIR) + QStringLiteral("../../../../examples/backgroundprocess/DemoApp/DemoApp"));

	connect(process, &QProcess::errorOccurred,
			this, &ProcessHelper::errorOccurred);
	connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
			this, &ProcessHelper::finished);
}

void ProcessHelper::setExitCode(int code)
{
	exitCode = code;
}

void ProcessHelper::start(const QByteArrayList &commands, bool logpath, int timeout)
{
	QStringList s;
	foreach(auto c, commands)
		s.append(QString::fromUtf8(c));
	if(logpath)
		s.append({QStringLiteral("--logpath"), logPath()});
	process->setArguments(s);
	process->start();
	QVERIFY2(process->waitForStarted(5000), qUtf8Printable(process->errorString()));
	QThread::msleep(timeout);
}

void ProcessHelper::waitForFinished()
{
	if(!process->waitForFinished(5000)) {
		process->terminate();
		QFAIL("Process did not stop by itself");
	}
}

void ProcessHelper::verifyLog(const QByteArrayList &log, bool isError)
{
	allGreen = false;

	if(isError) {
		auto err = process->readAllStandardError();
		QBuffer buffer(&err);
		buffer.open(QIODevice::ReadOnly | QIODevice::Text);
		testLog(log, &buffer);
		buffer.close();
	} else {
		auto out = process->readAllStandardOutput();
		QBuffer buffer(&out);
		buffer.open(QIODevice::ReadOnly | QIODevice::Text);
		testLog(log, &buffer);
		buffer.close();
	}

	if(!allGreen)
		qDebug() << "on arguments:" << process->arguments();
}

void ProcessHelper::verifyLogEmpty(bool isError)
{
	verifyLog(QByteArrayList(), isError);
}

void ProcessHelper::waitForFinished(const QList<ProcessHelper *> &helpers)
{
	foreach (auto h, helpers)
		h->waitForFinished();
}

void ProcessHelper::clearLog()
{
	auto logFile = logPath();
	if(QFile::exists(logFile))
		QVERIFY(QFile::remove(logFile));
}

void ProcessHelper::verifyMasterLog(const QByteArrayList &log)
{
	auto logFile = logPath();
	QFile file(logFile);
	QVERIFY(file.exists());
	QVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text), qUtf8Printable(file.errorString()));

	allGreen = false;
	testLog(log, &file);
	if(!allGreen)
		qDebug() << "on master log";

	file.close();
	QVERIFY(file.remove());

}

void ProcessHelper::errorOccurred(QProcess::ProcessError error)
{
	Q_UNUSED(error)
	QFAIL(qUtf8Printable(process->errorString()));
}

void ProcessHelper::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
	QCOMPARE(exitStatus, QProcess::NormalExit);
	QCOMPARE(exitCode, this->exitCode);
}

QString ProcessHelper::logPath()
{
	return QDir::current().absoluteFilePath(QStringLiteral("MasterTest.log"));
}

void ProcessHelper::testLog(const QByteArrayList &log, QIODevice *device)
{
	auto index = 0;
	while(!device->atEnd()) {
		auto logStr = device->readLine().trimmed();
		if(logStr.isEmpty())
			continue;

		QVERIFY2(index < log.size(), logStr.constData());
		auto testStr = log[index++];

		auto testSplit = testStr.split(Stamp);
		if(testSplit.size() == 2) {
			QVERIFY2(logStr.startsWith(testSplit[0]), logStr.constData());
			QVERIFY2(logStr.endsWith(testSplit[1]), logStr.constData());
		} else
			QCOMPARE(logStr, testStr);
	}
	QCOMPARE(index, log.size());
	allGreen = true;
}
<commit_msg>Revert "try different method"<commit_after>#include "processhelper.h"
#include <QtTest>

const char ProcessHelper::Stamp = '%';
bool ProcessHelper::allGreen = true;

ProcessHelper::ProcessHelper(QObject *parent) :
	QObject(parent),
	process(new QProcess(this)),
	exitCode(EXIT_SUCCESS)
{
	process->setProgram(QStringLiteral(OUTDIR) + QStringLiteral("../../../../examples/backgroundprocess/DemoApp/DemoApp"));

	connect(process, &QProcess::errorOccurred,
			this, &ProcessHelper::errorOccurred);
	connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
			this, &ProcessHelper::finished);
}

void ProcessHelper::setExitCode(int code)
{
	exitCode = code;
}

void ProcessHelper::start(const QByteArrayList &commands, bool logpath, int timeout)
{
	QStringList s;
	foreach(auto c, commands)
		s.append(QString::fromUtf8(c));
	if(logpath)
		s.append({QStringLiteral("--logpath"), logPath()});
	process->setArguments(s);
	process->start();
	QVERIFY2(process->waitForStarted(5000), qUtf8Printable(process->errorString()));
	QThread::msleep(timeout);
}

void ProcessHelper::waitForFinished()
{
	if(!process->waitForFinished(5000)) {
		process->terminate();
		QFAIL("Process did not stop by itself");
	}
}

void ProcessHelper::verifyLog(const QByteArrayList &log, bool isError)
{
	allGreen = false;

	if(isError) {
		auto err = process->readAllStandardError();
		QBuffer buffer(&err);
		buffer.open(QIODevice::ReadOnly | QIODevice::Text);
		testLog(log, &buffer);
		buffer.close();
	} else
		testLog(log, process);

	if(!allGreen)
		qDebug() << "on arguments:" << process->arguments();
}

void ProcessHelper::verifyLogEmpty(bool isError)
{
	verifyLog(QByteArrayList(), isError);
}

void ProcessHelper::waitForFinished(const QList<ProcessHelper *> &helpers)
{
	foreach (auto h, helpers)
		h->waitForFinished();
}

void ProcessHelper::clearLog()
{
	auto logFile = logPath();
	if(QFile::exists(logFile))
		QVERIFY(QFile::remove(logFile));
}

void ProcessHelper::verifyMasterLog(const QByteArrayList &log)
{
	auto logFile = logPath();
	QFile file(logFile);
	QVERIFY(file.exists());
	QVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text), qUtf8Printable(file.errorString()));

	allGreen = false;
	testLog(log, &file);
	if(!allGreen)
		qDebug() << "on master log";

	file.close();
	QVERIFY(file.remove());

}

void ProcessHelper::errorOccurred(QProcess::ProcessError error)
{
	Q_UNUSED(error)
	QFAIL(qUtf8Printable(process->errorString()));
}

void ProcessHelper::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
	QCOMPARE(exitStatus, QProcess::NormalExit);
	QCOMPARE(exitCode, this->exitCode);
}

QString ProcessHelper::logPath()
{
	return QDir::current().absoluteFilePath(QStringLiteral("MasterTest.log"));
}

void ProcessHelper::testLog(const QByteArrayList &log, QIODevice *device)
{
	auto index = 0;
	while(!device->atEnd()) {
		auto logStr = device->readLine().trimmed();
		if(logStr.isEmpty())
			continue;

		QVERIFY2(index < log.size(), logStr.constData());
		auto testStr = log[index++];

		auto testSplit = testStr.split(Stamp);
		if(testSplit.size() == 2) {
			QVERIFY2(logStr.startsWith(testSplit[0]), logStr.constData());
			QVERIFY2(logStr.endsWith(testSplit[1]), logStr.constData());
		} else
			QCOMPARE(logStr, testStr);
	}
	QCOMPARE(index, log.size());
	allGreen = true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"

namespace chrome {

namespace {

const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";

class TabCaptureApiTest : public ExtensionApiTest {
 public:
  TabCaptureApiTest() {}

  void AddExtensionToCommandLineWhitelist() {
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kWhitelistedExtensionID, kExtensionId);
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests_audio.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_EndToEnd DISABLED_EndToEnd
#else
#define MAYBE_EndToEnd EndToEnd
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif
#if defined(OS_MACOSX)
  // TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.
  // http://crbug.com/174640
  if (base::mac::IsOSSnowLeopard())
    return;
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "end_to_end.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest
#else
#define MAYBE_GetUserMediaTest GetUserMediaTest
#endif
// Test that we can't get tabCapture streams using GetUserMedia directly.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {
  ExtensionTestMessageListener listener("ready", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "get_user_media_test.html")) << message_;

  EXPECT_TRUE(listener.WaitUntilSatisfied());

  content::OpenURLParams params(GURL("about:blank"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();
  int render_process_id = rvh->GetProcess()->GetID();
  int routing_id = rvh->GetRoutingID();

  listener.Reply(base::StringPrintf("%i:%i", render_process_id, routing_id));

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission
#else
#define MAYBE_ActiveTabPermission ActiveTabPermission
#endif
// Make sure tabCapture.capture only works if the tab has been granted
// permission via an extension icon click or the extension is whitelisted.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {
  ExtensionTestMessageListener before_open_tab("ready1", true);
  ExtensionTestMessageListener before_grant_permission("ready2", true);
  ExtensionTestMessageListener before_open_new_tab("ready3", true);
  ExtensionTestMessageListener before_whitelist_extension("ready4", true);

  ASSERT_TRUE(RunExtensionSubtest(
      "tab_capture/experimental", "active_tab_permission_test.html"))
          << message_;

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());
  content::OpenURLParams params(GURL("http://google.com"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);
  before_open_tab.Reply("");

  // Grant permission and make sure capture succeeds.
  EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());
  ExtensionService* extension_service =
      Profile::FromBrowserContext(web_contents->GetBrowserContext())
          ->GetExtensionService();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(kExtensionId, false);
  extensions::TabHelper::FromWebContents(web_contents)
      ->active_tab_permission_granter()->GrantIfRequested(extension);
  before_grant_permission.Reply("");

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());
  browser()->OpenURL(params);
  before_open_new_tab.Reply("");

  // Add extension to whitelist and make sure capture succeeds.
  EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());
  AddExtensionToCommandLineWhitelist();
  before_whitelist_extension.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

}  // namespace chrome
<commit_msg>Disable TabCaptureApiTest.EndToEnd for Linux (non-Aura) debug builds.<commit_after>// Copyright (c) 2012 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 "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"

namespace chrome {

namespace {

const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";

class TabCaptureApiTest : public ExtensionApiTest {
 public:
  TabCaptureApiTest() {}

  void AddExtensionToCommandLineWhitelist() {
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kWhitelistedExtensionID, kExtensionId);
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests_audio.html")) << message_;
}

// http://crbug.com/177163 -- for OS_WIN debug build flakiness
// http://crbug.com/251863 -- for OS_LINUX (non-Aura) debug build flakiness
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_EndToEnd DISABLED_EndToEnd
#elif defined(OS_LINUX) && !defined(USE_AURA) && !defined(NDEBUG)
#define MAYBE_EndToEnd DISABLED_EndToEnd
#else
#define MAYBE_EndToEnd EndToEnd
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif
#if defined(OS_MACOSX)
  // TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.
  // http://crbug.com/174640
  if (base::mac::IsOSSnowLeopard())
    return;
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "end_to_end.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest
#else
#define MAYBE_GetUserMediaTest GetUserMediaTest
#endif
// Test that we can't get tabCapture streams using GetUserMedia directly.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {
  ExtensionTestMessageListener listener("ready", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "get_user_media_test.html")) << message_;

  EXPECT_TRUE(listener.WaitUntilSatisfied());

  content::OpenURLParams params(GURL("about:blank"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();
  int render_process_id = rvh->GetProcess()->GetID();
  int routing_id = rvh->GetRoutingID();

  listener.Reply(base::StringPrintf("%i:%i", render_process_id, routing_id));

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission
#else
#define MAYBE_ActiveTabPermission ActiveTabPermission
#endif
// Make sure tabCapture.capture only works if the tab has been granted
// permission via an extension icon click or the extension is whitelisted.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {
  ExtensionTestMessageListener before_open_tab("ready1", true);
  ExtensionTestMessageListener before_grant_permission("ready2", true);
  ExtensionTestMessageListener before_open_new_tab("ready3", true);
  ExtensionTestMessageListener before_whitelist_extension("ready4", true);

  ASSERT_TRUE(RunExtensionSubtest(
      "tab_capture/experimental", "active_tab_permission_test.html"))
          << message_;

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());
  content::OpenURLParams params(GURL("http://google.com"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);
  before_open_tab.Reply("");

  // Grant permission and make sure capture succeeds.
  EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());
  ExtensionService* extension_service =
      Profile::FromBrowserContext(web_contents->GetBrowserContext())
          ->GetExtensionService();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(kExtensionId, false);
  extensions::TabHelper::FromWebContents(web_contents)
      ->active_tab_permission_granter()->GrantIfRequested(extension);
  before_grant_permission.Reply("");

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());
  browser()->OpenURL(params);
  before_open_new_tab.Reply("");

  // Add extension to whitelist and make sure capture succeeds.
  EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());
  AddExtensionToCommandLineWhitelist();
  before_whitelist_extension.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

}  // namespace chrome
<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * 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 "valuesFactory.h"

#include <QtCore/QRect>

#include <qrutils/mathUtils/geometry.h>
#include <utils/objectsSet.h>
#include <utils/timelineInterface.h>

using namespace twoDModel::constraints::details;

const QString typeOfNull = "undefined";

ValuesFactory::ValuesFactory(Variables &variables, const Objects &objects, StatusReporter &status)
	: mVariables(variables)
	, mObjects(objects)
	, mStatus(status)
{
}

Value ValuesFactory::invalidValue() const
{
	return []() { return QVariant(); };
}

Value ValuesFactory::boolValue(bool value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::intValue(int value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::doubleValue(qreal value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::stringValue(const QString &value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::variableValue(const QString &name) const
{
	return [this, name]() {
		const QStringList parts = name.split('.');
		if (parts.isEmpty()) {
			reportError(QObject::tr("Requesting variable value with empty name"));
			return QVariant();
		}

		if (!mVariables.contains(parts.first())) {
			// We do not mind the situation when trying to read non-declared varible
			// because really can`t manage the order in which Qt will call event checking,
			// so some variables (for example counters) can be checked before setted.
			return QVariant();
		}

		return propertyChain(mVariables[parts.first()], parts.mid(1), parts.first());
	};
}

Value ValuesFactory::typeOf(const QString &objectId) const
{
	return [this, objectId]() {
		if (!mObjects.contains(objectId)) {
			return typeOfNull;
		}

		QObject const *object = mObjects[objectId];
		return object == nullptr ? typeOfNull : object->metaObject()->className();
	};
}

Value ValuesFactory::objectState(const QString &path) const
{
	return [this, path]() {
		const QStringList parts = path.split('.', QString::SkipEmptyParts);
		if (parts.isEmpty()) {
			reportError(QObject::tr("Object path is empty!"));
			return QVariant();
		}

		QString objectId = parts.first();
		if (!mObjects.contains(objectId)) {
			reportError(QObject::tr("No such object: %1").arg(objectId));
			return QVariant();
		}

		int lastObjectPart = 1;
		while (lastObjectPart < parts.count() && mObjects.contains(objectId + "." + parts[lastObjectPart])) {
			objectId += "." + parts[lastObjectPart];
			++lastObjectPart;
		}

		return propertyChain(QVariant::fromValue<QObject *>(mObjects[objectId]), parts.mid(lastObjectPart), objectId);
	};
}

Value ValuesFactory::timestamp(const utils::TimelineInterface &timeline) const
{
	return [&timeline]() { return timeline.timestamp(); };
}

Value ValuesFactory::unaryMinus(const Value &value) const
{
	return [value]() { return -value().toInt(); };
}

Value ValuesFactory::abs(const Value &value) const
{
	return [value]() { return qAbs(value().toInt()); };
}

Value ValuesFactory::sum(const Value &left, const Value &right) const
{
	return [left, right]() { return left().toInt() + right().toInt(); };
}

Value ValuesFactory::difference(const Value &left, const Value &right) const
{
	return [left, right]() { return left().toInt() - right().toInt(); };
}

Value ValuesFactory::max(const Value &left, const Value &right) const
{
	return [left, right]() { return qMax(left().toInt(), right().toInt()); };
}

Value ValuesFactory::min(const Value &left, const Value &right) const
{
	return [left, right]() { return qMin(left().toInt(), right().toInt()); };
}

Value ValuesFactory::distance(const Value &point1, const Value &point2) const
{
	return [point1, point2]() { return mathUtils::Geometry::distance(point1().toPoint(), point2().toPoint()); };
}

Value ValuesFactory::boundingRect(const Value &items) const
{
	return [this, items]() {
		bool empty = true;
		int xMin = INT_MAX;
		int yMin = INT_MAX;
		int xMax = INT_MIN;
		int yMax = INT_MIN;
		iterate(items(), [this, &xMin, &yMin, &xMax, &yMax, &empty](const QVariant &item) {
			bool hasBoundingRect{};
			const QRect boundingRect = propertyOf(item, "boundingRect", &hasBoundingRect).toRect();
			if (hasBoundingRect) {
				empty = false;
				xMin = qMin(xMin, boundingRect.left());
				yMin = qMin(yMin, boundingRect.top());
				xMax = qMax(xMax, boundingRect.right());
				yMax = qMax(yMax, boundingRect.bottom());
				return;
			}

			bool hasX{};
			bool hasY{};
			const int x = propertyOf(item, "x", &hasX).toInt();
			const int y = propertyOf(item, "y", &hasY).toInt();
			if (hasX && hasY) {
				empty = false;
				xMin = qMin(xMin, x);
				yMin = qMin(yMin, y);
				xMax = qMax(xMax, x);
				yMax = qMax(yMax, y);
			}
		});

		return empty ? QRect() : QRect(QPoint(xMin, yMin), QPoint(xMax, yMax));
	};
}

QVariant ValuesFactory::propertyChain(const QVariant &value
		, const QStringList &propertyChain, const QString &objectAlias) const
{
	QVariant currentValue = value;
	QString currentObjectAlias = objectAlias;
	for (const QString &property : propertyChain) {
		currentValue = propertyOf(currentValue, property, currentObjectAlias);
		currentObjectAlias += "." + property;
		if (!currentValue.isValid()) {
			return QVariant();
		}
	}

	return currentValue;
}

QVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property, const QString &objectAlias) const
{
	bool hasProperty{};
	bool unknownType{};
	const QVariant result = propertyOf(value, property, &hasProperty, &unknownType);

	if (unknownType) {
		reportError(QObject::tr("Unknown type of object \"%1\"").arg(objectAlias));
		return QVariant();
	}

	if (!hasProperty) {
		reportError(QObject::tr("Object \"%1\" has no property \"%2\"").arg(objectAlias, property));
		return QVariant();
	}

	return result;
}

QVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property
		, bool *hasProperty, bool *unknownType) const
{
	QVariant result;

	/// This code is here just because Dmitry can. And everyone else is lazy enough.
	hasProperty && (*hasProperty = false);
	unknownType && (*unknownType = false);

	// Here must be enumerated all types whoose properties we can obtain.
	if (value.canConvert<QObject *>()) {
		result = propertyOf(value.value<QObject *>(), property, hasProperty);
	} else if (value.canConvert<QPoint>()) {
		result = propertyOf(value.value<QPoint>(), property, hasProperty);
	} else if (value.canConvert<QRect>()) {
		result = propertyOf(value.value<QRect>(), property, hasProperty);
	} else if (value.canConvert<QVariantList>()) {
		result = propertyOf(value.value<QVariantList>(), property, hasProperty);
	} else {
		unknownType && (*unknownType = true);
	}

	return result;
}

QVariant ValuesFactory::propertyOf(const QObject *object, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (!object) {
		return QVariant();
	}

	const int index = object->metaObject()->indexOfProperty(qPrintable(property));
	if (index < 0) {
		ok && (*ok = false);
		return QVariant();
	}

	return object->property(qPrintable(property));
}

QVariant ValuesFactory::propertyOf(const QPoint &point, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "x") {
		return point.x();
	}

	if (property == "y") {
		return point.y();
	}

	ok && (*ok = false);
	return QVariant();
}

QVariant ValuesFactory::propertyOf(const QRect &rect, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "x") {
		return rect.x();
	}

	if (property == "y") {
		return rect.y();
	}

	if (property == "width") {
		return rect.width();
	}

	if (property == "height") {
		return rect.height();
	}

	ok && (*ok = false);
	return QVariant();
}

QVariant ValuesFactory::propertyOf(const QVariantList &list, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "first") {
		return list.first();
	}

	if (property == "last") {
		return list.last();
	}

	if (property == "size") {
		return list.size();
	}

	if (property == "isEmpty") {
		return list.isEmpty();
	}

	ok && (*ok = false);
	return QVariant();
}

void ValuesFactory::iterate(const QVariant &collection, const std::function<void (const QVariant &)> &visitor) const
{
	if (collection.canConvert<utils::ObjectsSetBase *>()) {
		// A good iteration, without copying. Object sets are good for large collections.
		collection.value<utils::ObjectsSetBase *>()->iterate(visitor);
	} else if (collection.canConvert<QVariantList>()) {
		// Warning: the whole list will be copied here!
		for (const QVariant &item : collection.value<QVariantList>()) {
			visitor(item);
		}
	} else {
		// Fallback case. This is not very nice situation is we get here, but it still can work.
		visitor(collection);
	}
}

void ValuesFactory::reportError(const QString &message) const
{
	emit mStatus.checkerError(message);
}
<commit_msg>Fixed crash in checker when trying to get member of an empty list<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * 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 "valuesFactory.h"

#include <QtCore/QRect>

#include <qrutils/mathUtils/geometry.h>
#include <utils/objectsSet.h>
#include <utils/timelineInterface.h>

using namespace twoDModel::constraints::details;

const QString typeOfNull = "undefined";

ValuesFactory::ValuesFactory(Variables &variables, const Objects &objects, StatusReporter &status)
	: mVariables(variables)
	, mObjects(objects)
	, mStatus(status)
{
}

Value ValuesFactory::invalidValue() const
{
	return []() { return QVariant(); };
}

Value ValuesFactory::boolValue(bool value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::intValue(int value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::doubleValue(qreal value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::stringValue(const QString &value) const
{
	return [value]() { return value; };
}

Value ValuesFactory::variableValue(const QString &name) const
{
	return [this, name]() {
		const QStringList parts = name.split('.');
		if (parts.isEmpty()) {
			reportError(QObject::tr("Requesting variable value with empty name"));
			return QVariant();
		}

		if (!mVariables.contains(parts.first())) {
			// We do not mind the situation when trying to read non-declared varible
			// because really can`t manage the order in which Qt will call event checking,
			// so some variables (for example counters) can be checked before setted.
			return QVariant();
		}

		return propertyChain(mVariables[parts.first()], parts.mid(1), parts.first());
	};
}

Value ValuesFactory::typeOf(const QString &objectId) const
{
	return [this, objectId]() {
		if (!mObjects.contains(objectId)) {
			return typeOfNull;
		}

		QObject const *object = mObjects[objectId];
		return object == nullptr ? typeOfNull : object->metaObject()->className();
	};
}

Value ValuesFactory::objectState(const QString &path) const
{
	return [this, path]() {
		const QStringList parts = path.split('.', QString::SkipEmptyParts);
		if (parts.isEmpty()) {
			reportError(QObject::tr("Object path is empty!"));
			return QVariant();
		}

		QString objectId = parts.first();
		if (!mObjects.contains(objectId)) {
			reportError(QObject::tr("No such object: %1").arg(objectId));
			return QVariant();
		}

		int lastObjectPart = 1;
		while (lastObjectPart < parts.count() && mObjects.contains(objectId + "." + parts[lastObjectPart])) {
			objectId += "." + parts[lastObjectPart];
			++lastObjectPart;
		}

		return propertyChain(QVariant::fromValue<QObject *>(mObjects[objectId]), parts.mid(lastObjectPart), objectId);
	};
}

Value ValuesFactory::timestamp(const utils::TimelineInterface &timeline) const
{
	return [&timeline]() { return timeline.timestamp(); };
}

Value ValuesFactory::unaryMinus(const Value &value) const
{
	return [value]() { return -value().toInt(); };
}

Value ValuesFactory::abs(const Value &value) const
{
	return [value]() { return qAbs(value().toInt()); };
}

Value ValuesFactory::sum(const Value &left, const Value &right) const
{
	return [left, right]() { return left().toInt() + right().toInt(); };
}

Value ValuesFactory::difference(const Value &left, const Value &right) const
{
	return [left, right]() { return left().toInt() - right().toInt(); };
}

Value ValuesFactory::max(const Value &left, const Value &right) const
{
	return [left, right]() { return qMax(left().toInt(), right().toInt()); };
}

Value ValuesFactory::min(const Value &left, const Value &right) const
{
	return [left, right]() { return qMin(left().toInt(), right().toInt()); };
}

Value ValuesFactory::distance(const Value &point1, const Value &point2) const
{
	return [point1, point2]() { return mathUtils::Geometry::distance(point1().toPoint(), point2().toPoint()); };
}

Value ValuesFactory::boundingRect(const Value &items) const
{
	return [this, items]() {
		bool empty = true;
		int xMin = INT_MAX;
		int yMin = INT_MAX;
		int xMax = INT_MIN;
		int yMax = INT_MIN;
		iterate(items(), [this, &xMin, &yMin, &xMax, &yMax, &empty](const QVariant &item) {
			bool hasBoundingRect{};
			const QRect boundingRect = propertyOf(item, "boundingRect", &hasBoundingRect).toRect();
			if (hasBoundingRect) {
				empty = false;
				xMin = qMin(xMin, boundingRect.left());
				yMin = qMin(yMin, boundingRect.top());
				xMax = qMax(xMax, boundingRect.right());
				yMax = qMax(yMax, boundingRect.bottom());
				return;
			}

			bool hasX{};
			bool hasY{};
			const int x = propertyOf(item, "x", &hasX).toInt();
			const int y = propertyOf(item, "y", &hasY).toInt();
			if (hasX && hasY) {
				empty = false;
				xMin = qMin(xMin, x);
				yMin = qMin(yMin, y);
				xMax = qMax(xMax, x);
				yMax = qMax(yMax, y);
			}
		});

		return empty ? QRect() : QRect(QPoint(xMin, yMin), QPoint(xMax, yMax));
	};
}

QVariant ValuesFactory::propertyChain(const QVariant &value
		, const QStringList &propertyChain, const QString &objectAlias) const
{
	QVariant currentValue = value;
	QString currentObjectAlias = objectAlias;
	for (const QString &property : propertyChain) {
		currentValue = propertyOf(currentValue, property, currentObjectAlias);
		currentObjectAlias += "." + property;
		if (!currentValue.isValid()) {
			return QVariant();
		}
	}

	return currentValue;
}

QVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property, const QString &objectAlias) const
{
	bool hasProperty{};
	bool unknownType{};
	const QVariant result = propertyOf(value, property, &hasProperty, &unknownType);

	if (unknownType) {
		reportError(QObject::tr("Unknown type of object \"%1\"").arg(objectAlias));
		return QVariant();
	}

	if (!hasProperty) {
		reportError(QObject::tr("Object \"%1\" has no property \"%2\"").arg(objectAlias, property));
		return QVariant();
	}

	return result;
}

QVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property
		, bool *hasProperty, bool *unknownType) const
{
	QVariant result;

	/// This code is here just because Dmitry can. And everyone else is lazy enough.
	hasProperty && (*hasProperty = false);
	unknownType && (*unknownType = false);

	// Here must be enumerated all types whoose properties we can obtain.
	if (value.canConvert<QObject *>()) {
		result = propertyOf(value.value<QObject *>(), property, hasProperty);
	} else if (value.canConvert<QPoint>()) {
		result = propertyOf(value.value<QPoint>(), property, hasProperty);
	} else if (value.canConvert<QRect>()) {
		result = propertyOf(value.value<QRect>(), property, hasProperty);
	} else if (value.canConvert<QVariantList>()) {
		result = propertyOf(value.value<QVariantList>(), property, hasProperty);
	} else {
		unknownType && (*unknownType = true);
	}

	return result;
}

QVariant ValuesFactory::propertyOf(const QObject *object, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (!object) {
		return QVariant();
	}

	const int index = object->metaObject()->indexOfProperty(qPrintable(property));
	if (index < 0) {
		ok && (*ok = false);
		return QVariant();
	}

	return object->property(qPrintable(property));
}

QVariant ValuesFactory::propertyOf(const QPoint &point, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "x") {
		return point.x();
	}

	if (property == "y") {
		return point.y();
	}

	ok && (*ok = false);
	return QVariant();
}

QVariant ValuesFactory::propertyOf(const QRect &rect, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "x") {
		return rect.x();
	}

	if (property == "y") {
		return rect.y();
	}

	if (property == "width") {
		return rect.width();
	}

	if (property == "height") {
		return rect.height();
	}

	ok && (*ok = false);
	return QVariant();
}

QVariant ValuesFactory::propertyOf(const QVariantList &list, const QString &property, bool *ok) const
{
	ok && (*ok = true);
	if (property == "first" && !list.isEmpty()) {
		return list.first();
	}

	if (property == "last" && !list.isEmpty()) {
		return list.last();
	}

	if (property == "size") {
		return list.size();
	}

	if (property == "isEmpty") {
		return list.isEmpty();
	}

	ok && (*ok = false);
	return QVariant();
}

void ValuesFactory::iterate(const QVariant &collection, const std::function<void (const QVariant &)> &visitor) const
{
	if (collection.canConvert<utils::ObjectsSetBase *>()) {
		// A good iteration, without copying. Object sets are good for large collections.
		collection.value<utils::ObjectsSetBase *>()->iterate(visitor);
	} else if (collection.canConvert<QVariantList>()) {
		// Warning: the whole list will be copied here!
		for (const QVariant &item : collection.value<QVariantList>()) {
			visitor(item);
		}
	} else {
		// Fallback case. This is not very nice situation is we get here, but it still can work.
		visitor(collection);
	}
}

void ValuesFactory::reportError(const QString &message) const
{
	emit mStatus.checkerError(message);
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-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.
 *
 *
 */
#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_
#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::registration::CorrespondenceRejectorFeatures::getRemainingCorrespondences (
    const pcl::Correspondences& original_correspondences,
    pcl::Correspondences& remaining_correspondences)
{
  unsigned int number_valid_correspondences = 0;
  remaining_correspondences.resize (original_correspondences.size ());
  // For each set of features, go over each correspondence from input_correspondences_
  for (size_t i = 0; i < input_correspondences_->size (); ++i)
  {
    // Go over the map of features
    for (FeaturesMap::const_iterator it = features_map_.begin (); it != features_map_.end (); ++it)
    {
      // Check if the score in feature space is above the given threshold
      // (assume that the number of feature correspondenecs is the same as the number of point correspondences)
      if (!it->second->isCorrespondenceValid (i))
        break;

      remaining_correspondences[number_valid_correspondences] = original_correspondences[i];
      ++number_valid_correspondences;
    }
  }
  remaining_correspondences.resize (number_valid_correspondences);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setSourceFeature (
    const typename pcl::PointCloud<FeatureT>::ConstPtr &source_feature, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setSourceFeature (source_feature);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline typename pcl::PointCloud<FeatureT>::ConstPtr
pcl::registration::CorrespondenceRejectorFeatures::getSourceFeature (const std::string &key)
{
  if (features_map_.count (key) == 0)
    return (boost::shared_ptr<pcl::PointCloud<const FeatureT> > ());
  else
    return (boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->getSourceFeature ());
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setTargetFeature (
    const typename pcl::PointCloud<FeatureT>::ConstPtr &target_feature, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setTargetFeature (target_feature);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline typename pcl::PointCloud<FeatureT>::ConstPtr
pcl::registration::CorrespondenceRejectorFeatures::getTargetFeature (const std::string &key)
{
  typedef pcl::PointCloud<FeatureT> FeatureCloud;
  typedef typename FeatureCloud::ConstPtr FeatureCloudConstPtr;

  if (features_map_.count (key) == 0)
    return (boost::shared_ptr<const pcl::PointCloud<FeatureT> > ());
  else
    return (boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->getTargetFeature ());
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setDistanceThreshold (
    double thresh, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setDistanceThreshold (thresh);
}

//////////////////////////////////////////////////////////////////////////////////////////////
inline bool
pcl::registration::CorrespondenceRejectorFeatures::hasValidFeatures ()
{
  if (features_map_.empty ())
    return (false);
  typename FeaturesMap::const_iterator feature_itr;
  for (feature_itr = features_map_.begin (); feature_itr != features_map_.end (); ++feature_itr)
    if (!feature_itr->second->isValid ())
      return (false);
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setFeatureRepresentation (
  const typename pcl::PointRepresentation<FeatureT>::ConstPtr &fr,
  const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setFeatureRepresentation (fr);
}

#endif /* PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_ */
<commit_msg>fixed a visual studio compilation error<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-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.
 *
 *
 */
#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_
#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::registration::CorrespondenceRejectorFeatures::getRemainingCorrespondences (
    const pcl::Correspondences& original_correspondences,
    pcl::Correspondences& remaining_correspondences)
{
  unsigned int number_valid_correspondences = 0;
  remaining_correspondences.resize (original_correspondences.size ());
  // For each set of features, go over each correspondence from input_correspondences_
  for (size_t i = 0; i < input_correspondences_->size (); ++i)
  {
    // Go over the map of features
    for (FeaturesMap::const_iterator it = features_map_.begin (); it != features_map_.end (); ++it)
    {
      // Check if the score in feature space is above the given threshold
      // (assume that the number of feature correspondenecs is the same as the number of point correspondences)
      if (!it->second->isCorrespondenceValid (i))
        break;

      remaining_correspondences[number_valid_correspondences] = original_correspondences[i];
      ++number_valid_correspondences;
    }
  }
  remaining_correspondences.resize (number_valid_correspondences);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setSourceFeature (
    const typename pcl::PointCloud<FeatureT>::ConstPtr &source_feature, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setSourceFeature (source_feature);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline typename pcl::PointCloud<FeatureT>::ConstPtr
pcl::registration::CorrespondenceRejectorFeatures::getSourceFeature (const std::string &key)
{
  if (features_map_.count (key) == 0)
    return (boost::shared_ptr<pcl::PointCloud<const FeatureT> > ());
  else
    return (boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->getSourceFeature ());
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setTargetFeature (
    const typename pcl::PointCloud<FeatureT>::ConstPtr &target_feature, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setTargetFeature (target_feature);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline typename pcl::PointCloud<FeatureT>::ConstPtr
pcl::registration::CorrespondenceRejectorFeatures::getTargetFeature (const std::string &key)
{
  typedef pcl::PointCloud<FeatureT> FeatureCloud;
  typedef typename FeatureCloud::ConstPtr FeatureCloudConstPtr;

  if (features_map_.count (key) == 0)
    return (boost::shared_ptr<const pcl::PointCloud<FeatureT> > ());
  else
    return (boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->getTargetFeature ());
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setDistanceThreshold (
    double thresh, const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setDistanceThreshold (thresh);
}

//////////////////////////////////////////////////////////////////////////////////////////////
inline bool
pcl::registration::CorrespondenceRejectorFeatures::hasValidFeatures ()
{
  if (features_map_.empty ())
    return (false);
  FeaturesMap::const_iterator feature_itr;
  for (feature_itr = features_map_.begin (); feature_itr != features_map_.end (); ++feature_itr)
    if (!feature_itr->second->isValid ())
      return (false);
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename FeatureT> inline void
pcl::registration::CorrespondenceRejectorFeatures::setFeatureRepresentation (
  const typename pcl::PointRepresentation<FeatureT>::ConstPtr &fr,
  const std::string &key)
{
  if (features_map_.count (key) == 0)
    features_map_[key].reset (new FeatureContainer<FeatureT>);
  boost::static_pointer_cast<FeatureContainer<FeatureT> > (features_map_[key])->setFeatureRepresentation (fr);
}

#endif /* PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_ */
<|endoftext|>