<commit_before>#include "Matrix.h"
#include <string>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

Matrix::Matrix() {
	this->rows = 0;
	this->cols = 0;
}

Matrix::Matrix(int rows, int cols) {
	resize(rows, cols);
}

Matrix::Matrix(const Matrix& m) {
	int i, j;

	resize(m.rows, m.cols);

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			this->matrix[i][j] = m.matrix[i][j];
		}
	}
}

void Matrix::resize(int rows, int cols) {
	int i, j;

	if(this->rows > 0 && this->cols > 0) {
		for(i = 0; i < this->rows; i++) {
			free(this->matrix[i]);
		}
		free(this->matrix);

	}

	this->matrix = (float**) malloc(rows * sizeof(float*));
	for (i = 0; i < rows; i++){
		this->matrix[i] = (float*) malloc(cols * sizeof(float));
		for(j = 0; j < cols; j++)
			this->matrix[i][j] = 0;
	}

	this->rows = rows;
	this->cols = cols;

	return;
}

void Matrix::set(int row, int col, float value) {
	this->matrix[row][col] = value;
}

float Matrix::get(int row, int col) {
	return matrix[row][col];
}

int Matrix::getRows() {
	return this->rows;
}

int Matrix::getCols() {
	return this->cols;
}

int* Matrix::getSize() {
	static int size[] = { this->rows, this->cols };
	return size;
}

Matrix Matrix::multiply(const Matrix& m) {
	int i, j, k;
	float sum = 0;

	if(this->cols != m.rows)
		throw 30;

	Matrix result(this->rows, m.cols);

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < m.cols; j++) {
			for(k = 0; k < m.rows; k++) {
				sum = sum + (this->matrix[i][k] * m.matrix[k][j]);
			}
			result.set(i,j, sum);
			sum = 0;
		}
	}
	return result;
}

Matrix Matrix::pow(int power) {
	int i;
	Matrix result(*this);

	for(i = 1; i < power; i++) {
		result = this->multiply(result);
	}

	return result;
}

void Matrix::fill() {
	int i, j;

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			this->matrix[i][j] = rand();
		}
	}
}

string Matrix::toString() {
	std::ostringstream val;
	int i, j;
	string result("");

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			val.str("");
			val << this->matrix[i][j];
			result += val.str();
			result += "\t";
		}
		result += "\n";
	}

	return result;
}
<commit_msg>Abmessungen in toString<commit_after>#include "Matrix.h"
#include <string>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

Matrix::Matrix() {
	this->rows = 0;
	this->cols = 0;
}

Matrix::Matrix(int rows, int cols) {
	resize(rows, cols);
}

Matrix::Matrix(const Matrix& m) {
	int i, j;

	resize(m.rows, m.cols);

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			this->matrix[i][j] = m.matrix[i][j];
		}
	}
}

void Matrix::resize(int rows, int cols) {
	int i, j;

	if(this->rows > 0 && this->cols > 0) {
		for(i = 0; i < this->rows; i++) {
			free(this->matrix[i]);
		}
		free(this->matrix);

	}

	this->matrix = (float**) malloc(rows * sizeof(float*));
	for (i = 0; i < rows; i++){
		this->matrix[i] = (float*) malloc(cols * sizeof(float));
		for(j = 0; j < cols; j++)
			this->matrix[i][j] = 0;
	}

	this->rows = rows;
	this->cols = cols;

	return;
}

void Matrix::set(int row, int col, float value) {
	this->matrix[row][col] = value;
}

float Matrix::get(int row, int col) {
	return matrix[row][col];
}

int Matrix::getRows() {
	return this->rows;
}

int Matrix::getCols() {
	return this->cols;
}

int* Matrix::getSize() {
	static int size[] = { this->rows, this->cols };
	return size;
}

Matrix Matrix::multiply(const Matrix& m) {
	int i, j, k;
	float sum = 0;

	if(this->cols != m.rows)
		throw 30;

	Matrix result(this->rows, m.cols);

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < m.cols; j++) {
			for(k = 0; k < m.rows; k++) {
				sum = sum + (this->matrix[i][k] * m.matrix[k][j]);
			}
			result.set(i,j, sum);
			sum = 0;
		}
	}
	return result;
}

Matrix Matrix::pow(int power) {
	int i;
	Matrix result(*this);

	for(i = 1; i < power; i++) {
		result = this->multiply(result);
	}

	return result;
}

void Matrix::fill() {
	int i, j;

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			this->matrix[i][j] = rand();
		}
	}
}

string Matrix::toString() {
	std::ostringstream val;
	int i, j;
	string result("");

	val << "\n\n" << this->rows << "x" << this->cols << " Matrix\n";
	result += val.str();

	for(i = 0; i < this->rows; i++) {
		for(j = 0; j < this->cols; j++) {
			val.str("");
			val << this->matrix[i][j];
			result += val.str();
			result += "\t";
		}
		result += "\n";
	}

	return result;
}
<|endoftext|>


<commit_before>// geography.cpp
//
#include "common/common.h"
#include "geography.h"
#include "math_util.h"
#include "system/page_info.h"

namespace sdl { namespace db {

geo_mem::geo_mem(data_type && m): m_data(std::move(m))
{
    init_geography();
    m_type = init_type();
    SDL_ASSERT(m_type != spatial_type::null);
}

void geo_mem::swap(geo_mem & v)
{
    m_data.swap(v.m_data);
    m_buf.swap(v.m_buf);
    std::swap(m_type, v.m_type);
    std::swap(m_geography, v.m_geography);
}

void geo_mem::init_geography()
{
    SDL_ASSERT(!m_geography && !m_buf);
    if (mem_size(m_data) > sizeof(geo_data)) {
        if (m_data.size() == 1) {
            m_geography = reinterpret_cast<geo_data const *>(m_data[0].first);
        }
        else {
            reset_new(m_buf, make_vector(m_data));
            m_geography = reinterpret_cast<geo_data const *>(m_buf->data());
        }
    }
    else {
        throw_error<geo_mem_error>("bad geography");
    }
    SDL_ASSERT(m_geography->data.SRID == 4326);
}

spatial_type geo_mem::init_type()
{
    static_assert(sizeof(geo_data) < sizeof(geo_point), "");
    static_assert(sizeof(geo_point) < sizeof(geo_multipolygon), "");
    static_assert(sizeof(geo_pointarray) < sizeof(geo_linesegment), "");
    static_assert(sizeof(geo_multipolygon) == sizeof(geo_pointarray), "");
    static_assert(sizeof(geo_linestring) == sizeof(geo_pointarray), "");

    geo_data const * const data = m_geography;
    size_t const data_size = mem_size(m_data);

    if (data_size == sizeof(geo_point)) { // 22 bytes
        if (data->data.tag == spatial_tag::t_point) {
            return spatial_type::point;
        }
        SDL_ASSERT(0);
        return spatial_type::null;
    }
    if (data_size == sizeof(geo_linesegment)) { // 38 bytes
        if (data->data.tag == spatial_tag::t_linesegment) {
            return spatial_type::linesegment;
        }
        SDL_ASSERT(0);
        return spatial_type::null;
    }
    if (data_size >= sizeof(geo_pointarray)) { // 26 bytes
        if (data->data.tag == spatial_tag::t_linestring) {
            SDL_ASSERT(!reinterpret_cast<const geo_linestring *>(data)->tail(data_size));
            return spatial_type::linestring;
        }
        if (data->data.tag == spatial_tag::t_multipolygon) {
            geo_base_polygon const * const pp = reinterpret_cast<const geo_base_polygon *>(data);
            geo_tail const * const tail = pp->tail(data_size);
            if (tail) {
                if (tail->size() > 1) {
                    SDL_ASSERT(tail->data.reserved.num == 0);
                    SDL_ASSERT(tail->data.numobj.num > 1);
                    if (tail->data.numobj.tag == 1) {
                        SDL_ASSERT(tail->data.reserved.tag == 1);
                        return spatial_type::multilinestring;
                    }
                    else {
                        SDL_ASSERT((tail->data.reserved.tag == 0) || (tail->data.reserved.tag == 2));
                        SDL_ASSERT(tail->data.numobj.tag == 2);
                        SDL_ASSERT(!pp->ring_empty());
                        return spatial_type::multipolygon; // or polygon with interior rings
                    }
                }
                else {
                    SDL_ASSERT(tail->data.reserved.num == 0);
                    SDL_ASSERT(tail->data.reserved.tag == 1);
                    SDL_ASSERT(tail->data.numobj.num == 1);
                    if (tail->data.numobj.tag == 1) {
                        return spatial_type::linestring;
                    }
                    else {
                        SDL_ASSERT(tail->data.numobj.tag == 2);
                        SDL_ASSERT(pp->ring_num() == 1);
                        return spatial_type::polygon;
                    }
                }
            }
            SDL_ASSERT(0); // to be tested
            return spatial_type::linestring;
        }
    }
    SDL_ASSERT(0);
    return spatial_type::null;
}

std::string geo_mem::STAsText() const {
    if (!is_null()) {
        return to_string::type(*this);
    }
    SDL_ASSERT(0);
    return{};
}

bool geo_mem::STContains(spatial_point const & p) const
{
    switch (m_type) {
    case spatial_type::point:           return cast_point()->STContains(p);
//  case spatial_type::linestring:      return false; //cast_linestring()->STContains(p);
    case spatial_type::polygon:         return cast_polygon()->STContains(p);
//  case spatial_type::linesegment:     return false; //cast_linesegment()->STContains(p);
//  case spatial_type::multilinestring: return false; //cast_multilinestring()->STContains(p);
    case spatial_type::multipolygon:    return cast_multipolygon()->STContains(p);
    default:
        return false;
    }
}

geo_tail const * geo_mem::get_tail() const
{
    if (m_type == spatial_type::multipolygon) {
        return cast_multipolygon()->tail(mem_size(data()));
    }
    if (m_type == spatial_type::multilinestring) {
        return cast_multilinestring()->tail(mem_size(data()));
    }
    return nullptr;
}

geo_tail const * geo_mem::get_tail_multipolygon() const
{
    if (m_type == spatial_type::multipolygon) {
        return cast_multipolygon()->tail(mem_size(data()));
    }
    SDL_ASSERT(0);
    return nullptr;
}

geo_mem::vec_orientation
geo_mem::ring_orient() const
{
    if (geo_tail const * const tail = get_tail_multipolygon()) {
        const size_t size = tail->size();
        vec_orientation result(size, orientation::exterior);
        point_access exterior = get_subobj(0);
        bool point_on_vertix = false;
        for (size_t i = 1; i < size; ++i) {
            point_access next = get_subobj(i);
            for (auto const & p : next) {
                if (math_util::point_in_polygon(exterior.begin(), exterior.end(), p, point_on_vertix)) {
                    if (!point_on_vertix) {
                        result[i] = orientation::interior;
                        break;
                    }
                }
                else {
                    exterior = next;
                    break;
                }
            }
        }
        return result;
    }
    return {};
}

//------------------------------------------------------------------------

} // db
} // sdl

#if SDL_DEBUG
namespace sdl {
    namespace db {
        namespace {
            class unit_test {
            public:
                unit_test()
                {
                    if (1) {
                        using vec = geo_mem::vec_orientation;
                        SDL_TRACE(sizeof(vec));
                        vec t1(4, orientation::interior);
                        vec t2(10, orientation::interior);
                        SDL_ASSERT(t1.use_buf());
                        SDL_ASSERT(!t2.use_buf());
                        vec m1(std::move(t1));
                        vec m2(std::move(t2));
                        vec m11, m22;
                        m11 = std::move(m1);
                        m22 = std::move(m2);
                        SDL_ASSERT(m11.size() == 4);
                        SDL_ASSERT(m22.size() == 10);
                        m22 = std::move(m11);
                        SDL_ASSERT(m22.size() == 4);
                    }
                }
            };
            static unit_test s_test;
        }
    } // db
} // sdl
#endif //#if SV_DEBUG<commit_msg>enum class winding<commit_after>// geography.cpp
//
#include "common/common.h"
#include "geography.h"
#include "math_util.h"
#include "system/page_info.h"

namespace sdl { namespace db {

geo_mem::geo_mem(data_type && m): m_data(std::move(m))
{
    init_geography();
    m_type = init_type();
    SDL_ASSERT(m_type != spatial_type::null);
}

void geo_mem::swap(geo_mem & v)
{
    m_data.swap(v.m_data);
    m_buf.swap(v.m_buf);
    std::swap(m_type, v.m_type);
    std::swap(m_geography, v.m_geography);
}

void geo_mem::init_geography()
{
    SDL_ASSERT(!m_geography && !m_buf);
    if (mem_size(m_data) > sizeof(geo_data)) {
        if (m_data.size() == 1) {
            m_geography = reinterpret_cast<geo_data const *>(m_data[0].first);
        }
        else {
            reset_new(m_buf, make_vector(m_data));
            m_geography = reinterpret_cast<geo_data const *>(m_buf->data());
        }
    }
    else {
        throw_error<geo_mem_error>("bad geography");
    }
    SDL_ASSERT(m_geography->data.SRID == 4326);
}

spatial_type geo_mem::init_type()
{
    static_assert(sizeof(geo_data) < sizeof(geo_point), "");
    static_assert(sizeof(geo_point) < sizeof(geo_multipolygon), "");
    static_assert(sizeof(geo_pointarray) < sizeof(geo_linesegment), "");
    static_assert(sizeof(geo_multipolygon) == sizeof(geo_pointarray), "");
    static_assert(sizeof(geo_linestring) == sizeof(geo_pointarray), "");

    geo_data const * const data = m_geography;
    size_t const data_size = mem_size(m_data);

    if (data_size == sizeof(geo_point)) { // 22 bytes
        if (data->data.tag == spatial_tag::t_point) {
            return spatial_type::point;
        }
        SDL_ASSERT(0);
        return spatial_type::null;
    }
    if (data_size == sizeof(geo_linesegment)) { // 38 bytes
        if (data->data.tag == spatial_tag::t_linesegment) {
            return spatial_type::linesegment;
        }
        SDL_ASSERT(0);
        return spatial_type::null;
    }
    if (data_size >= sizeof(geo_pointarray)) { // 26 bytes
        if (data->data.tag == spatial_tag::t_linestring) {
            SDL_ASSERT(!reinterpret_cast<const geo_linestring *>(data)->tail(data_size));
            return spatial_type::linestring;
        }
        if (data->data.tag == spatial_tag::t_multipolygon) {
            geo_base_polygon const * const pp = reinterpret_cast<const geo_base_polygon *>(data);
            geo_tail const * const tail = pp->tail(data_size);
            if (tail) {
                if (tail->size() > 1) {
                    SDL_ASSERT(tail->data.reserved.num == 0);
                    SDL_ASSERT(tail->data.numobj.num > 1);
                    if (tail->data.numobj.tag == 1) {
                        SDL_ASSERT(tail->data.reserved.tag == 1);
                        return spatial_type::multilinestring;
                    }
                    else {
                        SDL_ASSERT((tail->data.reserved.tag == 0) || (tail->data.reserved.tag == 2));
                        SDL_ASSERT(tail->data.numobj.tag == 2);
                        SDL_ASSERT(!pp->ring_empty());
                        return spatial_type::multipolygon; // or polygon with interior rings
                    }
                }
                else {
                    SDL_ASSERT(tail->data.reserved.num == 0);
                    SDL_ASSERT(tail->data.reserved.tag == 1);
                    SDL_ASSERT(tail->data.numobj.num == 1);
                    if (tail->data.numobj.tag == 1) {
                        return spatial_type::linestring;
                    }
                    else {
                        SDL_ASSERT(tail->data.numobj.tag == 2);
                        SDL_ASSERT(pp->ring_num() == 1);
                        return spatial_type::polygon;
                    }
                }
            }
            SDL_ASSERT(0); // to be tested
            return spatial_type::linestring;
        }
    }
    SDL_ASSERT(0);
    return spatial_type::null;
}

std::string geo_mem::STAsText() const {
    if (!is_null()) {
        return to_string::type(*this);
    }
    SDL_ASSERT(0);
    return{};
}

bool geo_mem::STContains(spatial_point const & p) const
{
    switch (m_type) {
    case spatial_type::point:           return cast_point()->STContains(p);
//  case spatial_type::linestring:      return false; //cast_linestring()->STContains(p);
    case spatial_type::polygon:         return cast_polygon()->STContains(p);
//  case spatial_type::linesegment:     return false; //cast_linesegment()->STContains(p);
//  case spatial_type::multilinestring: return false; //cast_multilinestring()->STContains(p);
    case spatial_type::multipolygon:    return cast_multipolygon()->STContains(p);
    default:
        return false;
    }
}

geo_tail const * geo_mem::get_tail() const
{
    if (m_type == spatial_type::multipolygon) {
        return cast_multipolygon()->tail(mem_size(data()));
    }
    if (m_type == spatial_type::multilinestring) {
        return cast_multilinestring()->tail(mem_size(data()));
    }
    return nullptr;
}

geo_tail const * geo_mem::get_tail_multipolygon() const
{
    if (m_type == spatial_type::multipolygon) {
        return cast_multipolygon()->tail(mem_size(data()));
    }
    SDL_ASSERT(0);
    return nullptr;
}

geo_mem::vec_orientation
geo_mem::ring_orient() const
{
    if (geo_tail const * const tail = get_tail_multipolygon()) {
        const size_t size = tail->size();
        vec_orientation result(size, orientation::exterior);
        point_access exterior = get_subobj(0);
        bool point_on_vertix = false;
        for (size_t i = 1; i < size; ++i) {
            point_access next = get_subobj(i);
            for (auto const & p : next) {
                if (math_util::point_in_polygon(exterior.begin(), exterior.end(), p, point_on_vertix)) {
                    if (!point_on_vertix) {
                        result[i] = orientation::interior;
                        break;
                    }
                }
                else {
                    exterior = next;
                    break;
                }
            }
        }
        return result;
    }
    return {};
}

//------------------------------------------------------------------------

} // db
} // sdl

#if SDL_DEBUG
namespace sdl {
    namespace db {
        namespace {
            class unit_test {
            public:
                unit_test()
                {
                    if (1) {
                        using vec = geo_mem::vec_orientation;
                        //SDL_TRACE(sizeof(vec));
                        vec t1(4, orientation::interior);
                        vec t2(10, orientation::interior);
                        SDL_ASSERT(t1.use_buf());
                        SDL_ASSERT(!t2.use_buf());
                        vec m1(std::move(t1));
                        vec m2(std::move(t2));
                        vec m11, m22;
                        m11 = std::move(m1);
                        m22 = std::move(m2);
                        SDL_ASSERT(m11.size() == 4);
                        SDL_ASSERT(m22.size() == 10);
                        m22 = std::move(m11);
                        SDL_ASSERT(m22.size() == 4);
                    }
                }
            };
            static unit_test s_test;
        }
    } // db
} // sdl
#endif //#if SV_DEBUG<|endoftext|>


<commit_before>// Copyright 2019 Google LLC, Andrew Hines
//
// 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 "alignment.h"

#include <memory>
#include <utility>

#include "amatrix.h"
#include "audio_signal.h"
#include "envelope.h"
#include "xcorr.h"

namespace Visqol {
std::tuple<AudioSignal, AudioSignal, double> Alignment::AlignAndTruncate(
    const AudioSignal &ref_signal, const AudioSignal &deg_signal) {
  auto alignment_result = Alignment::GloballyAlign(ref_signal, deg_signal);
  AudioSignal aligned_deg_signal = std::get<0>(alignment_result);
  double lag = std::get<1>(alignment_result);
  auto &ref_matrix = ref_signal.data_matrix;
  // Take the aligned degraded matrix.
  auto &deg_matrix = aligned_deg_signal.data_matrix;
  AMatrix<double> new_ref_matrix = ref_matrix;
  AMatrix<double> new_deg_matrix = deg_matrix;

  // Truncate the two aligned signals to match lengths.
  // If the lag is positive or negative, the starts are aligned.
  // (The front of deg_signal is zero padded or truncated).
  if (ref_matrix.NumRows() > deg_matrix.NumRows()) {
    new_ref_matrix = ref_matrix.GetRows(0, deg_matrix.NumRows() - 1);
  } else if (ref_matrix.NumRows() < deg_matrix.NumRows()) {
    // For positive lag, the beginning of ref is now aligned with zeros, so
    // that amount should be truncated.
    new_ref_matrix = ref_matrix.GetRows(int(lag * ref_signal.sample_rate),
                                        ref_matrix.NumRows() - 1);
    // Truncate the zeros off the deg matrix as well.
    new_deg_matrix = deg_matrix.GetRows((int)(lag * deg_signal.sample_rate),
                                        ref_matrix.NumRows() - 1);
  }

  AudioSignal new_deg_signal{new_deg_matrix, deg_signal.sample_rate};
  AudioSignal new_ref_signal{new_ref_matrix, ref_signal.sample_rate};
  return std::make_tuple(new_ref_signal, new_deg_signal, lag);
}

std::tuple<AudioSignal, double> Alignment::GloballyAlign(
    const AudioSignal &ref_signal, const AudioSignal &deg_signal) {
  auto &ref_matrix = ref_signal.data_matrix;
  auto &deg_matrix = deg_signal.data_matrix;
  auto ref_upper_env = Envelope::CalcUpperEnv(ref_matrix);
  auto deg_upper_env = Envelope::CalcUpperEnv(deg_matrix);
  auto best_lag = XCorr::CalcBestLag(ref_upper_env, deg_upper_env);

  // Limit the lag to half a patch.
  if (best_lag == 0 || std::abs(best_lag) > (double) ref_matrix.NumRows() / 2) {
    return std::make_tuple(deg_signal, 0);
  } else {
    // align degraded matrix
    AMatrix<double> new_deg_matrix;
    // If the same point of the reference comes after the degraded
    // (negative lag), truncate the rows before the refrence.
    // If the reference comes before the degraded, prepend zeros
    // to the degraded.
    if (best_lag < 0) {
      new_deg_matrix = deg_matrix.GetRows(std::abs(best_lag),
                                          deg_matrix.NumRows() - 1);
    } else {
      new_deg_matrix = AMatrix<double>::Filled(best_lag, 1, 0.0);
      new_deg_matrix = new_deg_matrix.JoinVertically(deg_matrix);
    }
    AudioSignal new_deg_signal{std::move(new_deg_matrix),
                               deg_signal.sample_rate};
    return std::make_tuple(new_deg_signal, best_lag / (double) deg_signal.sample_rate);
  }
}
}  // namespace Visqol
<commit_msg>Add missing tuple header<commit_after>// Copyright 2019 Google LLC, Andrew Hines
//
// 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 "alignment.h"

#include <memory>
#include <tuple>
#include <utility>

#include "amatrix.h"
#include "audio_signal.h"
#include "envelope.h"
#include "xcorr.h"

namespace Visqol {
std::tuple<AudioSignal, AudioSignal, double> Alignment::AlignAndTruncate(
    const AudioSignal &ref_signal, const AudioSignal &deg_signal) {
  auto alignment_result = Alignment::GloballyAlign(ref_signal, deg_signal);
  AudioSignal aligned_deg_signal = std::get<0>(alignment_result);
  double lag = std::get<1>(alignment_result);
  auto &ref_matrix = ref_signal.data_matrix;
  // Take the aligned degraded matrix.
  auto &deg_matrix = aligned_deg_signal.data_matrix;
  AMatrix<double> new_ref_matrix = ref_matrix;
  AMatrix<double> new_deg_matrix = deg_matrix;

  // Truncate the two aligned signals to match lengths.
  // If the lag is positive or negative, the starts are aligned.
  // (The front of deg_signal is zero padded or truncated).
  if (ref_matrix.NumRows() > deg_matrix.NumRows()) {
    new_ref_matrix = ref_matrix.GetRows(0, deg_matrix.NumRows() - 1);
  } else if (ref_matrix.NumRows() < deg_matrix.NumRows()) {
    // For positive lag, the beginning of ref is now aligned with zeros, so
    // that amount should be truncated.
    new_ref_matrix = ref_matrix.GetRows(int(lag * ref_signal.sample_rate),
                                        ref_matrix.NumRows() - 1);
    // Truncate the zeros off the deg matrix as well.
    new_deg_matrix = deg_matrix.GetRows((int)(lag * deg_signal.sample_rate),
                                        ref_matrix.NumRows() - 1);
  }

  AudioSignal new_deg_signal{new_deg_matrix, deg_signal.sample_rate};
  AudioSignal new_ref_signal{new_ref_matrix, ref_signal.sample_rate};
  return std::make_tuple(new_ref_signal, new_deg_signal, lag);
}

std::tuple<AudioSignal, double> Alignment::GloballyAlign(
    const AudioSignal &ref_signal, const AudioSignal &deg_signal) {
  auto &ref_matrix = ref_signal.data_matrix;
  auto &deg_matrix = deg_signal.data_matrix;
  auto ref_upper_env = Envelope::CalcUpperEnv(ref_matrix);
  auto deg_upper_env = Envelope::CalcUpperEnv(deg_matrix);
  auto best_lag = XCorr::CalcBestLag(ref_upper_env, deg_upper_env);

  // Limit the lag to half a patch.
  if (best_lag == 0 || std::abs(best_lag) > (double) ref_matrix.NumRows() / 2) {
    return std::make_tuple(deg_signal, 0);
  } else {
    // align degraded matrix
    AMatrix<double> new_deg_matrix;
    // If the same point of the reference comes after the degraded
    // (negative lag), truncate the rows before the refrence.
    // If the reference comes before the degraded, prepend zeros
    // to the degraded.
    if (best_lag < 0) {
      new_deg_matrix = deg_matrix.GetRows(std::abs(best_lag),
                                          deg_matrix.NumRows() - 1);
    } else {
      new_deg_matrix = AMatrix<double>::Filled(best_lag, 1, 0.0);
      new_deg_matrix = new_deg_matrix.JoinVertically(deg_matrix);
    }
    AudioSignal new_deg_signal{std::move(new_deg_matrix),
                               deg_signal.sample_rate};
    return std::make_tuple(new_deg_signal, best_lag / (double) deg_signal.sample_rate);
  }
}
}  // namespace Visqol
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDebug>
#include <QThread>

#include <KDBusService>
#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    KDBusService service(KDBusService::Unique);

    QCommandLineParser parser;
    parser.addOption(QCommandLineOption("reset", i18n("Reset the database")));
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    if (parser.isSet("reset")) {
//         KokoConfig config;
//         config.reset();

//         ImageStorage::reset();
    }

    QThread trackerThread;

    QStringList locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation);
    Q_ASSERT(locations.size() >= 1);
//     qDebug() << locations;
//     FileSystemTracker tracker;
//     tracker.setFolder(locations.first());
//     tracker.moveToThread(&trackerThread);

//     Koko::Processor processor;
//     QObject::connect(&tracker, &FileSystemTracker::imageAdded, &processor, &Koko::Processor::addFile);
//     QObject::connect(&tracker, &FileSystemTracker::imageRemoved, &processor, &Koko::Processor::removeFile);
//     QObject::connect(&tracker, &FileSystemTracker::initialScanComplete, &processor, &Koko::Processor::initialScanCompleted);
//
//     trackerThread.start();
//     tracker.init();
//
//     KokoConfig config;

    QQmlEngine engine;
    QQmlContext* objectContext = engine.rootContext();
    QString platformEnv(qgetenv("PLASMA_PLATFORM"));
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv);
    engine.rootContext()->setContextProperty("bookLocations", locations);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);

    QString path;
    if (platformEnv.startsWith("phone")) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    QQmlComponent component(&engine, path);
    if (component.isError()) {
        std::cout << component.errorString().toUtf8().constData() << std::endl;
        Q_ASSERT(0);
    }
    Q_ASSERT(component.status() == QQmlComponent::Ready);

    QObject* obj = component.create(objectContext);
    Q_ASSERT(obj);

    int rt = app.exec();
//     trackerThread.quit();
    return rt;
}
<commit_msg>Always use the mobile version for now<commit_after>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDebug>
#include <QThread>

#include <KDBusService>
#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    KDBusService service(KDBusService::Unique);

    QCommandLineParser parser;
    parser.addOption(QCommandLineOption("reset", i18n("Reset the database")));
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    if (parser.isSet("reset")) {
//         KokoConfig config;
//         config.reset();

//         ImageStorage::reset();
    }

    QThread trackerThread;

    QStringList locations = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    locations << QStandardPaths::standardLocations(QStandardPaths::DownloadLocation);
    Q_ASSERT(locations.size() >= 1);
//     qDebug() << locations;
//     FileSystemTracker tracker;
//     tracker.setFolder(locations.first());
//     tracker.moveToThread(&trackerThread);

//     Koko::Processor processor;
//     QObject::connect(&tracker, &FileSystemTracker::imageAdded, &processor, &Koko::Processor::addFile);
//     QObject::connect(&tracker, &FileSystemTracker::imageRemoved, &processor, &Koko::Processor::removeFile);
//     QObject::connect(&tracker, &FileSystemTracker::initialScanComplete, &processor, &Koko::Processor::initialScanCompleted);
//
//     trackerThread.start();
//     tracker.init();
//
//     KokoConfig config;

    QQmlEngine engine;
    QQmlContext* objectContext = engine.rootContext();
    QString platformEnv(qgetenv("PLASMA_PLATFORM"));
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv);
    engine.rootContext()->setContextProperty("bookLocations", locations);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);

    QString path;
//     if (platformEnv.startsWith("phone")) {
    // Once we've got a functional desktop version, restore this check. Right now it doesn't make a lot of sense.
    if(true) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    QQmlComponent component(&engine, path);
    if (component.isError()) {
        std::cout << component.errorString().toUtf8().constData() << std::endl;
        Q_ASSERT(0);
    }
    Q_ASSERT(component.status() == QQmlComponent::Ready);

    QObject* obj = component.create(objectContext);
    Q_ASSERT(obj);

    int rt = app.exec();
//     trackerThread.quit();
    return rt;
}
<|endoftext|>


<commit_before>#include <QtQuick>

#include "person.h"
#include "company.h"

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "Logger"
#include "LogManager"

// Includes below are needed for manual configuration. If you use .conf file for configuring,
// just PropertyConfigurator is enough
//#include "ConsoleAppender"
//#include "ColorConsoleAppender"
//#include "SimpleTimeLayout"
//#include "SystemlogAppender"
//#include "Level"
//#include "DailyRollingFileAppender"
//#include "helpers/factory.h"
//#include "Appender"

#include "PropertyConfigurator"

#include <QFile>
#include "qmllogger.h"

//Log4Qt::Appender *create_system_log_appender() {
//    return new Log4Qt::SystemLogAppender;
//}

/**
 * @brief initLogging
 * @param app Is used for determining app-specific config, log file locations, etc
 */
void initLogging(const QCoreApplication& app)
{

    const QString& binaryName = QCoreApplication::applicationName();
    const QString logConfigFilePath("/home/nemo/.config/" + binaryName + "/log4qt.conf");
    const QString fallbackLogConfigPath("/usr/share/" + binaryName + "/log4qt.conf");

    const QString& usedConfigFile = QFile::exists(logConfigFilePath) ? logConfigFilePath : fallbackLogConfigPath;
    Log4Qt::PropertyConfigurator::configure(usedConfigFile);
    Log4Qt::LogManager::setHandleQtMessages(true);

    qDebug() << "Using following log config file: " << usedConfigFile;

    /**
    // Normally you call it all from .conf properties, but you can instantiate it manually too
    Log4Qt::Factory::registerAppender("org.apache.log4j.SystemLogAppender", create_system_log_appender);
    Log4Qt::LogManager::rootLogger();

    // Note that it doesn't work for QML logs from device

    Log4Qt::SimpleTimeLayout *p_layout = new Log4Qt::SimpleTimeLayout();

    p_layout->setName(QLatin1String("root layout"));
    p_layout->activateOptions();

    // Create an appender
    Log4Qt::ColorConsoleAppender *p_consoleAppender = new Log4Qt::ColorConsoleAppender(p_layout, Log4Qt::ColorConsoleAppender::STDOUT_TARGET);
    p_consoleAppender->setName(QLatin1String("root console appender"));
    p_consoleAppender->activateOptions();

    Log4Qt::SystemLogAppender *p_syslogAppender = new Log4Qt::SystemLogAppender();
    p_syslogAppender->setServiceName("journalctl");
    p_syslogAppender->setName(QLatin1String("root sysylog appender"));
    p_syslogAppender->setLayout(p_layout);

    // Root logger gets all levels of logs, but let's send only
    // important ones to syslog
    p_syslogAppender->setThreshold(Log4Qt::Level(Log4Qt::Level::ERROR_INT));

    p_syslogAppender->activateOptions();

    Log4Qt::DailyRollingFileAppender *p_fileAppender =
            new Log4Qt::DailyRollingFileAppender();
    p_fileAppender->setFile(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
                            + "/" + applicationName + "/" + applicationName +".log");
    p_fileAppender->setDatePattern(Log4Qt::DailyRollingFileAppender::DAILY_ROLLOVER);
    p_fileAppender->setLayout(p_layout);
    p_syslogAppender->setName(QLatin1String("root file appender"));
    p_fileAppender->activateOptions();

    // Set appenders on root logger
    Log4Qt::Logger::rootLogger()->addAppender(p_consoleAppender);
    Log4Qt::Logger::rootLogger()->addAppender(p_syslogAppender);
    Log4Qt::Logger::rootLogger()->addAppender(p_fileAppender);
    */

    Log4Qt::Logger::logger(QLatin1String("Main Logger"))->info("Logging started");

    bool handingMessages = Log4Qt::LogManager::handleQtMessages();
    qDebug() << "Intercepting messages from qDebug is " << handingMessages;
    qDebug() << "temp loc" << QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    qDebug() << "config loc" << QStandardPaths::standardLocations(QStandardPaths::ConfigLocation);
    qDebug() << "cache loc" << QStandardPaths::standardLocations(QStandardPaths::CacheLocation);
    qDebug() << "generic cache loc" << QStandardPaths::standardLocations(QStandardPaths::GenericCacheLocation);
    qDebug() << "data loc" << QStandardPaths::standardLocations(QStandardPaths::DataLocation);
    qDebug() << "generic data loc" << QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
    qDebug() << "appName: " << QCoreApplication::applicationName();
    qDebug() << "appFilePath: " << QCoreApplication::applicationFilePath();
    qDebug() << "appDirPath: " << QCoreApplication::applicationDirPath();
}

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

    qmlRegisterType<Person>("harbour.log4qtdemo", 0, 1, "Person");
    qmlRegisterType<Company>("harbour.log4qtdemo", 0, 1, "Company");
    qmlRegisterType<QmlLogger>("harbour.log4qtdemo", 0, 1, "Logger");
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    initLogging(*app);

    QScopedPointer<QQuickView> view(SailfishApp::createView());
    qDebug() << "app's name: " << app->applicationName();
    qDebug() << "app's die path: " << app->applicationDirPath();

    view->setSource(SailfishApp::pathTo("qml/main.qml"));
//    view->rootContext()->setContextProperty("appVersion", APP_VERSION);
//    view->rootContext()->setContextProperty("appBuildNum", APP_BUILDNUM);
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
//    view->engine()->addImportPath(SailfishApp::pathTo("lib").toString());

    view->show();

    return app->exec();
}
<commit_msg>Minor cleanup<commit_after>#include <QtQuick>

#include "person.h"
#include "company.h"

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "Logger"
#include "LogManager"

// Includes below are needed for manual configuration. If you use .conf file for configuring,
// just PropertyConfigurator is enough
//#include "ConsoleAppender"
//#include "ColorConsoleAppender"
//#include "SimpleTimeLayout"
//#include "SystemlogAppender"
//#include "Level"
//#include "DailyRollingFileAppender"
//#include "helpers/factory.h"
//#include "Appender"

#include "PropertyConfigurator"

#include <QFile>
#include "qmllogger.h"

//Log4Qt::Appender *create_system_log_appender() {
//    return new Log4Qt::SystemLogAppender;
//}

/**
 * @brief initLogging
 * @param app Is used for determining app-specific config, log file locations, etc
 */
void initLogging()
{
    const QString& binaryName = QCoreApplication::applicationName();
    const QString logConfigFilePath("/home/nemo/.config/" + binaryName + "/log4qt.conf");
    const QString fallbackLogConfigPath("/usr/share/" + binaryName + "/log4qt.conf");

    const QString& usedConfigFile = QFile::exists(logConfigFilePath) ? logConfigFilePath : fallbackLogConfigPath;
    Log4Qt::PropertyConfigurator::configure(usedConfigFile);
    Log4Qt::LogManager::setHandleQtMessages(true);

    qDebug() << "Using following log config file: " << usedConfigFile;

    /**
    // Normally you call it all from .conf properties, but you can instantiate it manually too
    Log4Qt::Factory::registerAppender("org.apache.log4j.SystemLogAppender", create_system_log_appender);
    Log4Qt::LogManager::rootLogger();

    // Note that it doesn't work for QML logs from device

    Log4Qt::SimpleTimeLayout *p_layout = new Log4Qt::SimpleTimeLayout();

    p_layout->setName(QLatin1String("root layout"));
    p_layout->activateOptions();

    // Create an appender
    Log4Qt::ColorConsoleAppender *p_consoleAppender = new Log4Qt::ColorConsoleAppender(p_layout, Log4Qt::ColorConsoleAppender::STDOUT_TARGET);
    p_consoleAppender->setName(QLatin1String("root console appender"));
    p_consoleAppender->activateOptions();

    Log4Qt::SystemLogAppender *p_syslogAppender = new Log4Qt::SystemLogAppender();
    p_syslogAppender->setServiceName("journalctl");
    p_syslogAppender->setName(QLatin1String("root sysylog appender"));
    p_syslogAppender->setLayout(p_layout);

    // Root logger gets all levels of logs, but let's send only
    // important ones to syslog
    p_syslogAppender->setThreshold(Log4Qt::Level(Log4Qt::Level::ERROR_INT));

    p_syslogAppender->activateOptions();

    Log4Qt::DailyRollingFileAppender *p_fileAppender =
            new Log4Qt::DailyRollingFileAppender();
    p_fileAppender->setFile(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
                            + "/" + applicationName + "/" + applicationName +".log");
    p_fileAppender->setDatePattern(Log4Qt::DailyRollingFileAppender::DAILY_ROLLOVER);
    p_fileAppender->setLayout(p_layout);
    p_syslogAppender->setName(QLatin1String("root file appender"));
    p_fileAppender->activateOptions();

    // Set appenders on root logger
    Log4Qt::Logger::rootLogger()->addAppender(p_consoleAppender);
    Log4Qt::Logger::rootLogger()->addAppender(p_syslogAppender);
    Log4Qt::Logger::rootLogger()->addAppender(p_fileAppender);
    */

    Log4Qt::Logger::logger(QLatin1String("Main Logger"))->info("Logging started");

    bool handingMessages = Log4Qt::LogManager::handleQtMessages();
    qDebug() << "Intercepting messages from qDebug is " << handingMessages;
    qDebug() << "temp loc" << QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    qDebug() << "config loc" << QStandardPaths::standardLocations(QStandardPaths::ConfigLocation);
    qDebug() << "cache loc" << QStandardPaths::standardLocations(QStandardPaths::CacheLocation);
    qDebug() << "generic cache loc" << QStandardPaths::standardLocations(QStandardPaths::GenericCacheLocation);
    qDebug() << "data loc" << QStandardPaths::standardLocations(QStandardPaths::DataLocation);
    qDebug() << "generic data loc" << QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
    qDebug() << "appName: " << QCoreApplication::applicationName();
    qDebug() << "appFilePath: " << QCoreApplication::applicationFilePath();
    qDebug() << "appDirPath: " << QCoreApplication::applicationDirPath();
}

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

    qmlRegisterType<Person>("harbour.log4qtdemo", 0, 1, "Person");
    qmlRegisterType<Company>("harbour.log4qtdemo", 0, 1, "Company");
    qmlRegisterType<QmlLogger>("harbour.log4qtdemo", 0, 1, "Logger");
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    initLogging();

    QScopedPointer<QQuickView> view(SailfishApp::createView());
    qDebug() << "app's name: " << app->applicationName();
    qDebug() << "app's die path: " << app->applicationDirPath();

    view->setSource(SailfishApp::pathTo("qml/main.qml"));
//    view->rootContext()->setContextProperty("appVersion", APP_VERSION);
//    view->rootContext()->setContextProperty("appBuildNum", APP_BUILDNUM);
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
//    view->engine()->addImportPath(SailfishApp::pathTo("lib").toString());

    view->show();

    return app->exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDebug>
#include <QThread>

#include <KDBusService>
#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    KDBusService service(KDBusService::Unique);

    QCommandLineParser parser;
    parser.addOption(QCommandLineOption("reset", i18n("Reset the database")));
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    if (parser.isSet("reset")) {
//         KokoConfig config;
//         config.reset();

//         ImageStorage::reset();
    }

    QThread trackerThread;

    QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    Q_ASSERT(locations.size() >= 1);
//     qDebug() << locations;
//     FileSystemTracker tracker;
//     tracker.setFolder(locations.first());
//     tracker.moveToThread(&trackerThread);

//     Koko::Processor processor;
//     QObject::connect(&tracker, &FileSystemTracker::imageAdded, &processor, &Koko::Processor::addFile);
//     QObject::connect(&tracker, &FileSystemTracker::imageRemoved, &processor, &Koko::Processor::removeFile);
//     QObject::connect(&tracker, &FileSystemTracker::initialScanComplete, &processor, &Koko::Processor::initialScanCompleted);
//
//     trackerThread.start();
//     tracker.init();
//
//     KokoConfig config;

    QQmlEngine engine;
    QQmlContext* objectContext = engine.rootContext();
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", QString(qgetenv("PLASMA_PLATFORM")));
    engine.rootContext()->setContextProperty("bookLocations", locations);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);

    QString path;
    if (qgetenv("PLASMA_PLATFORM") == QByteArray("phone")) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    QQmlComponent component(&engine, path);
    if (component.isError()) {
        std::cout << component.errorString().toUtf8().constData() << std::endl;
        Q_ASSERT(0);
    }
    Q_ASSERT(component.status() == QQmlComponent::Ready);

    QObject* obj = component.create(objectContext);
    Q_ASSERT(obj);

    int rt = app.exec();
//     trackerThread.quit();
    return rt;
}
<commit_msg>Less assumptions, more proper platform sniff<commit_after>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDebug>
#include <QThread>

#include <KDBusService>
#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    KDBusService service(KDBusService::Unique);

    QCommandLineParser parser;
    parser.addOption(QCommandLineOption("reset", i18n("Reset the database")));
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    if (parser.isSet("reset")) {
//         KokoConfig config;
//         config.reset();

//         ImageStorage::reset();
    }

    QThread trackerThread;

    QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    Q_ASSERT(locations.size() >= 1);
//     qDebug() << locations;
//     FileSystemTracker tracker;
//     tracker.setFolder(locations.first());
//     tracker.moveToThread(&trackerThread);

//     Koko::Processor processor;
//     QObject::connect(&tracker, &FileSystemTracker::imageAdded, &processor, &Koko::Processor::addFile);
//     QObject::connect(&tracker, &FileSystemTracker::imageRemoved, &processor, &Koko::Processor::removeFile);
//     QObject::connect(&tracker, &FileSystemTracker::initialScanComplete, &processor, &Koko::Processor::initialScanCompleted);
//
//     trackerThread.start();
//     tracker.init();
//
//     KokoConfig config;

    QQmlEngine engine;
    QQmlContext* objectContext = engine.rootContext();
    QString platformEnv(qgetenv("PLASMA_PLATFORM"));
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv);
    engine.rootContext()->setContextProperty("bookLocations", locations);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);

    QString path;
    if (platformEnv.startsWith("phone")) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    QQmlComponent component(&engine, path);
    if (component.isError()) {
        std::cout << component.errorString().toUtf8().constData() << std::endl;
        Q_ASSERT(0);
    }
    Q_ASSERT(component.status() == QQmlComponent::Ready);

    QObject* obj = component.create(objectContext);
    Q_ASSERT(obj);

    int rt = app.exec();
//     trackerThread.quit();
    return rt;
}
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * Get all distinct N-Queen solutions
     * @param n: The number of queens
     * @return: All distinct solutions
     * For example, A string '...Q' shows a queen on forth position
     */

    vector<vector<string> > rt_st;
    int n;

    vector<vector<string> > solveNQueens(int n) {
        // write your code here
    	string s1,s2,s3;
        std::vector<string> v_str;
        vector<int> v_int;

        if (n<1) return rt_st;
        this->n=n;

        int rt_flag=bfs(n,0,v_int);

        if(rt_flag==1) return rt_st;
        else cout<<rt_flag<<endl;
  	    rt_st.clear();
    }

    vector<string> vecInt_to_vecstring(std::vector<int> &v){
    	int i,j,k;
    	string s1;
    	std::vector<string> rt_s;
    	for (auto v1:v){
    		s1.clear();
    		for (i=1;i<=n;i++) s1+='.';
    		s1[v1]='Q';

    		rt_s.push_back(s1);

    	}

    	return rt_s;
    }

    int bfs(int n,int i,std::vector<int> &v){

    	if (i==n) rt_st.push_back(vecInt_to_vecstring(v));

    	int j,k;

    	for (j=1;j<=n;j++){
    		if (find(v.begin(),v.end(),j)!=v.end()){

    			v.push_back(j);
    			bfs(n,i+1,v);
    			v.pop_back();

    		}
    		else{
    			continue;
    		}
    	}

    	return 1;

    }

};
<commit_msg>Debugging 33<commit_after>class Solution {
public:
    /**
     * Get all distinct N-Queen solutions
     * @param n: The number of queens
     * @return: All distinct solutions
     * For example, A string '...Q' shows a queen on forth position
     */

    vector<vector<string> > rt_st;
    int n;

    vector<vector<string> > solveNQueens(int n) {
        // write your code here
    	string s1,s2,s3;
        std::vector<string> v_str;
        vector<int> v_int;

        if (n<1) return rt_st;
        this->n=n;

        int rt_flag=bfs(n,0,v_int);

        if(rt_flag==1) return rt_st;
        else cout<<rt_flag<<endl;
  	    rt_st.clear();
    }

    vector<string> vecInt_to_vecstring(std::vector<int> &v){
    	int i,j,k;
    	string s1;
    	std::vector<string> rt_s;
    	for (auto v1:v){
    		s1.clear();
    		for (i=1;i<=n;i++) s1+='.';
    		s1[v1]='Q';

    		rt_s.push_back(s1);

    	}

    	return rt_s;
    }

    int bfs(int n,int i,std::vector<int> &v){

    	if (i==n) rt_st.push_back(vecInt_to_vecstring(v));

    	int j,k;
    	long long dj_status=0,dj_status_bf=0;
    	for (const auto v1:v){
    		dj_status=dj_status|(1<<v1);
    		cout<<v1<<" ";
    	}

    	dj_status_bf=dj_status;
    	dj_status = ((dj_status<<1) | (dj_status>>1));
    	cout<<dj_status<<endl;

    	for (j=1;j<=n;j++){

    		if (find(v.begin(),v.end(),j)==v.end()){

				if ( ( dj_status & (1<<j)) == 0){
					v.push_back(j);
    				bfs(n,i+1,v);
    				v.pop_back();
				}

    		}
    		else{
    			continue;
    		}
    	}

    	return 1;

    }

};
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * @param A: A string includes Upper Case letters
     * @param B: A string includes Upper Case letter
     * @return:  if string A contains all of the characters in B return true
     *           else return false
     */

    typedef map<char,int> charHash;

    charHash keyHashLize(string s){
        	charHash s1;
        	for (int i=0;i<s.length();i++){
        		if (s1[s[i]]) s1[s[i]]++;
        		else s1[s[i]]=1;
        	}

        	return s1;
        }

    bool compareStrings(string A, string B) {
        // write your code here

        charHash s1=keyHashLize(A),t1=keyHashLize(B);
        if (!A.length() and B.length()) return false;
        if (!B.length()) return true;

        for (charHash::iterator t2=t1.begin();t2 != t1.end();t2++)
        {
        	if (! t2->second <= s1[t2->first] ) return false;
        }

        return true;

    }
};
<commit_msg>Solve No.55 in C++<commit_after>class Solution {
public:
    /**
     * @param A: A string includes Upper Case letters
     * @param B: A string includes Upper Case letter
     * @return:  if string A contains all of the characters in B return true
     *           else return false
     */

    typedef map<char,int> charHash;

    charHash keyHashLize(string s){
        	charHash s1;

        	for (int i=0;i<26;++i){
        	    s1['A'+i]=0;
        	    s1['a'+i]=0;
        	}
        	for (int i=0;i<s.length();i++){
        		if (s1[s[i]]) s1[s[i]]++;
        		else s1[s[i]]=1;
        	}

        	return s1;
        }

    bool compareStrings(string A, string B) {
        // write your code here

        charHash s1=keyHashLize(A),t1=keyHashLize(B);
        if (!A.length() and B.length()) return false;
        if (!B.length()) return true;

        for (charHash::iterator t2=t1.begin();t2 != t1.end();t2++)
        {
        	if (! (t2->second <= s1[t2->first]) ) return false;
        }

        return true;

    }
};
<|endoftext|>


<commit_before>/*
  Copyright 2012 David Robillard <http://drobilla.net>

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

/**
   @file pugl_win.cpp Windows/WGL Pugl Implementation.
*/

#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>

#include <stdio.h>
#include <stdlib.h>

#include "pugl_internal.h"

#ifndef WM_MOUSEWHEEL
#    define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WM_MOUSEHWHEEL
#    define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef WHEEL_DELTA
#    define WHEEL_DELTA 120
#endif

const int LOCAL_CLOSE_MSG = WM_USER + 50;

struct PuglInternalsImpl {
	HWND     hwnd;
	HDC      hdc;
	HGLRC    hglrc;
	WNDCLASS wc;
};

LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

PuglView*
puglCreate(PuglNativeWindow parent,
           const char*      title,
           int              width,
           int              height,
           bool             resizable,
           bool             visible)
{
	PuglView*      view = (PuglView*)calloc(1, sizeof(PuglView));
	PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
	if (!view || !impl) {
		return NULL;
	}

	view->impl   = impl;
	view->width  = width;
	view->height = height;

	// FIXME: This is nasty, and pugl should not have static anything.
	// Should class be a parameter?  Does this make sense on other platforms?
	static int wc_count = 0;
	char classNameBuf[256];
	_snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d\n", title, wc_count++);

	impl->wc.style         = CS_OWNDC;
	impl->wc.lpfnWndProc   = wndProc;
	impl->wc.cbClsExtra    = 0;
	impl->wc.cbWndExtra    = 0;
	impl->wc.hInstance     = 0;
	impl->wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	impl->wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	impl->wc.lpszMenuName  = NULL;
	impl->wc.lpszClassName = classNameBuf;
	RegisterClass(&impl->wc);

	int winFlags = WS_POPUPWINDOW | WS_CAPTION;
	if (resizable) {
		winFlags |= WS_SIZEBOX;
	}

	// Adjust the overall window size to accomodate our requested client size
	RECT wr = { 0, 0, width, height };
	AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);

	impl->hwnd = CreateWindowEx(
		WS_EX_TOPMOST,
 		classNameBuf, title,
		(addToDesktop ? WS_VISIBLE : 0) | (parent ? WS_CHILD : winFlags),
		0, 0, wr.right-wr.left, wr.bottom-wr.top,
		(HWND)parent, NULL, NULL, NULL);

	if (!impl->hwnd) {
		free(impl);
		free(view);
		return NULL;
	}

	SetWindowLongPtr(impl->hwnd, GWL_USERDATA, (LONG)view);

	impl->hdc = GetDC(impl->hwnd);

	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd, sizeof(pfd));
	pfd.nSize      = sizeof(pfd);
	pfd.nVersion   = 1;
	pfd.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 24;
	pfd.cDepthBits = 16;
	pfd.iLayerType = PFD_MAIN_PLANE;

	int format = ChoosePixelFormat(impl->hdc, &pfd);
	SetPixelFormat(impl->hdc, format, &pfd);

	impl->hglrc = wglCreateContext(impl->hdc);
	wglMakeCurrent(impl->hdc, impl->hglrc);

	view->width  = width;
	view->height = height;

	return view;
}

void
puglDestroy(PuglView* view)
{
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(view->impl->hglrc);
	ReleaseDC(view->impl->hwnd, view->impl->hdc);
	DestroyWindow(view->impl->hwnd);
	UnregisterClass(view->impl->wc.lpszClassName, NULL);
	free(view->impl);
	free(view);
}

static void
puglReshape(PuglView* view, int width, int height)
{
	wglMakeCurrent(view->impl->hdc, view->impl->hglrc);

	if (view->reshapeFunc) {
		view->reshapeFunc(view, width, height);
	} else {
		puglDefaultReshape(view, width, height);
	}

	view->width  = width;
	view->height = height;
}

void
puglDisplay(PuglView* view)
{
	wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	if (view->displayFunc) {
		view->displayFunc(view);
	}

	glFlush();
	SwapBuffers(view->impl->hdc);
	view->redisplay = false;
}

static PuglKey
keySymToSpecial(int sym)
{
	switch (sym) {
	case VK_F1:      return PUGL_KEY_F1;
	case VK_F2:      return PUGL_KEY_F2;
	case VK_F3:      return PUGL_KEY_F3;
	case VK_F4:      return PUGL_KEY_F4;
	case VK_F5:      return PUGL_KEY_F5;
	case VK_F6:      return PUGL_KEY_F6;
	case VK_F7:      return PUGL_KEY_F7;
	case VK_F8:      return PUGL_KEY_F8;
	case VK_F9:      return PUGL_KEY_F9;
	case VK_F10:     return PUGL_KEY_F10;
	case VK_F11:     return PUGL_KEY_F11;
	case VK_F12:     return PUGL_KEY_F12;
	case VK_LEFT:    return PUGL_KEY_LEFT;
	case VK_UP:      return PUGL_KEY_UP;
	case VK_RIGHT:   return PUGL_KEY_RIGHT;
	case VK_DOWN:    return PUGL_KEY_DOWN;
	case VK_PRIOR:   return PUGL_KEY_PAGE_UP;
	case VK_NEXT:    return PUGL_KEY_PAGE_DOWN;
	case VK_HOME:    return PUGL_KEY_HOME;
	case VK_END:     return PUGL_KEY_END;
	case VK_INSERT:  return PUGL_KEY_INSERT;
	case VK_SHIFT:   return PUGL_KEY_SHIFT;
	case VK_CONTROL: return PUGL_KEY_CTRL;
	case VK_MENU:    return PUGL_KEY_ALT;
	case VK_LWIN:    return PUGL_KEY_SUPER;
	case VK_RWIN:    return PUGL_KEY_SUPER;
	}
	return (PuglKey)0;
}

static void
processMouseEvent(PuglView* view, int button, bool press, LPARAM lParam)
{
	view->event_timestamp_ms = GetMessageTime();
	if (press) {
		SetCapture(view->impl->hwnd);
	} else {
		ReleaseCapture();
	}

	if (view->mouseFunc) {
		view->mouseFunc(view, button, press,
		                GET_X_LPARAM(lParam),
		                GET_Y_LPARAM(lParam));
	}
}

static void
setModifiers(PuglView* view)
{
	view->mods = 0;
	view->mods |= (GetKeyState(VK_SHIFT)   < 0) ? PUGL_MOD_SHIFT  : 0;
	view->mods |= (GetKeyState(VK_CONTROL) < 0) ? PUGL_MOD_CTRL   : 0;
	view->mods |= (GetKeyState(VK_MENU)    < 0) ? PUGL_MOD_ALT    : 0;
	view->mods |= (GetKeyState(VK_LWIN)    < 0) ? PUGL_MOD_SUPER  : 0;
	view->mods |= (GetKeyState(VK_RWIN)    < 0) ? PUGL_MOD_SUPER  : 0;
}

static LRESULT
handleMessage(PuglView* view, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	PuglKey     key;

	setModifiers(view);
	switch (message) {
	case WM_CREATE:
	case WM_SHOWWINDOW:
	case WM_SIZE:
		RECT rect;
		GetClientRect(view->impl->hwnd, &rect);
		puglReshape(view, rect.right, rect.bottom);
		view->width = rect.right;
		view->height = rect.bottom;
		break;
	case WM_PAINT:
		BeginPaint(view->impl->hwnd, &ps);
		puglDisplay(view);
		EndPaint(view->impl->hwnd, &ps);
		break;
	case WM_MOUSEMOVE:
		if (view->motionFunc) {
			view->motionFunc(view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
		}
		break;
	case WM_LBUTTONDOWN:
		processMouseEvent(view, 1, true, lParam);
		break;
	case WM_MBUTTONDOWN:
		processMouseEvent(view, 2, true, lParam);
		break;
	case WM_RBUTTONDOWN:
		processMouseEvent(view, 3, true, lParam);
		break;
	case WM_LBUTTONUP:
		processMouseEvent(view, 1, false, lParam);
		break;
	case WM_MBUTTONUP:
		processMouseEvent(view, 2, false, lParam);
		break;
	case WM_RBUTTONUP:
		processMouseEvent(view, 3, false, lParam);
		break;
	case WM_MOUSEWHEEL:
		if (view->scrollFunc) {
			view->scrollFunc(
				view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
				(int16_t)HIWORD(wParam) / (float)WHEEL_DELTA);
		}
		break;
	case WM_MOUSEHWHEEL:
		if (view->scrollFunc) {
			view->scrollFunc(
				view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
				(int16_t)HIWORD(wParam) / float(WHEEL_DELTA), 0);
		}
		break;
	case WM_KEYDOWN:
		view->event_timestamp_ms = (GetMessageTime());
		if (view->ignoreKeyRepeat && (lParam & (1 << 30))) {
			break;
		} // else nobreak
	case WM_KEYUP:
		if ((key = keySymToSpecial(wParam))) {
			if (view->specialFunc) {
				view->specialFunc(view, message == WM_KEYDOWN, key);
			}
		} else if (view->keyboardFunc) {
			view->keyboardFunc(view, message == WM_KEYDOWN, wParam);
		}
		break;
	case WM_QUIT:
	case LOCAL_CLOSE_MSG:
		if (view->closeFunc) {
			view->closeFunc(view);
		}
		break;
	default:
		return DefWindowProc(
			view->impl->hwnd, message, wParam, lParam);
	}

	return 0;
}

PuglStatus
puglProcessEvents(PuglView* view)
{
	MSG msg;
	while (PeekMessage(&msg, view->impl->hwnd, 0, 0, PM_REMOVE)) {
		handleMessage(view, msg.message, msg.wParam, msg.lParam);
	}

	if (view->redisplay) {
		InvalidateRect(view->impl->hwnd, NULL, FALSE);
	}

	return PUGL_SUCCESS;
}

LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWL_USERDATA);
	switch (message) {
	case WM_CREATE:
		PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0);
		return 0;
	case WM_CLOSE:
		PostMessage(hwnd, LOCAL_CLOSE_MSG, wParam, lParam);
		return 0;
	case WM_DESTROY:
		return 0;
	default:
		if (view) {
			return handleMessage(view, message, wParam, lParam);
		} else {
			return DefWindowProc(hwnd, message, wParam, lParam);
		}
	}
}

void
puglPostRedisplay(PuglView* view)
{
	view->redisplay = true;
}

PuglNativeWindow
puglGetNativeWindow(PuglView* view)
{
	return (PuglNativeWindow)view->impl->hwnd;
}
<commit_msg>Fix compilation error on Windows.  I think.<commit_after>/*
  Copyright 2012 David Robillard <http://drobilla.net>

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

/**
   @file pugl_win.cpp Windows/WGL Pugl Implementation.
*/

#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>

#include <stdio.h>
#include <stdlib.h>

#include "pugl_internal.h"

#ifndef WM_MOUSEWHEEL
#    define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WM_MOUSEHWHEEL
#    define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef WHEEL_DELTA
#    define WHEEL_DELTA 120
#endif

const int LOCAL_CLOSE_MSG = WM_USER + 50;

struct PuglInternalsImpl {
	HWND     hwnd;
	HDC      hdc;
	HGLRC    hglrc;
	WNDCLASS wc;
};

LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

PuglView*
puglCreate(PuglNativeWindow parent,
           const char*      title,
           int              width,
           int              height,
           bool             resizable,
           bool             visible)
{
	PuglView*      view = (PuglView*)calloc(1, sizeof(PuglView));
	PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
	if (!view || !impl) {
		return NULL;
	}

	view->impl   = impl;
	view->width  = width;
	view->height = height;

	// FIXME: This is nasty, and pugl should not have static anything.
	// Should class be a parameter?  Does this make sense on other platforms?
	static int wc_count = 0;
	char classNameBuf[256];
	_snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d\n", title, wc_count++);

	impl->wc.style         = CS_OWNDC;
	impl->wc.lpfnWndProc   = wndProc;
	impl->wc.cbClsExtra    = 0;
	impl->wc.cbWndExtra    = 0;
	impl->wc.hInstance     = 0;
	impl->wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	impl->wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	impl->wc.lpszMenuName  = NULL;
	impl->wc.lpszClassName = classNameBuf;
	RegisterClass(&impl->wc);

	int winFlags = WS_POPUPWINDOW | WS_CAPTION;
	if (resizable) {
		winFlags |= WS_SIZEBOX;
	}

	// Adjust the overall window size to accomodate our requested client size
	RECT wr = { 0, 0, width, height };
	AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);

	impl->hwnd = CreateWindowEx(
		WS_EX_TOPMOST,
 		classNameBuf, title,
		(visible ? WS_VISIBLE : 0) | (parent ? WS_CHILD : winFlags),
		0, 0, wr.right-wr.left, wr.bottom-wr.top,
		(HWND)parent, NULL, NULL, NULL);

	if (!impl->hwnd) {
		free(impl);
		free(view);
		return NULL;
	}

	SetWindowLongPtr(impl->hwnd, GWL_USERDATA, (LONG)view);

	impl->hdc = GetDC(impl->hwnd);

	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd, sizeof(pfd));
	pfd.nSize      = sizeof(pfd);
	pfd.nVersion   = 1;
	pfd.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 24;
	pfd.cDepthBits = 16;
	pfd.iLayerType = PFD_MAIN_PLANE;

	int format = ChoosePixelFormat(impl->hdc, &pfd);
	SetPixelFormat(impl->hdc, format, &pfd);

	impl->hglrc = wglCreateContext(impl->hdc);
	wglMakeCurrent(impl->hdc, impl->hglrc);

	view->width  = width;
	view->height = height;

	return view;
}

void
puglDestroy(PuglView* view)
{
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(view->impl->hglrc);
	ReleaseDC(view->impl->hwnd, view->impl->hdc);
	DestroyWindow(view->impl->hwnd);
	UnregisterClass(view->impl->wc.lpszClassName, NULL);
	free(view->impl);
	free(view);
}

static void
puglReshape(PuglView* view, int width, int height)
{
	wglMakeCurrent(view->impl->hdc, view->impl->hglrc);

	if (view->reshapeFunc) {
		view->reshapeFunc(view, width, height);
	} else {
		puglDefaultReshape(view, width, height);
	}

	view->width  = width;
	view->height = height;
}

void
puglDisplay(PuglView* view)
{
	wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	if (view->displayFunc) {
		view->displayFunc(view);
	}

	glFlush();
	SwapBuffers(view->impl->hdc);
	view->redisplay = false;
}

static PuglKey
keySymToSpecial(int sym)
{
	switch (sym) {
	case VK_F1:      return PUGL_KEY_F1;
	case VK_F2:      return PUGL_KEY_F2;
	case VK_F3:      return PUGL_KEY_F3;
	case VK_F4:      return PUGL_KEY_F4;
	case VK_F5:      return PUGL_KEY_F5;
	case VK_F6:      return PUGL_KEY_F6;
	case VK_F7:      return PUGL_KEY_F7;
	case VK_F8:      return PUGL_KEY_F8;
	case VK_F9:      return PUGL_KEY_F9;
	case VK_F10:     return PUGL_KEY_F10;
	case VK_F11:     return PUGL_KEY_F11;
	case VK_F12:     return PUGL_KEY_F12;
	case VK_LEFT:    return PUGL_KEY_LEFT;
	case VK_UP:      return PUGL_KEY_UP;
	case VK_RIGHT:   return PUGL_KEY_RIGHT;
	case VK_DOWN:    return PUGL_KEY_DOWN;
	case VK_PRIOR:   return PUGL_KEY_PAGE_UP;
	case VK_NEXT:    return PUGL_KEY_PAGE_DOWN;
	case VK_HOME:    return PUGL_KEY_HOME;
	case VK_END:     return PUGL_KEY_END;
	case VK_INSERT:  return PUGL_KEY_INSERT;
	case VK_SHIFT:   return PUGL_KEY_SHIFT;
	case VK_CONTROL: return PUGL_KEY_CTRL;
	case VK_MENU:    return PUGL_KEY_ALT;
	case VK_LWIN:    return PUGL_KEY_SUPER;
	case VK_RWIN:    return PUGL_KEY_SUPER;
	}
	return (PuglKey)0;
}

static void
processMouseEvent(PuglView* view, int button, bool press, LPARAM lParam)
{
	view->event_timestamp_ms = GetMessageTime();
	if (press) {
		SetCapture(view->impl->hwnd);
	} else {
		ReleaseCapture();
	}

	if (view->mouseFunc) {
		view->mouseFunc(view, button, press,
		                GET_X_LPARAM(lParam),
		                GET_Y_LPARAM(lParam));
	}
}

static void
setModifiers(PuglView* view)
{
	view->mods = 0;
	view->mods |= (GetKeyState(VK_SHIFT)   < 0) ? PUGL_MOD_SHIFT  : 0;
	view->mods |= (GetKeyState(VK_CONTROL) < 0) ? PUGL_MOD_CTRL   : 0;
	view->mods |= (GetKeyState(VK_MENU)    < 0) ? PUGL_MOD_ALT    : 0;
	view->mods |= (GetKeyState(VK_LWIN)    < 0) ? PUGL_MOD_SUPER  : 0;
	view->mods |= (GetKeyState(VK_RWIN)    < 0) ? PUGL_MOD_SUPER  : 0;
}

static LRESULT
handleMessage(PuglView* view, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	PuglKey     key;

	setModifiers(view);
	switch (message) {
	case WM_CREATE:
	case WM_SHOWWINDOW:
	case WM_SIZE:
		RECT rect;
		GetClientRect(view->impl->hwnd, &rect);
		puglReshape(view, rect.right, rect.bottom);
		view->width = rect.right;
		view->height = rect.bottom;
		break;
	case WM_PAINT:
		BeginPaint(view->impl->hwnd, &ps);
		puglDisplay(view);
		EndPaint(view->impl->hwnd, &ps);
		break;
	case WM_MOUSEMOVE:
		if (view->motionFunc) {
			view->motionFunc(view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
		}
		break;
	case WM_LBUTTONDOWN:
		processMouseEvent(view, 1, true, lParam);
		break;
	case WM_MBUTTONDOWN:
		processMouseEvent(view, 2, true, lParam);
		break;
	case WM_RBUTTONDOWN:
		processMouseEvent(view, 3, true, lParam);
		break;
	case WM_LBUTTONUP:
		processMouseEvent(view, 1, false, lParam);
		break;
	case WM_MBUTTONUP:
		processMouseEvent(view, 2, false, lParam);
		break;
	case WM_RBUTTONUP:
		processMouseEvent(view, 3, false, lParam);
		break;
	case WM_MOUSEWHEEL:
		if (view->scrollFunc) {
			view->scrollFunc(
				view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
				(int16_t)HIWORD(wParam) / (float)WHEEL_DELTA);
		}
		break;
	case WM_MOUSEHWHEEL:
		if (view->scrollFunc) {
			view->scrollFunc(
				view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
				(int16_t)HIWORD(wParam) / float(WHEEL_DELTA), 0);
		}
		break;
	case WM_KEYDOWN:
		view->event_timestamp_ms = (GetMessageTime());
		if (view->ignoreKeyRepeat && (lParam & (1 << 30))) {
			break;
		} // else nobreak
	case WM_KEYUP:
		if ((key = keySymToSpecial(wParam))) {
			if (view->specialFunc) {
				view->specialFunc(view, message == WM_KEYDOWN, key);
			}
		} else if (view->keyboardFunc) {
			view->keyboardFunc(view, message == WM_KEYDOWN, wParam);
		}
		break;
	case WM_QUIT:
	case LOCAL_CLOSE_MSG:
		if (view->closeFunc) {
			view->closeFunc(view);
		}
		break;
	default:
		return DefWindowProc(
			view->impl->hwnd, message, wParam, lParam);
	}

	return 0;
}

PuglStatus
puglProcessEvents(PuglView* view)
{
	MSG msg;
	while (PeekMessage(&msg, view->impl->hwnd, 0, 0, PM_REMOVE)) {
		handleMessage(view, msg.message, msg.wParam, msg.lParam);
	}

	if (view->redisplay) {
		InvalidateRect(view->impl->hwnd, NULL, FALSE);
	}

	return PUGL_SUCCESS;
}

LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWL_USERDATA);
	switch (message) {
	case WM_CREATE:
		PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0);
		return 0;
	case WM_CLOSE:
		PostMessage(hwnd, LOCAL_CLOSE_MSG, wParam, lParam);
		return 0;
	case WM_DESTROY:
		return 0;
	default:
		if (view) {
			return handleMessage(view, message, wParam, lParam);
		} else {
			return DefWindowProc(hwnd, message, wParam, lParam);
		}
	}
}

void
puglPostRedisplay(PuglView* view)
{
	view->redisplay = true;
}

PuglNativeWindow
puglGetNativeWindow(PuglView* view)
{
	return (PuglNativeWindow)view->impl->hwnd;
}
<|endoftext|>


<commit_before>#include <bson.h>
#include <stdio.h>
#include "hphp/runtime/base/base-includes.h"

namespace HPHP {

static bool
cbson_loads_visit_int64 (const bson_iter_t *iter,
                         const char*        key,
                         int64_t          v_int64,
                         Array             *output)
{
  output->add(String(key),v_int64);

  return false;
}

static bool
cbson_loads_visit_bool (const bson_iter_t *iter,
                        const char        *key,
                        bool        v_bool,
                        Array       *output)
{
   output->add(String(key), v_bool);
   return false;
}

static bool
cbson_loads_visit_array (const bson_iter_t *iter,
                        const char        *key,
                        const bson_t     v_array,
                        Array           *output)
{
   output->add(String(key), v_array)
   return false;
}

static bool
cbson_loads_visit_double (const bson_iter_t *iter,
                          const char        *key,
                          double             v_double,
                          Array             *output)
{
   output->add(String(key),v_double);
   return false;
}

static bool
cbson_loads_visit_utf8 (const bson_iter_t *iter,
                        const char        *key,
                        size_t             v_utf8_len,
                        const char        *v_utf8,
                        Array             *output)
{
   output->add(String(key),v_utf8);
   return false;
}

static const bson_visitor_t gLoadsVisitors = {
   .visit_double = cbson_loads_visit_double,
   .visit_utf8 = cbson_loads_visit_utf8,
   .visit_array = cbson_loads_visit_array,
   .visit_bool = cbson_loads_visit_bool,
   .visit_int64 = cbson_loads_visit_int64;
};

static Array *
cbson_loads (bson_t * bson)
{
  bson_reader_t * reader;
  const bson_t * b;
  bson_iter_t iter;
  bool eof;

  Array ret = Array();

  reader = bson_reader_new_from_data((uint8_t *)bson.c_str(), bson.size());

  if (!(b = bson_reader_read(reader, &eof))
  {
    std::cout << "Buffer contained invalid BSON." << endl;
    return NULL;
  }

  do {
    if (!bson_iter_init(&iter, b))
    {
      bson_reader_destroy(reader);
      std::cout << "Failed to initiate iterator." << endl;
      return NULL;
    }
    bson_iter_visit_all(&iter, &gLoadsVisitors, &ret);
  } while ((b = bson_reader_read(reader, &eof)));

  bson_reader_destroy(reader);

  if (!eof) {
    std::cout << "Buffer contained invalid BSON." << endl;
    return NULL;
  }

  return ret;
}
}
<commit_msg>Fixed missing parentheses<commit_after>#include <bson.h>
#include <stdio.h>
#include "hphp/runtime/base/base-includes.h"

namespace HPHP {

static bool
cbson_loads_visit_int64 (const bson_iter_t *iter,
                         const char*        key,
                         int64_t          v_int64,
                         Array             *output)
{
  output->add(String(key),v_int64);

  return false;
}

static bool
cbson_loads_visit_bool (const bson_iter_t *iter,
                        const char        *key,
                        bool        v_bool,
                        Array       *output)
{
   output->add(String(key), v_bool);
   return false;
}

static bool
cbson_loads_visit_array (const bson_iter_t *iter,
                        const char        *key,
                        const bson_t     v_array,
                        Array           *output)
{
   output->add(String(key), v_array)
   return false;
}

static bool
cbson_loads_visit_double (const bson_iter_t *iter,
                          const char        *key,
                          double             v_double,
                          Array             *output)
{
   output->add(String(key),v_double);
   return false;
}

static bool
cbson_loads_visit_utf8 (const bson_iter_t *iter,
                        const char        *key,
                        size_t             v_utf8_len,
                        const char        *v_utf8,
                        Array             *output)
{
   output->add(String(key),v_utf8);
   return false;
}

static const bson_visitor_t gLoadsVisitors = {
   .visit_double = cbson_loads_visit_double,
   .visit_utf8 = cbson_loads_visit_utf8,
   .visit_array = cbson_loads_visit_array,
   .visit_bool = cbson_loads_visit_bool,
   .visit_int64 = cbson_loads_visit_int64;
};

static Array *
cbson_loads (bson_t * bson)
{
  bson_reader_t * reader;
  const bson_t * b;
  bson_iter_t iter;
  bool eof;

  Array ret = Array();

  reader = bson_reader_new_from_data((uint8_t *)bson.c_str(), bson.size());

  if (!(b = bson_reader_read(reader, &eof)))
  {
    std::cout << "Buffer contained invalid BSON." << endl;
    return NULL;
  }

  do {
    if (!bson_iter_init(&iter, b))
    {
      bson_reader_destroy(reader);
      std::cout << "Failed to initiate iterator." << endl;
      return NULL;
    }
    bson_iter_visit_all(&iter, &gLoadsVisitors, &ret);
  } while ((b = bson_reader_read(reader, &eof)));

  bson_reader_destroy(reader);

  if (!eof) {
    std::cout << "Buffer contained invalid BSON." << endl;
    return NULL;
  }

  return ret;
}
}
<|endoftext|>