blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ecbad2015cd2437c818ee49ecc72260224941e0 | d329e7db05b93b26641be508cdc9c9eb993ea067 | /recipes/prometheus-cpp/all/test_package/test_package.cpp | f22948e7726c1f26580a73abc352ee87b36891fb | [] | no_license | Tarjei400/conan-packages | 2019582cf478b427085fceb4f8c290bed9f8eb48 | d68315abf78d2cbec86aa6f9a3fc5869b1e4d054 | refs/heads/master | 2023-01-30T12:23:09.794868 | 2020-12-16T10:03:29 | 2020-12-16T10:03:29 | 321,362,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | cpp | #ifdef ENABLE_PULL
#include <prometheus/exposer.h>
#endif
#include <prometheus/counter.h>
#include <prometheus/registry.h>
#include <string>
#include <iostream>
#include <cstdlib>
int main(int argc, char *argv[])
{
using namespace prometheus;
#ifdef ENABLE_PULL
// create an http server running on port 8080
Exposer exposer{"127.0.0.1:8081"};
#endif
// create a metrics registry with component=main labels applied to all its
// metrics
auto registry = std::make_shared<Registry>();
// add a new counter family to the registry (families combine values with the
// same name, but distinct label dimensions)
auto& counter_family = BuildCounter()
.Name("time_running_seconds_total")
.Help("How many seconds is this server running?")
.Labels({{"label", "value"}})
.Register(*registry);
// add a counter to the metric family
auto& second_counter = counter_family.Add(
{{"another_label", "value"}, {"yet_another_label", "value"}});
std::cout << "Tested prometheus-cpp - ok " << std::endl;
return EXIT_SUCCESS;
}
| [
"adrian.jutrowski@redacreltd.com"
] | adrian.jutrowski@redacreltd.com |
d5035e58bee74350fff0b137dfdbd249bf7a7c03 | 2b1846cd62707be78851f2adb91d3da61fa3a73e | /c_02/list.hpp | 66578e14a0882def630c72d5d4991019447a12f2 | [] | no_license | y-shindoh/coding_interview | 1fb2af920696e4b3d373c87d9bdaae0564696796 | 88bd5665fd246703832f3e5eccba4daaf2026fbc | refs/heads/master | 2020-05-31T01:07:05.629942 | 2015-12-02T11:39:57 | 2015-12-02T11:39:57 | 35,543,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,382 | hpp | /* -*- coding: utf-8; tab-width: 4 -*- */
/**
* @file list.hpp
* @brief 「世界で闘うプログラミング力を鍛える150問」の2章の回答
* @author Yasutaka SHINDOH / 新堂 安孝
* @note see http://www.amazon.co.jp/dp/4839942390 .
*/
#ifndef __LIST_HPP__
#define __LIST_HPP__ "list.hpp"
#include <cstddef>
#include <cstdio>
#include <cassert>
//#define USE_DOUBLY_LINKED_LIST "use_doubly_linked_list"
/**
* リストを構成するノード
*/
template<typename TYPE>
class Node
{
private:
TYPE data_; ///< データ
#ifdef USE_DOUBLY_LINKED_LIST
Node<TYPE>* previous_; ///< 前のノード
#endif // USE_DOUBLY_LINKED_LIST
Node<TYPE>* next_; ///< 次のノード
public:
#ifdef USE_DOUBLY_LINKED_LIST
/**
* コンストラクタ
* @param[in] data 格納するデータ
* @param[in] previous 前のノード
* @param[in] next 次のノード
*/
Node(const TYPE& data,
Node<TYPE>* previous = 0,
Node<TYPE>* next = 0)
: data_(data), previous_(previous), next_(next)
{
;
}
#else // USE_DOUBLY_LINKED_LIST
/**
* コンストラクタ
* @param[in] data 格納するデータ
* @param[in] next 次のノード
*/
Node(const TYPE& data,
Node<TYPE>* next = 0)
: data_(data), next_(next)
{
;
}
#endif // USE_DOUBLY_LINKED_LIST
/**
* データを格納
* @param[in] data データ
*/
void
set_data(const TYPE& data)
{
data_ = data;
}
/**
* データを取得
* @return データ
*/
TYPE
get_data() const
{
return data_;
}
#ifdef USE_DOUBLY_LINKED_LIST
/**
* 前のノードを格納
* @param[in] previous 前のノードのポインタ
*/
void
set_previous(Node<TYPE>* previous)
{
previous_ = previous;
}
/**
* 前のノードを取得
* @return 前のノードのポインタ
*/
Node<TYPE>*
get_previous() const
{
return previous_;
}
#endif // USE_DOUBLY_LINKED_LIST
/**
* 次のノードを格納
* @param[in] next 次のノード
*/
void
set_next(Node<TYPE>* next)
{
next_ = next;
}
/**
* 次のノードを取得
* @return 次のノード
*/
Node<TYPE>*
get_next() const
{
return next_;
}
/**
* 配列からリストを生成
* @param[in] array 配列
* @param[in] length 引数 @a array の要素数
* @return リストの先頭のノード
*/
static Node<TYPE>*
MakeLinkedList(const TYPE* array,
size_t length)
{
Node<TYPE>* top(0);
Node<TYPE>* c;
Node<TYPE>* p(0);
for (size_t i(0); i < length; ++i) {
c = new Node<TYPE>(array[i]);
#ifdef USE_DOUBLY_LINKED_LIST
c->set_previous(p);
#endif // USE_DOUBLY_LINKED_LIST
if (p) p->set_next(c);
if (!top) top = c;
p = c;
}
return top;
}
/**
* リストを削除
* @param[in,out] node リストの先頭ノード
*/
static void
DeleteLinkedList(Node<TYPE>* node)
{
Node<TYPE>* n;
while (node) {
n = node->get_next();
delete node;
node = n;
}
}
/**
* リストの各ノードのデータを表示
* @param[in] node リストの先頭ノード
*/
static void
PrintLinkedList(const Node<TYPE>* node)
{
bool flag = false;
while (node) {
if (flag) std::printf(", ");
std::printf("%G", (double)node->get_data());
node = node->get_next();
flag = true;
}
if (flag) std::printf("\n");
}
};
#endif // __LIST_HPP__
| [
"cube@quruli.ivory.ne.jp"
] | cube@quruli.ivory.ne.jp |
2658fc437e564b998b6c8c924a3d7a5987bf8aec | 76f99fbe3a809d73e4fd74c39c4175236c33ca42 | /binding-genasm/core_bindings.cpp | 264e85179b65b1db5f8392ce14611ab4d40974be | [
"BSD-2-Clause"
] | permissive | bokuweb/opencvjs | 4f9a90eed5b85eab445cd2372226bbb24c0230cf | 290313845d3f937dcd72045675b594d18790d591 | refs/heads/Optimizations | 2023-04-08T08:59:36.339673 | 2017-06-19T22:42:51 | 2017-06-19T22:42:51 | 98,154,074 | 0 | 0 | NOASSERTION | 2023-04-04T01:14:28 | 2017-07-24T05:56:56 | JavaScript | UTF-8 | C++ | false | false | 15,308 | cpp | ////////////////////////////////////////////////////////////////////////////////
// AUTHOR: Sajjad Taheri sajjadt[at]uci[at]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015, University of California, Irvine
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by the UC Irvine.
// 4. Neither the name of the UC Irvine 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 UC IRVINE ''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 UC IRVINE OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////
#include "opencv2/core.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/flann/flann.hpp"
#include "opencv2/ml.hpp"
#include "opencv2/photo.hpp"
#include "opencv2/shape.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/imgcodecs.hpp"
#include <emscripten/bind.h>
using namespace emscripten;
using namespace cv;
using namespace cv::flann;
using namespace cv::ml;
namespace Utils{
template<typename T>
emscripten::val data(const cv::Mat& mat) {
return emscripten::val(emscripten::memory_view<T>( (mat.total()*mat.elemSize())/sizeof(T), (T*) mat.data));
}
emscripten::val matPtrI(const cv::Mat& mat, int i) {
return emscripten::val(emscripten::memory_view<uint8_t>(mat.step1(0), mat.ptr(i)));
}
emscripten::val matPtrII(const cv::Mat& mat, int i, int j) {
return emscripten::val(emscripten::memory_view<uint8_t>(mat.step1(1), mat.ptr(i,j)));
}
emscripten::val matFromArray(const emscripten::val& object, int type) {
int w= object["width"].as<unsigned>();
int h= object["height"].as<unsigned>();
std::string str = object["data"]["buffer"].as<std::string>();
return emscripten::val(cv::Mat(h, w, type, (void*)str.data(), 0));
}
cv::Mat* createMat(Size size, int type, intptr_t data, size_t step) {
return new cv::Mat(size, type, reinterpret_cast<void*>(data), step);
}
cv::Mat* createMat2(const std::vector<unsigned char>& vector) {
return new cv::Mat(vector, false);
}
// returning MatSize
static std::vector<int> getMatSize(const cv::Mat& mat)
{
std::vector<int> size;
for (int i = 0; i < mat.dims; i++) {
size.push_back(mat.size[i]);
}
return size;
}
static Mat eye(int rows, int cols, int type) {
return Mat(cv::Mat::eye(rows, cols, type));
}
static Mat eye(Size size, int type) {
return Mat(cv::Mat::eye(size, type));
}
void convertTo(const Mat& obj, Mat& m, int rtype, double alpha, double beta) {
obj.convertTo(m, rtype, alpha, beta);
}
Size matSize(const cv::Mat& mat) {
return mat.size();
}
cv::Mat mat_zeros_iii(int arg0, int arg1, int arg2) {
return cv::Mat::zeros(arg0, arg1, arg2);
}
cv::Mat mat_zeros_Si(cv::Size arg0, int arg1) {
return cv::Mat::zeros(arg0,arg1);
}
cv::Mat mat_zeros_ipii(int arg0, const int* arg1, int arg2) {
return cv::Mat::zeros(arg0,arg1,arg2);
}
cv::Mat mat_ones_iii(int arg0, int arg1, int arg2) {
return cv::Mat::ones(arg0, arg1, arg2);
}
cv::Mat mat_ones_ipii(int arg0, const int* arg1, int arg2) {
return cv::Mat::ones(arg0, arg1, arg2);
}
cv::Mat mat_ones_Si(cv::Size arg0, int arg1) {
return cv::Mat::ones(arg0, arg1);
}
double matDot(const cv::Mat& obj, const Mat& mat) {
return obj.dot(mat);
}
Mat matMul(const cv::Mat& obj, const Mat& mat, double scale) {
return Mat(obj.mul(mat, scale));
}
Mat matT(const cv::Mat& obj) {
return Mat(obj.t());
}
Mat matInv(const cv::Mat& obj, int type) {
return Mat(obj.inv(type));
}
}
EMSCRIPTEN_BINDINGS(Utils) {
register_vector<int>("IntVector");
register_vector<char>("CharVector");
register_vector<unsigned>("UnsignedVector");
register_vector<unsigned char>("UCharVector");
register_vector<std::string>("StrVector");
register_vector<emscripten::val>("EmvalVector");
register_vector<float>("FloatVector");
register_vector<std::vector<int>>("IntVectorVector");
register_vector<std::vector<Point>>("PointVectorVector");
register_vector<cv::Point>("PointVector");
register_vector<cv::Vec4i>("Vec4iVector");
register_vector<cv::Mat>("MatVector");
register_vector<cv::KeyPoint>("KeyPointVector");
register_vector<cv::Rect>("RectVector");
register_vector<cv::Point2f>("Point2fVector");
emscripten::class_<cv::TermCriteria>("TermCriteria")
.constructor<>()
.constructor<int, int, double>()
.property("type", &cv::TermCriteria::type)
.property("maxCount", &cv::TermCriteria::maxCount)
.property("epsilon", &cv::TermCriteria::epsilon);
emscripten::class_<cv::Mat>("Mat")
.constructor<>()
//.constructor<const Mat&>()
.constructor<Size, int>()
.constructor<int, int, int>()
.constructor(&Utils::createMat, allow_raw_pointers())
.constructor(&Utils::createMat2, allow_raw_pointers())
.function("elemSize1", select_overload<size_t()const>(&cv::Mat::elemSize1))
//.function("assignTo", select_overload<void(Mat&, int)const>(&cv::Mat::assignTo))
.function("channels", select_overload<int()const>(&cv::Mat::channels))
.function("convertTo", select_overload<void(const Mat&, Mat&, int, double, double)>(&Utils::convertTo))
.function("total", select_overload<size_t()const>(&cv::Mat::total))
.function("row", select_overload<Mat(int)const>(&cv::Mat::row))
.class_function("eye",select_overload<Mat(int, int, int)>(&Utils::eye))
.class_function("eye",select_overload<Mat(Size, int)>(&Utils::eye))
.function("create", select_overload<void(int, int, int)>(&cv::Mat::create))
.function("create", select_overload<void(Size, int)>(&cv::Mat::create))
.function("rowRange", select_overload<Mat(int, int)const>(&cv::Mat::rowRange))
.function("rowRange", select_overload<Mat(const Range&)const>(&cv::Mat::rowRange))
.function("copyTo", select_overload<void(OutputArray)const>(&cv::Mat::copyTo))
.function("copyTo", select_overload<void(OutputArray, InputArray)const>(&cv::Mat::copyTo))
.function("elemSize", select_overload<size_t()const>(&cv::Mat::elemSize))
.function("type", select_overload<int()const>(&cv::Mat::type))
.function("empty", select_overload<bool()const>(&cv::Mat::empty))
.function("colRange", select_overload<Mat(int, int)const>(&cv::Mat::colRange))
.function("colRange", select_overload<Mat(const Range&)const>(&cv::Mat::colRange))
.function("step1", select_overload<size_t(int)const>(&cv::Mat::step1))
.function("clone", select_overload<Mat()const>(&cv::Mat::clone))
.class_function("ones",select_overload<Mat(int, int, int)>(&Utils::mat_ones_iii))
.class_function("ones",select_overload<Mat(Size, int)>(&Utils::mat_ones_Si))
.class_function("zeros",select_overload<Mat(int, int, int)>(&Utils::mat_zeros_iii))
.class_function("zeros",select_overload<Mat(Size, int)>(&Utils::mat_zeros_Si))
.function("depth", select_overload<int()const>(&cv::Mat::depth))
.function("col", select_overload<Mat(int)const>(&cv::Mat::col))
.function("dot", select_overload<double(const Mat&, const Mat&)>(&Utils::matDot))
.function("mul", select_overload<Mat(const Mat&, const Mat&, double)>(&Utils::matMul))
.function("inv", select_overload<Mat(const Mat&, int)>(&Utils::matInv))
.function("t", select_overload<Mat(const Mat&)>(&Utils::matT))
.property("rows", &cv::Mat::rows)
.property("cols", &cv::Mat::cols)
.function("data", &Utils::data<unsigned char>)
.function("data8S", &Utils::data<char>)
.function("data16u", &Utils::data<unsigned short>)
.function("data16s", &Utils::data<short>)
.function("data32s", &Utils::data<int>)
.function("data32f", &Utils::data<float>)
.function("data64f", &Utils::data<double>)
.function("ptr", select_overload<val(const Mat&, int)>(&Utils::matPtrI))
.function("ptr", select_overload<val(const Mat&, int, int)>(&Utils::matPtrII))
.function("size" , &Utils::getMatSize)
.function("get_uchar_at" , select_overload<unsigned char&(int)>(&cv::Mat::at<unsigned char>))
.function("get_uchar_at", select_overload<unsigned char&(int, int)>(&cv::Mat::at<unsigned char>))
.function("get_uchar_at", select_overload<unsigned char&(int, int, int)>(&cv::Mat::at<unsigned char>))
.function("get_ushort_at", select_overload<unsigned short&(int)>(&cv::Mat::at<unsigned short>))
.function("get_ushort_at", select_overload<unsigned short&(int, int)>(&cv::Mat::at<unsigned short>))
.function("get_ushort_at", select_overload<unsigned short&(int, int, int)>(&cv::Mat::at<unsigned short>))
.function("get_int_at" , select_overload<int&(int)>(&cv::Mat::at<int>) )
.function("get_int_at", select_overload<int&(int, int)>(&cv::Mat::at<int>) )
.function("get_int_at", select_overload<int&(int, int, int)>(&cv::Mat::at<int>) )
.function("get_double_at", select_overload<double&(int, int, int)>(&cv::Mat::at<double>))
.function("get_double_at", select_overload<double&(int)>(&cv::Mat::at<double>))
.function("get_double_at", select_overload<double&(int, int)>(&cv::Mat::at<double>))
.function("get_float_at", select_overload<float&(int)>(&cv::Mat::at<float>))
.function("get_float_at", select_overload<float&(int, int)>(&cv::Mat::at<float>))
.function("get_float_at", select_overload<float&(int, int, int)>(&cv::Mat::at<float>))
.function( "getROI_Rect", select_overload<Mat(const Rect&)const>(&cv::Mat::operator()));
emscripten::class_<cv::Vec<int,4>>("Vec4i")
.constructor<>()
.constructor<int, int, int, int>();
emscripten::class_<cv::RNG> ("RNG");
value_array<Size>("Size")
.element(&Size::height)
.element(&Size::width);
value_array<Point>("Point")
.element(&Point::x)
.element(&Point::y);
value_array<Point2f>("Point2f")
.element(&Point2f::x)
.element(&Point2f::y);
emscripten::class_<cv::Rect_<int>> ("Rect")
.constructor<>()
.constructor<const cv::Point_<int>&, const cv::Size_<int>&>()
.constructor<int, int, int, int>()
.constructor<const cv::Rect_<int>&>()
.property("x", &cv::Rect_<int>::x)
.property("y", &cv::Rect_<int>::y)
.property("width", &cv::Rect_<int>::width)
.property("height", &cv::Rect_<int>::height);
emscripten::class_<cv::Scalar_<double>> ("Scalar")
.constructor<>()
.constructor<double>()
.constructor<double, double>()
.constructor<double, double, double>()
.constructor<double, double, double, double>()
.class_function("all", &cv::Scalar_<double>::all)
.function("isReal", select_overload<bool()const>(&cv::Scalar_<double>::isReal));
function("matFromArray", &Utils::matFromArray);
constant("CV_8UC1", CV_8UC1) ;
constant("CV_8UC2", CV_8UC2) ;
constant("CV_8UC3", CV_8UC3) ;
constant("CV_8UC4", CV_8UC4) ;
constant("CV_8SC1", CV_8SC1) ;
constant("CV_8SC2", CV_8SC2) ;
constant("CV_8SC3", CV_8SC3) ;
constant("CV_8SC4", CV_8SC4) ;
constant("CV_16UC1", CV_16UC1) ;
constant("CV_16UC2", CV_16UC2) ;
constant("CV_16UC3", CV_16UC3) ;
constant("CV_16UC4", CV_16UC4) ;
constant("CV_16SC1", CV_16SC1) ;
constant("CV_16SC2", CV_16SC2) ;
constant("CV_16SC3", CV_16SC3) ;
constant("CV_16SC4", CV_16SC4) ;
constant("CV_32SC1", CV_32SC1) ;
constant("CV_32SC2", CV_32SC2) ;
constant("CV_32SC3", CV_32SC3) ;
constant("CV_32SC4", CV_32SC4) ;
constant("CV_32FC1", CV_32FC1) ;
constant("CV_32FC2", CV_32FC2) ;
constant("CV_32FC3", CV_32FC3) ;
constant("CV_32FC4", CV_32FC4) ;
constant("CV_64FC1", CV_64FC1) ;
constant("CV_64FC2", CV_64FC2) ;
constant("CV_64FC3", CV_64FC3) ;
constant("CV_64FC4", CV_64FC4) ;
constant("CV_8U", CV_8U);
constant("CV_8S", CV_8S);
constant("CV_16U", CV_16U);
constant("CV_16S", CV_16S);
constant("CV_32S", CV_32S);
constant("CV_32F", CV_32F);
constant("CV_32F", CV_32F);
constant("BORDER_CONSTANT", +cv::BorderTypes::BORDER_CONSTANT);
constant("BORDER_REPLICATE", +cv::BorderTypes::BORDER_REPLICATE);
constant("BORDER_REFLECT", +cv::BorderTypes::BORDER_REFLECT);
constant("BORDER_WRAP", +cv::BorderTypes::BORDER_WRAP);
constant("BORDER_REFLECT_101", +cv::BorderTypes::BORDER_REFLECT_101);
constant("BORDER_TRANSPARENT", +cv::BorderTypes::BORDER_TRANSPARENT);
constant("BORDER_REFLECT101", +cv::BorderTypes::BORDER_REFLECT101);
constant("BORDER_DEFAULT", +cv::BorderTypes::BORDER_DEFAULT);
constant("BORDER_ISOLATED", +cv::BorderTypes::BORDER_ISOLATED);
constant("NORM_INF", +cv::NormTypes::NORM_INF);
constant("NORM_L1", +cv::NormTypes::NORM_L1);
constant("NORM_L2", +cv::NormTypes::NORM_L2);
constant("NORM_L2SQR", +cv::NormTypes::NORM_L2SQR);
constant("NORM_HAMMING", +cv::NormTypes::NORM_HAMMING);
constant("NORM_HAMMING2", +cv::NormTypes::NORM_HAMMING2);
constant("NORM_TYPE_MASK", +cv::NormTypes::NORM_TYPE_MASK);
constant("NORM_RELATIVE", +cv::NormTypes::NORM_RELATIVE);
constant("NORM_MINMAX", +cv::NormTypes::NORM_MINMAX);
constant("INPAINT_NS", +cv::INPAINT_NS);
constant("INPAINT_TELEA", +cv::INPAINT_TELEA);
}
| [
"yebastikian@gmail.com"
] | yebastikian@gmail.com |
7adf5d7d022d87ca3b414d11c2c61ae70c122bcd | e5d7314e57789b78b80f5aa9367ba1c0c6cd59b1 | /chapter4/strtype3.cpp | 599cec213c46af823e6eb1a87c3d521ae158143a | [] | no_license | dga1t/cpp-primer-practice | 1b36da26922433647ac1396a3d6ffead88ad0178 | 8f68b71b16297f8c8d490d811ddc62dc4b3bbe2b | refs/heads/master | 2023-05-29T03:44:40.098175 | 2021-06-06T12:33:50 | 2021-06-06T12:33:50 | 321,054,667 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | cpp | #include <iostream>
#include <string>
#include <cstring>
int main() {
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
// assignment for string objects and character arrays
str1 = str2;
strcpy(charr1, charr2);
// appending for string objects and character arrays
str1 += " paste";
strcat(charr1, " juice");
// finding the length of a string object and a C-style string
int len1 = str1.size();
int len2 = strlen(charr1);
cout << "The string " << str1 << " contains " << len1 << " characters.\n";
cout << "The string " << charr1 << " contains " << len2 << " characters.\n";
return 0;
} | [
"dpsmnsk@gmail.com"
] | dpsmnsk@gmail.com |
aadb9c727bb81454389ef7a64edfdb899199382d | f5c323253e3abe9eb6097d28ad8124c78e0c8ce2 | /src/Modules/Heightmap/filters/raytracing/RayTracing.hpp | a2197e27071c7d1c8717336fad92b516739a11c9 | [] | no_license | VCityTeam/DA-POM-Legonizer | 5cff7bb6cdce9ff9e6aaf2723910f7f07cb3c52d | 0abc3e1ed2147ba2696be81297cd2bd99b3e72fa | refs/heads/main | 2023-05-25T09:25:32.923133 | 2021-05-31T13:07:29 | 2021-05-31T13:07:29 | 335,885,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | hpp | // Copyright University of Lyon, 2012 - 2017
// Distributed under the GNU Lesser General Public License Version 2.1 (LGPLv2)
// (Refer to accompanying file LICENSE.md or copy at
// https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html )
#ifndef __RAYTRACING_HPP__
#define __RAYTRACING_HPP__
#include "Ray.hpp"
#include "../../filters_export.h"
#include <vector>
struct TriangleList;
/**
* @build Perform raytracing algorithm on a set of triangles
* @param triangles List of triangle of a CityGML tile
* @param rays List of rays
* @param breakOnFirstInter If true, stop raytracing when an intersection is found.
* Default : false (compute all intersections between rays and triangles).
* @return list of hits
*/
std::vector<Hit*> *RayTracing(
TriangleList* triangles,
const std::vector<Ray*>& rays,
bool breakOnFirstInter = false
);
#endif
| [
"remi.lhoste@etu.univ-lyon1.fr"
] | remi.lhoste@etu.univ-lyon1.fr |
7cbf52f509813c622341bde38c4d2c50e585824b | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/BP_TreasureArtifact_box_02_a_Desc_classes.h | 468c18e02c83e27a9bea4ed13d16dfb46a9a2a6a | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_TreasureArtifact_box_02_a_Desc.BP_TreasureArtifact_box_02_a_Desc_C
// 0x0000 (FullSize[0x0130] - InheritedSize[0x0130])
class UBP_TreasureArtifact_box_02_a_Desc_C : public UBootyItemDesc
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_TreasureArtifact_box_02_a_Desc.BP_TreasureArtifact_box_02_a_Desc_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
b32a6a0f15f7a25297a6983b1fa22690282946fd | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/ext/boost/geometry/strategies/distance.hpp | 4179f8250f659f6df46dbf55836b715f74cf925f | [
"BSD-2-Clause",
"BSL-1.0",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 2,700 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_STRATEGIES_DISTANCE_HPP
#define BOOST_GEOMETRY_STRATEGIES_DISTANCE_HPP
#include <boost/mpl/assert.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/strategies/tags.hpp>
namespace boost { namespace geometry
{
namespace strategy { namespace distance { namespace services
{
template <typename Strategy> struct tag {};
template <typename Strategy, typename P1, typename P2>
struct return_type
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_STRATEGY, (types<Strategy, P1, P2>)
);
};
template <typename Strategy> struct comparable_type
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_STRATEGY, (types<Strategy>)
);
};
template <typename Strategy> struct get_comparable
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_STRATEGY, (types<Strategy>)
);
};
template <typename Strategy, typename P1, typename P2>
struct result_from_distance {};
// For point-segment only:
template <typename Strategy> struct strategy_point_point {};
// Default strategy
/*!
\brief Traits class binding a default strategy for distance
to one (or possibly two) coordinate system(s)
\ingroup distance
\tparam GeometryTag tag (point/segment) for which this strategy is the default
\tparam Point1 first point-type
\tparam Point2 second point-type
\tparam CsTag1 tag of coordinate system of first point type
\tparam CsTag2 tag of coordinate system of second point type
*/
template
<
typename GeometryTag,
typename Point1,
typename Point2 = Point1,
typename CsTag1 = typename cs_tag<Point1>::type,
typename CsTag2 = typename cs_tag<Point2>::type,
typename UnderlyingStrategy = void
>
struct default_strategy
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION
, (types<Point1, Point2, CsTag1, CsTag2>)
);
};
}}} // namespace strategy::distance::services
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_DISTANCE_HPP
| [
"hanchuan.peng@gmail.com"
] | hanchuan.peng@gmail.com |
bb97b07590c520cce091ac175cc290772288f95c | f80f0f71b9f3b6b186484446188411c263cd0728 | /9095.cpp | 5b1af2e60d1fb019217709ae459616f3ea278816 | [] | no_license | Kimuksung/algorithm | 082c160a4ae27017ad01be2554e6eb47f28fb668 | 431ddb3807a9a4d55521919a43b9f43000300dbb | refs/heads/master | 2021-06-26T01:54:04.759187 | 2021-01-08T15:23:29 | 2021-01-08T15:23:29 | 200,968,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | cpp | #include <iostream>
using namespace std;
#include <vector>
int arr[100];
int answer(int temp2) {
int answer2;
vector<int> temp;
arr[1] = 1;
arr[2] = 2;
arr[3] = 4;
for (int i = 4;i <= temp2;i++) {
arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3];
}
return arr[temp2];
}
int main() {
int n;
cin >> n;
for (int i = 0;i < n;i++) {
int temp;
cin >> temp;
cout<<answer(temp)<<endl;
}
return 0;
} | [
"kimuksung2@gmail.com"
] | kimuksung2@gmail.com |
ce6e2e30400bc213e743e4a8669c7ae13c310b37 | 8642c2865a417d402f12ff38e417874dac4ed0f5 | /export_eps.cpp | d0c81e0dfa6f511878b0a9e9983ae88e2de43492 | [] | no_license | Neplex/symmetrical-guacamole | 23fcac0b0ce407600a22fc5fd39d5117cc85832f | f5cf165f15ae3897172c78dc2e3fcdeba479cacf | refs/heads/master | 2021-05-01T01:00:27.297999 | 2016-12-02T14:33:18 | 2016-12-02T14:33:18 | 75,391,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | cpp | #include "export_eps.hpp"
#include <assert.h>
#define NDEBUG 1
using namespace std;
Export_Eps::Export_Eps(char const *const _file_name, unsigned int const _x_max,
unsigned int const _y_max, unsigned int const _res)
: x_max(_x_max), y_max(_y_max), res(_res),
output(_file_name, std::ofstream::out) {
output << "%!PS-Adobe-2.0 EPSF-2.0" << endl;
output << "%%BoundingBox: 0.0 0.0 " << ((x_max + 1) * res) << " "
<< ((y_max + 1) * res) << endl;
output << "%%Pages: 1" << endl
<< "%%EndComments" << endl
<< "%%EndProlog" << endl;
output << "/res { " << res << " } def" << endl;
output << "/p { gsave newpath moveto 0 res rlineto res 0 rlineto 0 res neg "
"rlineto closepath fill grestore } def"
<< endl;
}
Export_Eps::~Export_Eps() {
output << "%%EOF" << endl;
// file will be destroyed and thus the stream closed
}
void Export_Eps::plot(unsigned int const x, unsigned int const y) {
output << (res * x) << " " << (res * y) << " p" << endl;
}
void Export_Eps::plot(Shape const *const sh) {
assert(NULL != sh);
for (unsigned int i = 0; i <= x_max; i++) {
for (unsigned int j = 0; j <= y_max; j++) {
if (sh->contains(i, j)) {
plot(i, j);
}
}
}
}
| [
"nicolas.hiot@etu.univ-orleans.fr"
] | nicolas.hiot@etu.univ-orleans.fr |
751c7110ac408eca54ac84908ce8f50cb6d4aee6 | c0a96ec9a2266951872a56fb1b48c9af34ddcefc | /opencv-3.1.0/build/modules/imgproc/opencv_test_imgproc_pch_dephelp.cxx | 0ae69b231bbe06ff59c453f71aecd3ecdfbb6364 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | permissive | fagan2888/LPReader | 15692a6811ef0a9b395eea33db91e25b3a7c5cef | 6841c3f5ef29ecbebfff1b20bcd43809d113f39e | refs/heads/master | 2021-05-31T04:42:23.192340 | 2016-03-28T03:49:06 | 2016-03-28T03:49:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 142 | cxx | #include "/home/gloria/Downloads/opencv-3.1.0/modules/imgproc/test/test_precomp.hpp"
int testfunction();
int testfunction()
{
return 0;
}
| [
"gloria.leung@rutgers.edu"
] | gloria.leung@rutgers.edu |
ec24abebb2d45c2f25836511e77fd4719b935ee0 | 0570750c6d8e28d837f9e4f7dc825c968c874fb4 | /build/Android/Preview1/app/src/main/include/Fuse.Scripting.BoolChangedArgs.h | 136b4ebc552807b85fde92cca44fa5b97e53de6b | [] | no_license | theaustinthompson/maryjane | b3671d950aad58fd2ed490bda8aa1113aedf5a97 | b4ddf76aa2a2caae77765435d0315cf9111d6626 | refs/heads/master | 2021-04-12T08:37:47.311922 | 2018-03-27T23:06:47 | 2018-03-27T23:06:47 | 126,034,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | h | // This file was generated based on C:/Users/borde_000/AppData/Local/Fusetools/Packages/Fuse.Scripting/1.8.1/IScriptEvent.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Scripting.IScriptEvent.h>
#include <Uno.Bool.h>
#include <Uno.UX.ValueChangedArgs-1.h>
namespace g{namespace Fuse{namespace Scripting{struct BoolChangedArgs;}}}
namespace g{
namespace Fuse{
namespace Scripting{
// public sealed class BoolChangedArgs :64
// {
struct BoolChangedArgs_type : uType
{
::g::Fuse::Scripting::IScriptEvent interface0;
};
BoolChangedArgs_type* BoolChangedArgs_typeof();
void BoolChangedArgs__ctor_2_fn(BoolChangedArgs* __this, bool* value);
void BoolChangedArgs__FuseScriptingIScriptEventSerialize_fn(BoolChangedArgs* __this, uObject* s);
void BoolChangedArgs__New3_fn(bool* value, BoolChangedArgs** __retval);
struct BoolChangedArgs : ::g::Uno::UX::ValueChangedArgs
{
void ctor_2(bool value);
static BoolChangedArgs* New3(bool value);
};
// }
}}} // ::g::Fuse::Scripting
| [
"austin@believeinthompson.com"
] | austin@believeinthompson.com |
c3467dfc074f00fdbb8d5a161aea39bf645d01b7 | bac9ca4fd8774eb2447297424b6bc9a5bf13a801 | /number-of-closed-islands/number-of-closed-islands.cpp | e169068f919c585220cfafbd88de79c877fcd031 | [] | no_license | devansh2021/My_LC_Sol | 28b10349cd6e77e5da5bfad8a35038844c540dd6 | bd8d22fa3de110057e99b75194f5d60ed1874ba2 | refs/heads/main | 2023-06-21T21:49:36.092740 | 2021-07-14T11:27:02 | 2021-07-14T11:27:02 | 347,848,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | class Solution {
public:
bool terminal=0;
void dfs(vector<vector<int>> &g, int r, int c)
{
int dr[4]={1,0,0,-1};
int dc[4]={0,1,-1,0};
int m=g.size();
int n=g[0].size();
if(r<0 ||c<0 ||c>=n||r>=m)
{
terminal=true;
return;
}
if(g[r][c])
return ;
else
g[r][c]=1;
for(int i=0;i<4;i++)
{
dfs(g,r+dr[i],c+dc[i]);
}
return;
}
int closedIsland(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
int ans=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(!grid[i][j]){
terminal=0;
dfs(grid, i, j);
if(!terminal)
ans++;
}
}
}
return ans;
}
}; | [
"devanshsuwalka@gmail.com"
] | devanshsuwalka@gmail.com |
4160b9fb7dd0b97ef0fcc0e285234ef767ae28ad | 9becd9b6722f4c0273625cc5803ac3f820cb9a3d | /Heavy Light Bruteforce/KALTSUM - k Alternating Sum.cpp | 4f9e4a28051bb0acc54a4824f80b6127d93e9e65 | [] | no_license | debsourav33/Category-Wise-Oonline-Judge-Solutions | b16566d3c2a0506f7c0c9f90956d0a7d1e61aa38 | c69a1d35dd43c9265f7f804064b51f1ec16764be | refs/heads/master | 2021-07-14T16:56:33.084844 | 2020-11-08T18:26:57 | 2020-11-08T18:26:57 | 219,268,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | #include<bits/stdc++.h>
using namespace std;
//{
#define si(a) scanf("%d",&a)
#define sii(a,b) scanf("%d %d",&a,&b);
#define siii(a,b,c) scanf("%d %d %d",&a,&b,&c);
#define sl(a) scanf("%lld",&a)
#define sll(a,b) scanf("%lld %lld",&a,&b);
#define slll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c);
#define outi(a) printf("%d\n",a)
#define outii(a,b) printf("%d %d\n",a,b)
#define outis(a) printf(" %d",a)
#define outl(a) printf("%lld\n",a)
#define outll(a,b) printf("%lld %lld\n",a,b)
#define outls(a) printf(" %lld",a)
#define cel(n,k) ((n-1)/k+1)
#define sets(a) memset(a, -1, sizeof(a))
#define clr(a) memset(a, 0, sizeof(a))
#define fr(n) for(int i=0;i<n;i++)
#define fr1(n) for(int i=1;i<=n;i++)
#define frj(n) for(int j=0;j<n;j++)
#define frj1(n) for(int j=1;j<=n;j++)
#define pb push_back
#define all(v) v.begin(),v.end()
#define mp make_pair
#define ff first
#define ss second
#define INF 10000007
#define fastIO() ios_base::sync_with_stdio(false); cin.tie(NULL);
typedef long long i64;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
//}
const int N= 1e5+5;
i64 n, q, a[N], presum[N][320], pre[N], sqroot;
void preprocess(){
fr1(sqroot)
{
frj1(i)
{
i64 sum= 0, turn=1;
for(int l=j; l<=n;l+=i)
{
int r= l+i-1;
if(r>n) break;
sum+= (pre[r]-pre[l-1]) * turn;
presum[r][i]= sum;
turn*=-1;
}
}
}
}
void query1(int l, int r, int k){
i64 ans= presum[r][k]- presum[l-1][k];
int odd= (l-1)/k;
if(odd%2) ans*=-1;
outl(ans);
}
void query2(int l, int r, int k){
i64 ans= 0, turn= 1;
int st= l+k-1;
for(int i=st; i<=r;i+=k){
ans+= (pre[i]- pre[i-k]) * turn;
turn*= -1;
}
outl(ans);
}
main(){
sll(n,q);
fr1(n){
sl(a[i]);
pre[i]= pre[i-1]+a[i];
}
sqroot= (i64) sqrt(n);
preprocess();
int l, r, k;
while(q--){
siii(l,r,k);
if(k>=sqroot) query2(l,r,k);
else query1(l,r,k);
}
}
| [
"debsourav33@gmail.com"
] | debsourav33@gmail.com |
0cf50ffd84b8ab6a560332413e1f3978b2849e5a | 3b1d08997d0dc9c444f2bdaaab55a8606c60d332 | /IOCMain/CMXWrap/RTC.h | 8eaf67606d737f41795edd461c346266bac36f1d | [] | no_license | zjsaisi/sm2000 | 8303ece373516c871694d382bb3daef9f5129d1a | 0fa74cdb7566621162e1845dd4558723182a49ac | refs/heads/master | 2020-04-16T09:22:12.797424 | 2019-01-23T10:31:07 | 2019-01-23T10:31:07 | 165,461,667 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,310 | h | // RTC.h: interface for the CRTC class.
//
//////////////////////////////////////////////////////////////////////
/*
* $Header: RTC.h 1.2 2009/04/29 18:52:02PDT Zheng Miao (zmiao) Exp $
* $Revision: 1.2 $
*/
#if !defined(AFX_RTC_H__F598CDC0_6174_42DB_A593_48450BF914F3__INCLUDED_)
#define AFX_RTC_H__F598CDC0_6174_42DB_A593_48450BF914F3__INCLUDED_
#include "DataType.h"
#ifdef __cplusplus
class CRTC
{
public:
uint32 GetMjd(void);
void SetGpsLocal(int32 seconds);
void SetComputerSeconds(uint32 seconds);
unsigned long GetComputerSeconds(void);
uint32 GetAbsoluteSecond(void);
void SetGPSSeconds(uint32 seconds);
int SetDateTime(int year, int month, int day, int hour, int minute, int second);
void GetDateTime(int *year, int *month, int *day, int *hour, int *minute, int *second);
unsigned long GetGPSSeconds(void);
void SetTime(uint32 seconds);
void TickOfOneSecond(void);
CRTC();
virtual ~CRTC();
static int DaysOfMonth(int year, int month);
private:
static int IsLeapYear(int year);
int DaysOfYear(int year);
volatile uint32 m_seconds_1970; // seconds since 1/1/1970
uint32 volatile m_absoluteSecond;
};
extern CRTC *g_pRTC;
#endif
EXTERN void RTOS_TICK(void);
EXTERN uint32 GetRawTick(void);
#endif // !defined(AFX_RTC_H__F598CDC0_6174_42DB_A593_48450BF914F3__INCLUDED_)
| [
"you@example.com"
] | you@example.com |
ea122a20d7ec4109638a0637e230b04b5fe9e4b6 | e464f1343cfe35bac84abf63f7ce08bff041c24c | /src/base/VulkanCommandBuffer.cpp | 06fc431720ba71e6936336cdd8752bea50cd69e6 | [] | no_license | brioche1703/VulkanLearning | 08b8202d8bc1caee456a24c99a33fc4663674621 | 9b1ef41ddf439d8a2ba96bb6600d63b787ffeeed | refs/heads/master | 2023-05-18T04:26:57.957553 | 2021-06-11T12:48:18 | 2021-06-11T12:48:18 | 275,235,534 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | cpp | #include "VulkanCommandBuffer.hpp"
#include <vulkan/vulkan_core.h>
namespace VulkanLearning {
VulkanCommandBuffer::VulkanCommandBuffer() {}
VulkanCommandBuffer::~VulkanCommandBuffer() {}
void VulkanCommandBuffer::create(VulkanDevice* device, VkCommandBufferLevel level, bool begin) {
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = level;
allocInfo.commandPool = device->getCommandPool();
allocInfo.commandBufferCount = 1;
vkAllocateCommandBuffers(device->getLogicalDevice(), &allocInfo, &m_commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(m_commandBuffer, &beginInfo);
}
void VulkanCommandBuffer::flushCommandBuffer(VulkanDevice* device, bool free) {
if (m_commandBuffer == VK_NULL_HANDLE) {
return;
}
if (vkEndCommandBuffer(m_commandBuffer) != VK_SUCCESS) {
throw std::runtime_error("Command buffer end failed!");
}
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_commandBuffer;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
VkFence fence;
if (vkCreateFence(device->getLogicalDevice(), &fenceInfo, nullptr, &fence) != VK_SUCCESS) {
throw std::runtime_error("Fence creation failed!");
}
if (vkQueueSubmit(device->getGraphicsQueue(), 1, &submitInfo, fence) != VK_SUCCESS) {
throw std::runtime_error("Fence submition to queue failed!");
}
if (vkWaitForFences(device->getLogicalDevice(), 1, &fence, VK_TRUE, UINT64_MAX) != VK_SUCCESS) {
throw std::runtime_error("Waiting for fence failed!");
}
vkDestroyFence(device->getLogicalDevice(), fence, nullptr);
if (free)
{
vkFreeCommandBuffers(device->getLogicalDevice(), device->getCommandPool(), 1, &m_commandBuffer);
}
}
void VulkanCommandBuffer::flushCommandBuffer(VulkanDevice* device, VkQueue queue, bool free) {
if (m_commandBuffer == VK_NULL_HANDLE) {
return;
}
if (vkEndCommandBuffer(m_commandBuffer) != VK_SUCCESS) {
throw std::runtime_error("Command buffer end failed!");
}
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_commandBuffer;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
VkFence fence;
if (vkCreateFence(device->getLogicalDevice(), &fenceInfo, nullptr, &fence) != VK_SUCCESS) {
throw std::runtime_error("Fence creation failed!");
}
if (vkQueueSubmit(queue, 1, &submitInfo, fence) != VK_SUCCESS) {
throw std::runtime_error("Fence submition to queue failed!");
}
if (vkWaitForFences(device->getLogicalDevice(), 1, &fence, VK_TRUE, UINT64_MAX) != VK_SUCCESS) {
throw std::runtime_error("Waiting for fence failed!");
}
vkDestroyFence(device->getLogicalDevice(), fence, nullptr);
if (free)
{
vkFreeCommandBuffers(device->getLogicalDevice(), device->getCommandPool(), 1, &m_commandBuffer);
}
}
}
| [
"kevin.meniel@gmail.com"
] | kevin.meniel@gmail.com |
3b97087b4460988e52c950f2590c4f3e1272e3c1 | 62c4079409e7fc6bfa18fb4667d0e288f240d8d8 | /obj_detect/include/detectors/ClassifierConfig.h | 753d6104c2b20d7226a244c714e14769e4814040 | [] | no_license | RoboticsLabURJC/2017-tfm-jorge_vela | e91e5fd6e4a9406cdff8cfde99c2d9687abe873f | b72283723d3549d05d5a438dfda4afc84931c8fc | refs/heads/master | 2021-03-19T14:41:07.285716 | 2021-02-22T11:30:19 | 2021-02-22T11:30:19 | 111,129,118 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,210 | h | /** ------------------------------------------------------------------------
*
* @brief DetectionRectangle.
* @author Jorge Vela
* @author Jose M. Buenaposada (josemiguel.buenaposada@urjc.es)
* @date 2020/09/29
*
* ------------------------------------------------------------------------ */
#ifndef CLASSIFIER_CONFIG_HPP
#define CLASSIFIER_CONFIG_HPP
#include <opencv2/opencv.hpp>
struct channelsLUV{
int smooth_kernel_size;
int smooth;
};
struct gradientMag{
int normRad;
float normConst;
};
struct gradientHist{
int binSize;
int nOrients;
int softBin;
int full;
};
/** ------------------------------------------------------------------------
*
* @brief Struct whit the classifier values to extract data LUV, MAG, HIST.
*
* ------------------------------------------------------------------------ */
struct ClassifierConfig
{
cv::Size padding;
int nOctUp;
int nPerOct;
int nApprox;
int shrink;
//int stride;
channelsLUV luv;
gradientMag gradMag;
gradientHist gradHist;
std::vector<float> lambdas;
cv::Size minDs;
cv::Size modelDsPad;
cv::Size modelDs;
float cascThr;
int stride;
};
#endif // DETECTION_HPP
| [
"velajorge.93@gmail.com"
] | velajorge.93@gmail.com |
d328d24824a78131daf085dd55fe664e2612a69e | 0b3bd3ceaed3ecc7bebe89a84fd134ce00b3d600 | /dvdwaala/dvdwaala/dvdwaala.cpp | 2e841346ffa3e7633fd0b0eb901e172f5e467bc6 | [] | no_license | ashar-sarwar/Object-oriented-programming-uni-work | 5eb668f4131bba4a38ba0a8ebbc5a7d3928859b3 | 4bea74409db8dddeb6ffa7623e66a172f3242a7a | refs/heads/master | 2020-03-11T03:45:41.142241 | 2018-06-01T11:00:09 | 2018-06-01T11:00:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | // dvdwaala.cpp : Defines the entry point for the console application.
#include <stdafx.h>
#include <iostream>
#include <string>
using namespace std;
//#include "dvd.h"
#include "DVDCollection.h"
int main()
{
DvdCollection mycollection;
Dvd d1;
Dvd d2("Windows10","Microsoft",150);
Dvd d3("Windows8","Microsoft",120);
Dvd d4("Mac11","Apple",150);
Dvd d5("GTA 5","Rockstar",150);
Dvd d6("CS","Ubisoft",150);
mycollection.add_Dvd(d1);
mycollection.add_Dvd(d2);
mycollection.add_Dvd(d3);
mycollection.add_Dvd(d4);
mycollection.add_Dvd(d5);
//mycollection.add_Dvd(d6);
// mycollection.show();
system("pause");
} | [
"“asharsarwar186@gmail.com”"
] | “asharsarwar186@gmail.com” |
ac5731dedfd0ed70a0d7632dfa29e2e98f35949e | 6cd33a276282fef63940f49dabc6fdcffc00623a | /include/nana/gui/widgets/treebox.hpp | 2616cc1eed36e6f2a521a79cb6c98395a40ef895 | [
"BSL-1.0"
] | permissive | qPCR4vir/nana.cygwin | a32ea24d7d6cee4f2545724d488c975b11ce76c2 | 3e289bf4ff7861953e912a8f058e21b665be7f4a | refs/heads/master | 2021-05-01T20:06:46.648597 | 2015-03-28T20:00:13 | 2015-03-28T20:00:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,828 | hpp | /*
* A Tree Box Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/gui/widgets/treebox.hpp
* @brief:
* The treebox organizes the nodes by a key string.
* The treebox would have a vertical scrollbar if the node
* is too many to display. And it does not have a horizontal scrollbar,
* the widget will adjust the node's displaying position for fitting.
*/
#ifndef NANA_GUI_WIDGETS_TREEBOX_HPP
#define NANA_GUI_WIDGETS_TREEBOX_HPP
#include "widget.hpp"
#include "scroll.hpp"
#include <nana/paint/gadget.hpp>
#include "detail/tree_cont.hpp"
#include <nana/gui/timer.hpp>
#include <nana/any.hpp>
namespace nana
{
namespace gui
{
namespace drawerbase
{
namespace treebox
{
class tooltip_window;
template<typename NodeType>
struct extra_events
{
typedef NodeType node_type;
nana::fn_group<void(nana::gui::window, node_type, bool)> expand;
nana::fn_group<void(nana::gui::window, node_type, bool)> selected;
};
struct node_image_tag
{
nana::paint::image normal;
nana::paint::image highlighted;
nana::paint::image expanded;
};
class trigger
:public drawer_trigger
{
public:
struct treebox_node_type
{
treebox_node_type();
treebox_node_type(const nana::any&);
treebox_node_type(const nana::string& text, const nana::any&);
treebox_node_type& operator=(const treebox_node_type&);
nana::string text;
nana::any value;
bool expanded;
nana::string img_idstr;
};
struct pseudo_node_type{};
typedef nana::gui::widgets::detail::tree_cont<treebox_node_type> tree_cont_type;
typedef tree_cont_type::node_type node_type;
typedef extra_events<pseudo_node_type*> ext_event_type;
trigger();
void auto_draw(bool);
bool check(const node_type*) const;
nana::any & value(node_type*) const;
node_type* find(const nana::string& key_path);
node_type* get_owner(const node_type*) const;
node_type* get_root() const;
node_type* insert(node_type* node, const nana::string& key, const nana::string& title, const nana::any& v);
node_type* insert(const nana::string& path, const nana::string& title, const nana::any& v);
bool check(node_type* parent, node_type* child) const;
void remove(node_type*);
node_type * selected() const;
void selected(node_type*);
void set_expand(node_type* node, bool);
void set_expand(const nana::string& path, bool);
unsigned visual_item_size() const;
void image(const nana::string& id, const node_image_tag&);
node_image_tag& image(const nana::string&) const;
void image_erase(const nana::string&);
void node_image(node_type* node, const nana::string& id);
unsigned long node_width(const node_type *node) const;
bool rename(node_type *node, const nana::char_t* key, const nana::char_t* name);
ext_event_type& ext_event() const;
private:
void bind_window(widget_reference);
void attached(graph_reference);
void detached();
void refresh(graph_reference);
void dbl_click(graph_reference, const eventinfo&);
void mouse_down(graph_reference, const eventinfo&);
void mouse_up(graph_reference, const eventinfo&);
void mouse_move(graph_reference, const eventinfo&);
void mouse_wheel(graph_reference, const eventinfo&);
void resize(graph_reference, const eventinfo&);
void key_down(graph_reference, const eventinfo&);
void key_char(graph_reference, const eventinfo&);
private:
void _m_find_first(unsigned long offset);
unsigned _m_node_height() const;
unsigned _m_max_allow() const;
private:
const node_type* _m_find_track_node(nana::char_t);
nana::paint::image* _m_image(const node_type*);
bool _m_track_mouse(int x, int y);
void _m_tooltip_window(node_type* node, const nana::point& pos, const nana::size& size);
void _m_close_tooltip_window();
void _m_mouse_move_tooltip_window();
void _m_click_tooltip_window(const eventinfo&);
bool _m_draw(bool scrollbar_react);
void _m_draw_tree();
unsigned _m_visible_width() const;
void _m_show_scrollbar();
void _m_event_scrollbar(const eventinfo&);
bool _m_adjust(node_type * node, int reason);
bool _m_set_selected(node_type * node);
bool _m_set_expanded(node_type* node, bool value);
void _m_deal_adjust();
private:
//Functor
class item_renderer
{
public:
typedef tree_cont_type::node_type node_type;
item_renderer(trigger&, const nana::point&);
//affect
//0 = Sibling, the last is a sibling of node
//1 = Owner, the last is the owner of node
//>=2 = Children, the last is a child of a node that before this node.
int operator()(const node_type& node, int affect);
unsigned width(const node_type &node) const;
private:
void _m_draw_arrow(const node_type& node, unsigned item_height, bool expand);
void _m_background(const node_type& node, bool has_child, bool expand);
private:
trigger& drawer_;
nana::point pos_;
};
class item_locator
{
public:
struct object
{ enum{none, item, arrow};};
item_locator(trigger& drawer, int item_pos, int x, int y);
int operator()(tree_cont_type::node_type &node, int affect);
tree_cont_type::node_type * node() const;
unsigned what() const;
nana::point pos() const;
nana::size size() const;
private:
trigger& drawer_;
int item_pos_;
int item_ypos_;
nana::point pos_;
unsigned object_;
tree_cont_type::node_type * node_;
};
struct pred_allow_child
{
bool operator()(const tree_cont_type::node_type& node);
};
private:
nana::paint::graphics *graph_;
widget *widget_;
struct drawing_flags
{
drawing_flags();
bool pause; //It is a drawing flag, if it is true, the draw function dose nothing.
}dwflags_;
struct shape_data_type
{
shape_data_type();
nana::upoint border;
nana::gui::scroll<true> scrollbar;
unsigned long prev_first_value; //
mutable std::map<nana::string, node_image_tag> image_table;
}shape_;
struct attribute_type
{
attribute_type();
bool auto_draw;
mutable ext_event_type ext_event;
std::size_t mutable visual_item_size;
uint32_t button_width;
tree_cont_type tree_cont;
}attr_;
struct node_desc_type
{
node_desc_type();
tree_cont_type::node_type * first;
unsigned indent_size;
int offset_x;
int item_offset; //the offset of item to the start pos
int text_offset; //the offset of text to the item
unsigned long image_width;
}node_desc_;
struct node_state
{
node_state();
tooltip_window *tooltip;
tree_cont_type::node_type * highlight;
unsigned highlight_object;
tree_cont_type::node_type * selected;
tree_cont_type::node_type * event_node;
}node_state_;
struct track_node_tag
{
track_node_tag();
nana::string key_buf;
unsigned long key_time;
}track_node_;
struct adjust_desc_type
{
adjust_desc_type();
int offset_x_adjust; //It is a new value of offset_x, and offset_x will be adjusted to the new value.
tree_cont_type::node_type * node;
unsigned long scroll_timestamp;
nana::gui::timer timer;
}adjust_;
}; //end class trigger
}//end namespace treebox
}//end namespace drawerbase
template<typename UserData>
class treebox
:public widget_object<category::widget_tag, drawerbase::treebox::trigger>
{
public:
typedef UserData value_type;
typedef typename drawer_trigger_t::pseudo_node_type* node_type;
typedef typename drawer_trigger_t::ext_event_type ext_event_type;
typedef drawerbase::treebox::node_image_tag node_image_type;
treebox(){}
treebox(window wd, bool visible)
{
create(wd, rectangle(), visible);
}
treebox(window wd, const rectangle& r, bool visible)
{
create(wd, r, visible);
}
void auto_draw(bool ad)
{
get_drawer_trigger().auto_draw(ad);
}
ext_event_type& ext_event() const
{
return get_drawer_trigger().ext_event();
}
value_type& value(node_type node) const
{
return get_drawer_trigger().value(reinterpret_cast<drawer_trigger_t::node_type*>(node));
}
treebox& image(const nana::string& id, const nana::paint::image& img)
{
node_image_type node_img;
node_img.normal = img;
get_drawer_trigger().image(id, node_img);
return *this;
}
treebox& image(const nana::string& id, const node_image_type& node_img)
{
get_drawer_trigger().image(id, node_img);
return *this;
}
node_image_type& image(const nana::string& id) const
{
return get_drawer_trigger().image(id);
}
void image_erase(const nana::string& id)
{
get_drawer_trigger().image_erase(id);
}
void node_image(node_type node, const nana::string& id)
{
get_drawer_trigger().node_image(reinterpret_cast<drawer_trigger_t::node_type*>(node), id);
}
node_type insert(const nana::string& path_key, const nana::string& title, value_type value)
{
return reinterpret_cast<node_type>(get_drawer_trigger().insert(path_key, title, value));
}
node_type insert(node_type node, const nana::string& key, const nana::string& title, value_type value)
{
return reinterpret_cast<node_type>(get_drawer_trigger().insert(reinterpret_cast<drawer_trigger_t::node_type*>(node), key, title, value));
}
void remove(node_type node)
{
get_drawer_trigger().remove(reinterpret_cast<drawer_trigger_t::node_type*>(node));
}
void remove(const nana::string& key_path)
{
get_drawer_trigger().remove(
get_drawer_trigger().find(key_path)
);
}
void expand(node_type node, bool exp)
{
get_drawer_trigger().set_expand(reinterpret_cast<drawer_trigger_t::node_type*>(node), exp);
}
void expand(const nana::string& path_key, bool exp)
{
get_drawer_trigger().set_expand(path_key, exp);
}
bool expend(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
return reinterpret_cast<drawer_trigger_t::node_type*>(node)->value.second.expanded;
return false;
}
node_type node(const nana::string& keypath)
{
return reinterpret_cast<node_type>(get_drawer_trigger().find(keypath));
}
nana::string key(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
return reinterpret_cast<drawer_trigger_t::node_type*>(node)->value.first;
return nana::string();
}
bool key(node_type node, const nana::string& key)
{
return (get_drawer_trigger().rename(reinterpret_cast<drawer_trigger_t::node_type*>(node), key.c_str(), 0));
}
bool text(node_type node, const nana::string& str)
{
return (get_drawer_trigger().rename(reinterpret_cast<drawer_trigger_t::node_type*>(node), 0, str.c_str()));
}
nana::string text(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
return reinterpret_cast<drawer_trigger_t::node_type*>(node)->value.second.text;
return nana::string();
}
node_type selected() const
{
return reinterpret_cast<node_type>(get_drawer_trigger().selected());
}
void selected(node_type node)
{
get_drawer_trigger().selected(reinterpret_cast<drawer_trigger_t::node_type*>(node));
}
unsigned children_size(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
{
drawer_trigger_t::node_type* child = reinterpret_cast<drawer_trigger_t::node_type*>(node)->child;
unsigned n = 0;
for(; child; child = child->next)
++n;
return n;
}
return 0;
}
node_type get_sibling(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
return reinterpret_cast<node_type>(
reinterpret_cast<drawer_trigger_t::node_type*>(node)->next
);
return 0;
}
node_type get_child(node_type node) const
{
if(get_drawer_trigger().check(reinterpret_cast<drawer_trigger_t::node_type*>(node)))
return reinterpret_cast<node_type>(
reinterpret_cast<drawer_trigger_t::node_type*>(node)->child
);
return 0;
}
node_type get_owner(node_type node) const
{
return reinterpret_cast<node_type>(
get_drawer_trigger().get_owner(reinterpret_cast<drawer_trigger_t::node_type*>(node))
);
}
nana::string make_key_path(node_type node, const nana::string& splitter) const
{
const typename drawer_trigger_t::node_type *pnode = reinterpret_cast<drawer_trigger_t::node_type*>(node);
if(get_drawer_trigger().check(pnode))
{
const typename drawer_trigger_t::node_type* root = get_drawer_trigger().get_root();
nana::string path;
nana::string temp;
while(pnode->owner != root)
{
temp = splitter;
temp += pnode->value.first;
path.insert(0, temp);
pnode = pnode->owner;
}
path.insert(0, pnode->value.first);
return path;
}
return STR("");
}
};
}//end namespace gui
}//end namespace nana
#endif
| [
"lzbgt@126.com"
] | lzbgt@126.com |
f19eb7be4ca8a27b2915157598f842a4ec83e476 | 43523509ac3324883943b52c7d3e0e92cc46ef70 | /renderer/platform/plugins/plugin_list_builder.cc | 26d6f01a055cd7fef0969ea2627f9c52d5b2c71b | [] | no_license | JDenghui/blink | d935ab9a906c9f95c890549b254b4dec80d93765 | 6732fc88d110451aebda75b8822ba5d9b4f9de04 | refs/heads/master | 2020-03-23T15:55:33.238563 | 2018-07-21T05:26:31 | 2018-07-21T05:26:31 | 141,783,126 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | cc | /*
* Copyright (C) 2009 Google 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 Google 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.
*/
#include "third_party/blink/renderer/platform/plugins/plugin_list_builder.h"
#include "third_party/blink/public/platform/web_string.h"
namespace blink {
void PluginListBuilder::AddPlugin(const WebString& name,
const WebString& description,
const WebString& file_name,
WebColor background_color) {
if (results_) {
results_->push_back(
new PluginInfo(name, file_name, description, background_color));
}
}
void PluginListBuilder::AddMediaTypeToLastPlugin(const WebString& name,
const WebString& description) {
if (results_) {
MimeClassInfo* info =
new MimeClassInfo(name, description, *results_->back());
results_->back()->AddMimeType(info);
}
}
void PluginListBuilder::AddFileExtensionToLastMediaType(
const WebString& extension) {
if (results_) {
MimeClassInfo& info = *results_->back()->mimes_.back();
info.extensions_.push_back(extension);
}
}
} // namespace blink
| [
"Denghui_Jia@Dell.com"
] | Denghui_Jia@Dell.com |
f108229355fce2f9c5fa25ed7d378679087111c0 | ba4c240c04e9cdca87b50114845bbf4f51fe9f4c | /Packages/Packages.cc | 9d9c499a8ce6b01b8ba0e7dca69f6d7af0c36ae8 | [] | no_license | dparnell/newton-framework | a04044c41ae0eeee2e21e6816960cc27a9d50c74 | 8955e8d138b4755c0ac9024829b31a1538dd54f8 | refs/heads/master | 2021-01-22T20:54:42.855698 | 2017-03-14T13:33:43 | 2017-03-14T13:33:43 | 85,375,138 | 0 | 0 | null | 2017-03-18T04:16:43 | 2017-03-18T04:16:42 | null | UTF-8 | C++ | false | false | 7,841 | cc | /*
File: Packages.cc
Contains: Package loaders etc.
Written by: Newton Research Group.
*/
#include "Objects.h"
#include "ROMResources.h"
#include "PackageTypes.h"
#include "PackageParts.h"
#include "LargeBinaries.h"
#include "NewtonScript.h"
#include "MemoryPipe.h"
#include "EndpointPipe.h"
#include "EndpointClient.h"
/* -----------------------------------------------------------------------------
D a t a
----------------------------------------------------------------------------- */
const char * const kPackageMagicNumber = "package01";
extern "C" {
Ref FObjectPkgRef(RefArg inRcvr, RefArg inPkg);
Ref FGetPkgRefInfo(RefArg inRcvr, RefArg inPkg);
Ref FIsValid(RefArg inRcvr, RefArg inPkg);
}
Ref
FObjectPkgRef(RefArg inRcvr, RefArg inPkg)
{ return NILREF; }
Ref
FGetPkgRefInfo(RefArg inRcvr, RefArg inPkg)
{ return NILREF; }
Ref
FIsValid(RefArg inRcvr, RefArg inPkg)
{ return NILREF; }
/* -----------------------------------------------------------------------------
Determine whether block of data is a package header.
Args: inData pointer to data
inSize size of data
Return: true => is a package header
----------------------------------------------------------------------------- */
bool
IsPackageHeader(Ptr inData, size_t inSize)
{
bool isOK = false;
if (inSize >= sizeof(PackageDirectory))
{
PackageDirectory * directory = (PackageDirectory *)inData;
newton_try
{
ArrayIndex i;
for (i = 0, isOK = true; i < kPackageMagicLen && isOK; ++i)
{
if (directory->signature[i] != kPackageMagicNumber[i])
isOK = false;
}
if (isOK)
{
for (isOK = false; i < kPackageMagicLen+kPackageMagicVersionCount && !isOK; ++i)
{
if (directory->signature[kPackageMagicLen] == kPackageMagicNumber[i])
isOK = true;
}
}
}
newton_catch(exBusError)
isOK = false;
newton_catch(exPermissionViolation)
isOK = false;
end_try;
}
return isOK;
}
#pragma mark -
/* -------------------------------------------------------------------------------
Allocate a package on a store, providing feedback.
Args: inPipe the piped package
inStore the store on which to store the package
inCallback a callback frame for providing progress feedback
inFreq number of bytes after which we should callback
inActivate activate package after storing it?
Return: a package frame
------------------------------------------------------------------------------- */
Ref
AllocatePackage(CPipe * inPipe, RefArg inStore, RefArg inCallback, size_t inFreq, bool inActivate)
{
NewtonErr err;
CLOCallback callback;
callback.setFunc(inCallback);
callback.setChunk(inFreq);
callback.setInfo(RA(NILREF));
PSSId id;
RefVar storeObject = NOTNIL(inStore) ? (Ref)inStore : NSCallGlobalFn(SYMA(GetDefaultStore));
CStoreWrapper * storeWrapper = (CStoreWrapper *)GetFrameSlot(storeObject, SYMA(store));
GC();
if ((err = StorePackage(inPipe, storeWrapper->store(), &callback, &id)) != noErr)
ThrowErr(exFrames, err);
return NSCallGlobalFn(SYMA(RegisterNewPackage), WrapPackage(storeWrapper->store(), id), storeObject, MAKEBOOLEAN(inActivate));
}
/* -------------------------------------------------------------------------------
Allocate a package.
Args: inPipe the piped package
inStore the store on which to store the package
inParms installation parameter frame
Return: a package frame
------------------------------------------------------------------------------- */
Ref
AllocatePackage(CPipe * inPipe, RefArg inStore, RefArg inParms)
{
RefVar cbFrame;
Ref cbFreq;
size_t freq = 4*KByte;
bool doActivate = true;
if (NOTNIL(inParms))
{
// create AllocatePackage args from parms frame
cbFrame = GetFrameSlot(inParms, SYMA(callback));
doActivate = ISNIL(GetFrameSlot(inParms, SYMA(don_27tActivate)));
cbFreq = GetFrameSlot(inParms, SYMA(callbackFreq));
if (NOTNIL(cbFreq))
freq = RINT(cbFreq);
}
return AllocatePackage(inPipe, inStore, cbFrame, freq, doActivate);
}
/* -------------------------------------------------------------------------------
Create a new package.
NTK calls in here to download a package.
Args: inPipe the piped package
inStore the store on which to store the package
inCallback a callback frame for providing progress feedback
inFreq number of bytes after which we should callback
Return: a package frame
------------------------------------------------------------------------------- */
NewtonErr
NewPackage(CPipe * inPipe, RefArg inStore, RefArg inCallback, size_t inFreq)
{
NewtonErr err = noErr;
RefVar pkg;
newton_try
{
pkg = AllocatePackage(inPipe, inStore, inCallback, inFreq, true);
}
newton_catch_all
{
err = (NewtonErr)(long)CurrentException()->data;;
}
end_try;
return err;
}
/* -------------------------------------------------------------------------------
Suck a package through a pipe, providing feedback.
Args: inPipe the piped package
inStore the store on which to store the package
inCallback a callback frame for providing progress feedback
inFreq number of bytes after which we should callback
inActivate activate package after storing it?
Return: a package frame
------------------------------------------------------------------------------- */
Ref
SuckPackageThruPipe(CPipe * inPipe, RefArg inStore, RefArg inCallback, size_t inFreq, bool inActivate)
{
return AllocatePackage(inPipe, inStore, inCallback, inFreq, inActivate);
}
/* -------------------------------------------------------------------------------
Suck a package through a pipe.
Args: inPipe the piped package
inStore the store on which to store the package
inParms installation parameters
Return: a package frame
------------------------------------------------------------------------------- */
Ref
SuckPackageThruPipe(CPipe * inPipe, RefArg inStore, RefArg inParms)
{
return AllocatePackage(inPipe, inStore, inParms);
}
#pragma mark -
/* -----------------------------------------------------------------------------
P l a i n C I n t e r f a c e
----------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------
Suck a package from a binary object.
We do this by creating a memory pipe so we can SuckPackageThruPipe()
Args: inRcvr a store frame
inBinary the binary object containing the package
inParms params frame
Return: a package frame
------------------------------------------------------------------------------- */
Ref
StoreSuckPackageFromBinary(RefArg inRcvr, RefArg inBinary, RefArg inParms)
{
RefVar pkg;
#if !defined(forFramework)
size_t binSize = Length(inBinary);
CDataPtr binData(inBinary);
CBufferSegment * buf = CBufferSegment::make();
buf->init((char *)binData, binSize);
CMemoryPipe pipe;
pipe.init(buf, NULL, false);
pkg = SuckPackageThruPipe(&pipe, inRcvr, inParms);
buf->destroy();
#endif
return pkg;
}
/* -------------------------------------------------------------------------------
Suck a package from an endpoint.
Args: inRcvr a store frame
inBinary the binary object containing the package
inParms params frame
Return: a package frame
------------------------------------------------------------------------------- */
Ref
StoreSuckPackageFromEndpoint(RefArg inRcvr, RefArg inEndpoint, RefArg inParms)
{
NewtonErr err = noErr;
RefVar pkg;
#if 0 /* endpoints don’t work yet */
CEndpoint * ep = GetClientEndpoint(inEndpoint);
if (ep)
{
CEndpointPipe epp;
newton_try
{
epp.init(ep, 2*KByte, 0, 0, false, NULL);
pkg = AllocatePackage(&epp, inRcvr, inParms);
}
newton_catch_all
{
err = (NewtonErr)(long)CurrentException()data;
}
end_try;
}
#endif
if (err)
ThrowErr(exFrames, err);
return pkg;
}
| [
"simon@newtonresearch.org"
] | simon@newtonresearch.org |
2647a73f2e240df3c73a16960c90e0063c725162 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE124_Buffer_Underwrite/s03/CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B.cpp | c86a905a08b21ed1f9820db603a76df14f4159dd | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,866 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B.cpp
Label Definition File: CWE124_Buffer_Underwrite__new.label.xml
Template File: sources-sink-83_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE124_Buffer_Underwrite__new_char_memcpy_83.h"
namespace CWE124_Buffer_Underwrite__new_char_memcpy_83
{
CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B::CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B(char * dataCopy)
{
data = dataCopy;
{
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
}
CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B::~CWE124_Buffer_Underwrite__new_char_memcpy_83_goodG2B()
{
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memcpy(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
}
#endif /* OMITGOOD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
d3f231c3926414001b0da7a34c9b21ac615cf94d | 3601d7521b88d22b7e8afef8f031c64f5f075d91 | /Interfaces/UserGetQuestion.cpp | fad17e993517e06e5d855e779bea076bb01c11c6 | [] | no_license | GDUTSZH/AccountManagement | 1d27ac34b4b64c5510ab4526564bdb2588adcba7 | 6cf1bc6d5e0c257fe9ebf023de0df4ec2b1eb0f5 | refs/heads/master | 2021-05-15T16:55:50.388098 | 2017-11-21T08:49:29 | 2017-11-21T08:49:29 | 107,562,902 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,535 | cpp | #include "UserGetQuestion.h"
#define USER_GET_QUESTION_STR(sName) \
"SELECT * FROM \
( \
SELECT user_question1 AS QUESTIONS \
FROM AccountManagement_User WHERE \
user_name=\'"+(sName)+"\' \
UNION ALL \
SELECT user_question2 AS QUESTIONS \
FROM AccountManagement_User WHERE \
user_name=\'"+(sName)+"\' \
UNION ALL \
SELECT user_question3 AS QUESTIONS \
FROM AccountManagement_User WHERE \
user_name=\'"+(sName)+"\' \
) TempList;"
CUserGetQuestion::CUserGetQuestion(PREQ pReq) : CHttpCommon(pReq)
{ }
CUserGetQuestion::~CUserGetQuestion()
{ }
void CUserGetQuestion::Handle()
{
Json::Value jData;
if(!ParseParam(jData))
return;
if(!jData.isMember("name"))
{
Send_Error(404, Error_Data_Param_Miss);
return;
}
string sValues = USER_GET_QUESTION_STR(jData["name"].asString());
Json::Value jRoot = CMySQL_Client::GetInstance()->Select(sValues);
if(jRoot.isMember("error"))
{
Send_Fail(502, Error_Operation_Rrror(2, "User Login Failure"));
return;
}
int ret = jRoot["array"].size();
//问题个数小于
if(ret < 3)
{
Json::Value jContant;
jContant["data"] = "用户名不存在";
Json::Value jRet;
jRet["code"] = 2;
jRet["contant"] = jContant;
Send(504, jRet.toStyledString());
return;
}
Json::Value jContant;
jContant["question"] = jRoot["array"];
jContant["data"] = "Get Password Success";
Json::Value jRet;
jRet["code"] = 1;
jRet["contant"] = jContant;
Send(200, jRet.toStyledString());
} | [
"gdut_szh@163.com"
] | gdut_szh@163.com |
33ff034c896b7376ffddb10d69f0971ebd839dcd | 1c42215c5558211f02557ef1edd711d067ec78b6 | /src/Union_AlterDamage/ZenGin/Gothic_II_Classic/API/oInventory.h | 0795bc0a1c9954073e4cf3bf5d0556310cc57d9a | [] | no_license | UnresolvedExternal/Union_AlterDamage | fd5891c3a62896a3e2049e9fea2b3da9721c57c9 | 88b1ae773ea8e5c3762d2a5fd23b3ca7fae5c3b2 | refs/heads/master | 2023-07-26T13:52:00.230498 | 2023-07-11T17:49:13 | 2023-07-11T17:49:13 | 200,260,609 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,857 | h | // Supported with union (c) 2018 Union team
#ifndef __OINVENTORY_H__VER2__
#define __OINVENTORY_H__VER2__
#include "zViewBase.h"
#include "zArchiver.h"
namespace Gothic_II_Classic {
const int INV_MAX_SLOTS_COL = 8;
const int INV_MAX_SLOTS_ROW = 2;
enum {
INV_NONE,
INV_COMBAT,
INV_ARMOR,
INV_RUNE,
INV_MAGIC,
INV_FOOD,
INV_POTION,
INV_DOCS,
INV_OTHER,
INV_MAX
};
enum {
INV_MODE_DEFAULT,
INV_MODE_CONTAINER,
INV_MODE_PLUNDER,
INV_MODE_STEAL,
INV_MODE_BUY,
INV_MODE_SELL,
INV_MODE_MAX
};
class oCItemContainer : public zCInputCallback {
public:
zCListSort<oCItem>* contents;
oCNpc* npc;
zSTRING titleText;
int invMode;
int selectedItem;
int offset;
int maxSlotsCol;
int maxSlotsColScr;
int maxSlotsRow;
int maxSlotsRowScr;
int maxSlots;
int marginTop;
int marginLeft;
int frame;
int right;
int ownList;
int prepared;
int passive;
short TransferCount;
zCView* viewTitle;
zCView* viewBack;
zCView* viewItem;
zCView* viewItemActive;
zCView* viewItemHightlighted;
zCView* viewItemActiveHighlighted;
zCView* viewItemInfo;
zCView* viewItemInfoItem;
zCView* textView;
zCView* viewArrowAtTop;
zCView* viewArrowAtBottom;
zCWorld* rndWorld;
int posx;
int posy;
int m_bManipulateItemsDisabled;
int m_bCanTransferMoreThanOneItem;
void oCItemContainer_OnInit() zCall( 0x006A7270 );
oCItemContainer* GetNextContainerLeft( oCItemContainer* ) zCall( 0x006A7130 );
oCItemContainer* GetNextContainerRight( oCItemContainer* ) zCall( 0x006A71D0 );
oCItemContainer() zInit( oCItemContainer_OnInit() );
zCListSort<oCItem>* JumpOffset( int&, int& ) zCall( 0x006A8FC0 );
int ActivateNextContainer( int ) zCall( 0x006AC660 );
static int GetInvSplitScreen() zCall( 0x006A6B50 );
static short GetInvMaxColumns() zCall( 0x006A6B80 );
static short GetInvMaxRows() zCall( 0x006A6BD0 );
static short TransferCountToAmount( short ) zCall( 0x006A6C20 );
static float GetValueMultiplier() zCall( 0x006A6C60 );
static zSTRING GetCurrencyInstanceName() zCall( 0x006A6D80 );
static int GetCurrencyInstance() zCall( 0x006A6F70 );
static oCItem* CreateCurrencyItem( short ) zCall( 0x006A7010 );
static void RemoveCurrencyItem( oCItem* ) zCall( 0x006A70C0 );
static void Container_PrepareDraw() zCall( 0x006A70F0 );
static void Container_Draw() zCall( 0x006A7100 );
virtual int HandleEvent( int ) zCall( 0x006ACB50 );
virtual ~oCItemContainer() zCall( 0x006A87F0 );
virtual void Open( int, int, int ) zCall( 0x006AAA60 );
virtual void OpenPassive( int, int, int ) zCall( 0x006AABE0 );
virtual zSTRING GetName() zCall( 0x006A7480 );
virtual void SetName( zSTRING& ) zCall( 0x006A74D0 );
virtual int GetMode() zCall( 0x006A7610 );
virtual void SetMode( int ) zCall( 0x006A7620 );
virtual void Close() zCall( 0x006AB440 );
virtual void Activate() zCall( 0x006AB740 );
virtual void Deactivate() zCall( 0x006AB7A0 );
virtual int IsOpen() zCall( 0x006AB710 );
virtual int IsActive() zCall( 0x006A7640 );
virtual int IsEmpty() zCall( 0x006AC320 );
virtual int IsSplitScreen() zCall( 0x006AC350 );
virtual void SetContents( zCListSort<oCItem>* ) zCall( 0x006AAA00 );
virtual zCListSort<oCItem>* GetContents() zCall( 0x006AAA50 );
virtual oCItem* Insert( oCItem* ) zCall( 0x006AB870 );
virtual void Remove( oCItem* ) zCall( 0x006AB940 );
virtual oCItem* Remove( oCItem*, int ) zCall( 0x006AB9F0 );
virtual oCItem* RemoveByPtr( oCItem*, int ) zCall( 0x006AB9E0 );
virtual oCItem* GetSelectedItem() zCall( 0x006AB7D0 );
virtual int GetSelectedItemCount() zCall( 0x006AB800 );
virtual void GetSize( int&, int& ) zCall( 0x006A8F80 );
virtual void DisableManipulateItems( int ) zCall( 0x006A7650 );
virtual int CanManipulateItems() zCall( 0x006A7660 );
virtual void DisableTransferMoreThanOneItem( int ) zCall( 0x006A7670 );
virtual int CanTransferMoreThanOneItem() zCall( 0x006A7690 );
virtual int IsPassive() zCall( 0x006AB430 );
virtual short GetTransferCount() zCall( 0x006A76A0 );
virtual void SetTransferCount( short ) zCall( 0x006A76B0 );
virtual void IncTransferCount( short ) zCall( 0x006A76C0 );
virtual void Archive( zCArchiver& ) zCall( 0x006AC780 );
virtual void Unarchive( zCArchiver& ) zCall( 0x006AC970 );
virtual void Init( int, int, int ) zCall( 0x006A8D80 );
virtual void GetPosition( int&, int& ) zCall( 0x006A8FA0 );
virtual void LoadGrafix() zCall( 0x006A8940 );
virtual void DeleteContents() zCall( 0x006ABAA0 );
virtual void NextItem() zCall( 0x006ABC50 );
virtual void NextItemLine() zCall( 0x006ABEB0 );
virtual void PrevItem() zCall( 0x006AC010 );
virtual void PrevItemLine() zCall( 0x006AC240 );
virtual void CheckSelectedItem() zCall( 0x006ABB70 );
virtual int TransferItem( int, int ) zCall( 0x006AC450 );
virtual void Draw() zCall( 0x006A9BC0 );
virtual void DrawCategory() zCall( 0x006A9070 );
virtual void DrawItemInfo( oCItem*, zCWorld* ) zCall( 0x006A9350 );
// static properties
static zCList<oCItemContainer>& contList;
static int& gfx_loaded;
static zCGfx*& gfx_cat;
static zCGfx*& gfx_equip;
static zCGfx*& gfx_cursor;
static zCGfx*& gfx_cursor_equip;
static zCGfx**& gfx_arrow;
};
class oCStealContainer : public oCItemContainer {
public:
oCNpc* owner;
void oCStealContainer_OnInit() zCall( 0x006AD100 );
oCStealContainer() zInit( oCStealContainer_OnInit() );
virtual int HandleEvent( int ) zCall( 0x006AD5A0 );
virtual ~oCStealContainer() zCall( 0x006AD140 );
virtual void SetOwner( oCNpc* ) zCall( 0x006AD2C0 );
virtual oCNpc* GetOwner() zCall( 0x006AD2E0 );
virtual void CreateList() zCall( 0x006AD2F0 );
};
class oCNpcContainer : public oCStealContainer {
public:
void oCNpcContainer_OnInit() zCall( 0x006AD8D0 );
oCNpcContainer() zInit( oCNpcContainer_OnInit() );
virtual int HandleEvent( int ) zCall( 0x006ADC00 );
virtual ~oCNpcContainer() zCall( 0x006AD910 );
virtual oCItem* Insert( oCItem* ) zCall( 0x006ADF00 );
virtual void Remove( oCItem* ) zCall( 0x006ADF40 );
virtual void CreateList() zCall( 0x006ADA80 );
};
class oCNpcInventory : public oCItemContainer {
public:
oCNpc* owner;
int packAbility;
zCListSort<oCItem> inventory;
zSTRING packString;
int maxSlots;
void oCNpcInventory_OnInit() zCall( 0x0081FEC2 );
oCNpcInventory() zInit( oCNpcInventory_OnInit() );
void ClearInventory() zCall( 0x006AE2C0 );
void SetOwner( oCNpc* ) zCall( 0x006AE840 );
oCNpc* GetOwner() zCall( 0x006AE850 );
int GetNumItemsInCategory() zCall( 0x006AE860 );
oCItem* GetItem( int ) zCall( 0x006AE970 );
int GetCategory( oCItem* ) zCall( 0x006AEBB0 );
int GetAmount( int ) zCall( 0x006AEE80 );
int HandleTrade( int ) zCall( 0x006B02E0 );
void CheckForEquippedItems( int ) zCall( 0x006B1800 );
int CanCarry( oCItem* ) zCall( 0x006B1940 );
void SetPackAbility( int ) zCall( 0x006B1A70 );
void UnpackCategory() zCall( 0x006B1A90 );
int GetNumItemsInPackString() zCall( 0x006B1AA0 );
int GetPackedItemBySlot( int, zSTRING& ) zCall( 0x006B1B90 );
oCItem* CreateFromPackString( zSTRING const& ) zCall( 0x006B1CD0 );
int GetPackedItemInfo( zSTRING const&, int, int&, int& ) zCall( 0x006B1D60 );
int PackSingleItem( oCItem* ) zCall( 0x006B2010 );
void PackAllItems( int ) zCall( 0x006B2380 );
void UnpackAllItems() zCall( 0x006B2390 );
void PackItemsInCategory( int ) zCall( 0x006B23A0 );
void UnpackItemsInCategory() zCall( 0x006B2D80 );
virtual int HandleEvent( int ) zCall( 0x006B0520 );
virtual ~oCNpcInventory() zCall( 0x006AE110 );
virtual void Open( int, int, int ) zCall( 0x006AE420 );
virtual void Close() zCall( 0x006AE810 );
virtual oCItem* Insert( oCItem* ) zCall( 0x006AEC50 );
virtual oCItem* Remove( int, int ) zCall( 0x006AF590 );
virtual oCItem* Remove( zSTRING const&, int ) zCall( 0x006AF680 );
virtual oCItem* RemoveByPtr( oCItem*, int ) zCall( 0x006AF180 );
virtual void Archive( zCArchiver& ) zCall( 0x006AF6F0 );
virtual void Unarchive( zCArchiver& ) zCall( 0x006AFA30 );
virtual void Draw() zCall( 0x006AE830 );
virtual void DrawCategory() zCall( 0x006B00B0 );
virtual void Remove( oCItem* ) zCall( 0x006AF0F0 );
virtual oCItem* Remove( oCItem*, int ) zCall( 0x006AF330 );
virtual oCItem* IsIn( oCItem*, int ) zCall( 0x006AEF90 );
virtual oCItem* IsIn( int, int ) zCall( 0x006AF000 );
virtual oCItem* IsIn( zSTRING const&, int ) zCall( 0x006AEFD0 );
virtual int IsEmpty() zCall( 0x006AC320 );
virtual int IsEmpty( int ) zCall( 0x006AF6B0 );
// static properties
static zCGfx*& gfx_title;
};
} // namespace Gothic_II_Classic
#endif // __OINVENTORY_H__VER2__ | [
"vmi1401bsv04@gmail.com"
] | vmi1401bsv04@gmail.com |
38b197e7fa49cab79323d39b2824f66e8579a336 | c18b548e82bbc234eb3d01fdf6fab9464c37e845 | /old_demo/opencv_camera_test1.cpp | f59e2e2ec9033ff4aa909b5cc73e578d48a97e51 | [] | no_license | xiehuapeng/xiehuapeng | 026bec0d7a25ed65789fd624ab352f1cf84f70ba | 8b5752e4af6de88c85c8dcf76c6a5b5542279df8 | refs/heads/master | 2023-02-17T11:54:52.981706 | 2020-06-06T02:49:00 | 2020-06-06T02:49:00 | 155,349,681 | 0 | 0 | null | 2018-10-30T14:22:27 | 2018-10-30T08:25:35 | null | UTF-8 | C++ | false | false | 2,943 | cpp | //
// Created by caesar kekxv on 2020/3/12.
// http://scientistengineer.blogspot.com/2015/09/trying-to-generate-hdr-picture-from.html
//
#include "opencv2/opencv.hpp"
#include <vector>
#include <iostream>
#include <fstream>
using namespace cv;
using namespace std;
int main(int argc, char ** argv)
{
setenv("DISPLAY", "localhost:10.0", 1);
vector< Mat> images;
vector< float> times;
//float times[5];
VideoCapture camera;
camera.open(0);
// camera.set(CAP_PROP_FRAME_WIDTH,640);
// camera.set(CAP_PROP_FRAME_HEIGHT,480);
//for(;;)
//{
Mat defaultPic[5];
camera.set(CAP_PROP_EXPOSURE,-1);
//times[0] = 1;
camera >> defaultPic[0];
times.push_back(1);
images.push_back(defaultPic[0]);
namedWindow( "picture -1", WINDOW_AUTOSIZE );
imshow("picture -1", defaultPic[0]);
camera.set(CAP_PROP_EXPOSURE,2);
//times[1] = 0.2;
camera >> defaultPic[1];
times.push_back(2);
images.push_back(defaultPic[1]);
namedWindow( "picture -5", WINDOW_AUTOSIZE );
imshow("picture -5", defaultPic[1]);
camera.set(CAP_PROP_EXPOSURE,3);
//times[2] = 0.143;
camera >> defaultPic[2];
times.push_back(3);
images.push_back(defaultPic[2]);
namedWindow( "picture -7", WINDOW_AUTOSIZE );
imshow("picture -7", defaultPic[2]);
camera.set(CAP_PROP_EXPOSURE,4);
//times[3] = 0.11;
camera >> defaultPic[3];
times.push_back(4);
images.push_back(defaultPic[3]);
namedWindow( "picture -9", WINDOW_AUTOSIZE );
imshow("picture -9", defaultPic[3]);
camera.set(CAP_PROP_EXPOSURE,5);
//times[4] = 0.083;
camera >> defaultPic[4];
times.push_back(5);
images.push_back(defaultPic[4]);
imshow("img12.png",defaultPic[4]);
camera.set(CAP_PROP_EXPOSURE,7);
//times[4] = 0.083;
camera >> defaultPic[4];
times.push_back(7);
images.push_back(defaultPic[4]);
imshow("img13.png",defaultPic[4]);
camera.set(CAP_PROP_EXPOSURE,9);
//times[4] = 0.083;
camera >> defaultPic[4];
times.push_back(9);
images.push_back(defaultPic[4]);
namedWindow( "picture -12", WINDOW_AUTOSIZE );
imshow("picture -12", defaultPic[4]);
Mat response;
Ptr< CalibrateDebevec> calibrate = createCalibrateDebevec();
calibrate->process(images, response, times);
Mat hdr;
Ptr< MergeDebevec > merge_debevec = createMergeDebevec();
merge_debevec->process(images, hdr, times, response);
Mat ldr;
auto tonemap = cv::createTonemapDrago(2.2f);
tonemap->process(hdr, ldr);
Mat fusion;
// createTonemapDurand
auto merge_mertens = createMergeMertens();
merge_mertens->process(images, fusion);
imshow("fusion.png", fusion * 255);
imshow("ldr.png", ldr * 255);
imshow("hdr.hdr", hdr);
waitKey(0);
//}
return 0;
} | [
"1812412957@qq.com"
] | 1812412957@qq.com |
395a07d327962c499e8d2fd99fe72d831ab1f3c1 | 6e5303b1f5492b84f6ab911920975b78d0fe1982 | /BRAINSConstellationDetector/src/itkHoughTransformRadialVotingImageFilter.h | 373be68b5723eda87fa38a681a6a527a3cb8f95a | [] | no_license | aghayoor/BRAINSTools | ac247f73f6e874fa80094928ba68c1c2230f070d | 0da25be92227840b7290a83268f876e1d844c9ad | refs/heads/master | 2020-04-05T23:03:35.789313 | 2013-08-20T20:04:01 | 2013-08-20T20:04:01 | 9,104,769 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,748 | h | /*=========================================================================
Author: $Author: krm15 $ // Author of last commit
Version: $Rev: 585 $ // Revision of last commit
Date: $Date: 2009-08-20 21:25:19 -0400 (Thu, 20 Aug 2009) $ // Date of last commit
=========================================================================*/
/*=========================================================================
Authors: The GoFigure Dev. Team.
at Megason Lab, Systems biology, Harvard Medical school, 2009
Copyright (c) 2009, President and Fellows of Harvard College.
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 the President and Fellows of Harvard College
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 __itkHoughTransformRadialVotingImageFilter_h
#define __itkHoughTransformRadialVotingImageFilter_h
#include "itkImageToImageFilter.h"
#include "itkImage.h"
#include "itkEllipseSpatialObject.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkGaussianDerivativeImageFunction.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkCastImageFilter.h"
#include <itkGaussianDistribution.h>
#include "itkAddImageFilter.h"
#include "itkImageRegionIterator.h"
#if ITK_VERSION_MAJOR < 4 && !defined(ITKv3_THREAD_ID_TYPE_DEFINED)
#define ITKv3_THREAD_ID_TYPE_DEFINED 1
typedef int ThreadIdType;
#endif
namespace itk
{
/**
* \class HoughTransformRadialVotingImageFilter
* \brief Performs the Hough Transform to find circles in a 2D image.
*
* This filter derives from the base class ImageToImageFilter
* The input is an image, and all pixels above some threshold are those
* we want to consider during the process.
*
* This filter produces two output:
* 1) The accumulator array, which represents probability of centers.
* 2) The array or radii, which has the radius value at each coordinate point.
*
* When the filter found a "correct" point, it computes the gradient at this
* point and votes on a small region defined using the minimum and maximum
* radius given by the user, and fill in the array of radii.
*
* \ingroup ImageFeatureExtraction
* \todo Update the doxygen documentation!!!
* */
template <class TInputImage, class TOutputImage>
class HoughTransformRadialVotingImageFilter :
public ImageToImageFilter<TInputImage, TOutputImage>
{
public:
/** Standard "Self" typedef. */
typedef HoughTransformRadialVotingImageFilter Self;
/** Standard "Superclass" typedef. */
typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass;
/** Smart pointer typedef support. */
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
itkStaticConstMacro(ImageDimension, unsigned int,
TInputImage::ImageDimension);
/** Input Image typedef */
typedef TInputImage InputImageType;
typedef typename InputImageType::Pointer InputImagePointer;
typedef typename InputImageType::ConstPointer InputImageConstPointer;
typedef typename InputImageType::IndexType InputIndexType;
typedef typename InputIndexType::IndexValueType InputIndexValueType;
typedef typename InputImageType::PixelType InputPixelType;
typedef typename InputImageType::SizeType InputSizeType;
typedef typename InputSizeType::SizeValueType InputSizeValueType;
typedef typename InputImageType::RegionType InputRegionType;
typedef typename InputImageType::SpacingType InputSpacingType;
typedef typename InputImageType::PointType InputPointType;
typedef typename InputPointType::CoordRepType InputCoordType;
/** Output Image typedef */
typedef TOutputImage OutputImageType;
typedef typename OutputImageType::Pointer OutputImagePointer;
typedef typename OutputImageType::PixelType OutputPixelType;
typedef typename OutputImageType::RegionType OutputImageRegionType;
typedef Image<InputCoordType, ImageDimension> InternalImageType;
typedef typename InternalImageType::Pointer InternalImagePointer;
typedef typename InternalImageType::IndexType InternalIndexType;
typedef typename InternalIndexType::IndexValueType InternalIndexValueType;
typedef typename InternalImageType::PixelType InternalPixelType;
typedef typename InternalImageType::RegionType InternalRegionType;
typedef typename InternalImageType::SizeType InternalSizeType;
typedef typename InternalSizeType::SizeValueType InternalSizeValueType;
typedef typename InternalImageType::SpacingType InternalSpacingType;
/** Sphere typedef */
typedef EllipseSpatialObject<ImageDimension> SphereType;
typedef typename SphereType::Pointer SpherePointer;
typedef typename SphereType::VectorType SphereVectorType;
typedef std::list<SpherePointer> SpheresListType;
typedef ImageRegionIterator<InternalImageType> InternalIteratorType;
typedef ImageRegionIterator<OutputImageType> OutputIteratorType;
typedef DiscreteGaussianImageFilter<OutputImageType, InternalImageType>
GaussianFilterType;
typedef typename GaussianFilterType::Pointer
GaussianFilterPointer;
typedef itk::Statistics::GaussianDistribution GaussianFunctionType;
typedef typename GaussianFunctionType::Pointer GaussianFunctionPointer;
typedef GaussianDerivativeImageFunction<InputImageType, InputCoordType>
DoGFunctionType;
typedef typename DoGFunctionType::Pointer
DoGFunctionPointer;
typedef typename DoGFunctionType::VectorType
DoGVectorType;
typedef MinimumMaximumImageCalculator<InternalImageType> MinMaxCalculatorType;
typedef typename MinMaxCalculatorType::Pointer MinMaxCalculatorPointer;
typedef CastImageFilter<InternalImageType, OutputImageType> CastFilterType;
typedef typename CastFilterType::Pointer CastFilterPointer;
/** Run-time type information (and related methods). */
itkTypeMacro(HoughTransformRadialVotingImageFilter, ImageToImageFilter);
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Set both Minimum and Maximum radius values */
void SetRadius(InputCoordType radius);
/** Set the minimum radiu value the filter should look for */
itkSetMacro(MinimumRadius, InputCoordType);
/** Set the maximum radius value the filter should look for */
itkSetMacro(MaximumRadius, InputCoordType);
/** Set the threshold above which the filter should consider
the point as a valid point */
itkSetMacro(Threshold, double);
/** Get the threshold value */
itkGetConstMacro(Threshold, double);
/** Set the threshold above which the filter should consider
the point as a valid point */
itkSetMacro(OutputThreshold, InternalPixelType);
/** Get the threshold value */
itkGetConstMacro(OutputThreshold, InternalPixelType);
/** Set the threshold above which the filter should consider
the point as a valid point */
itkSetMacro(GradientThreshold, InputCoordType);
/** Get the threshold value */
itkGetConstMacro(GradientThreshold, InputCoordType);
/** Get the radius image */
itkGetConstObjectMacro(RadiusImage, InternalImageType);
/** Get the accumulator image */
itkGetConstObjectMacro(AccumulatorImage, InternalImageType);
/** Set the scale of the derivative function (using DoG) */
itkSetMacro(SigmaGradient, double);
/** Get the scale value */
itkGetConstMacro(SigmaGradient, double);
/** Get the list of circles. This recomputes the circles */
SpheresListType & GetSpheres();
/** Set/Get the number of circles to extract */
itkSetMacro(NumberOfSpheres, unsigned int);
itkGetConstMacro(NumberOfSpheres, unsigned int);
/** Set/Get the radius of the disc to remove from the accumulator
* for each circle found */
itkSetMacro(SphereRadiusRatio, InputCoordType);
itkGetConstMacro(SphereRadiusRatio, InputCoordType);
itkSetMacro(VotingRadiusRatio, InputCoordType);
itkGetConstMacro(VotingRadiusRatio, InputCoordType);
/** Set the variance of the gaussian bluring for the accumulator */
itkSetMacro(Variance, double);
itkGetConstMacro(Variance, double);
/** Set the number of threads */
itkSetMacro(NbOfThreads, unsigned int);
itkGetConstMacro(NbOfThreads, unsigned int);
/** Set the number of threads */
itkSetMacro(SamplingRatio, double);
itkGetConstMacro(SamplingRatio, double);
/** Set the mode of the algorithm */
/** HoughEyeDetectorMode = 0: Detecting bright spheres in a dark environment.
*/
/** HoughEyeDetectorMode = 1: Detecting dark spheres in a bright environment.
*/
itkSetMacro(HoughEyeDetectorMode, int);
/** Get the mode of the algorithm */
itkGetConstMacro(HoughEyeDetectorMode, int);
#ifdef ITK_USE_CONCEPT_CHECKING
/** Begin concept checking */
itkConceptMacro( IntConvertibleToOutputCheck,
( Concept::Convertible<int, OutputPixelType> ) );
itkConceptMacro( InputGreaterThanDoubleCheck,
( Concept::GreaterThanComparable<InputPixelType, double> ) );
itkConceptMacro( OutputPlusIntCheck,
( Concept::AdditiveOperators<OutputPixelType, int> ) );
itkConceptMacro( OutputDividedByIntCheck,
( Concept::DivisionOperators<OutputPixelType, int> ) );
/** End concept checking */
#endif
protected:
HoughTransformRadialVotingImageFilter();
virtual ~HoughTransformRadialVotingImageFilter();
InputCoordType m_MinimumRadius;
InputCoordType m_MaximumRadius;
double m_Threshold;
InputCoordType m_GradientThreshold;
InternalPixelType m_OutputThreshold;
double m_SigmaGradient;
double m_Variance;
InputCoordType m_VotingRadiusRatio;
InputCoordType m_SphereRadiusRatio;
double m_SamplingRatio;
InternalImagePointer m_RadiusImage;
InternalImagePointer m_AccumulatorImage;
SpheresListType m_SpheresList;
unsigned int m_NumberOfSpheres;
unsigned long m_OldModifiedTime;
unsigned int m_NbOfThreads;
bool m_AllSeedsProcessed;
// -- Add by Wei Lu
int m_HoughEyeDetectorMode;
/** Method for evaluating the implicit function over the image. */
virtual void BeforeThreadedGenerateData();
virtual void AfterThreadedGenerateData();
virtual void ThreadedGenerateData(const OutputImageRegionType & windowRegion, ThreadIdType threadId);
void PrintSelf(std::ostream & os, Indent indent) const;
/** HoughTransformRadialVotingImageFilter needs the entire input. Therefore
* it must provide an implementation GenerateInputRequestedRegion().
* \sa ProcessObject::GenerateInputRequestedRegion(). */
void GenerateInputRequestedRegion();
/** HoughTransformRadialVotingImageFilter's produces all the output.
* Therefore, it must provide an implementation of
* EnlargeOutputRequestedRegion.
* \sa ProcessObject::EnlargeOutputRequestedRegion() */
void EnlargeOutputRequestedRegion( DataObject * itkNotUsed(output) );
void ComputeMeanRadiusImage();
private:
HoughTransformRadialVotingImageFilter(const Self &)
{
}
void operator=(const Self &)
{
}
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkHoughTransformRadialVotingImageFilter.hxx"
#endif
#endif
| [
"hans-johnson@uiowa.edu"
] | hans-johnson@uiowa.edu |
f6415cd281f75068aea364ce8ff0cbd20bc007ad | a9636f0d96503b890f0f80d52de6fa7beb3ffe29 | /visual_widgets/dual_state_diagram/dualstatediagram.h | 64f5b0cafcdd87be6eeddbd595792f4aab974b4f | [] | no_license | grigp/a-analyser | 5d14e8f91e2104fbc8ffbf47a28d20fd95eb667e | 026badde88531b13a788140f8a3e13f08d4a5371 | refs/heads/master | 2023-09-01T08:09:35.475413 | 2023-06-14T11:37:22 | 2023-06-14T11:37:22 | 244,710,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | h | #ifndef DUALSTATEDIAGRAM_H
#define DUALSTATEDIAGRAM_H
#include <QWidget>
#include "dualstatediagrampainter.h"
namespace Ui {
class DualStateDiagram;
}
/*!
* \brief Класс визуальной диаграммы двунаправленного отображения состояния относительно нуля DualStateDiagram class
*/
class DualStateDiagram : public QWidget, public DualStateDiagramPainter
{
Q_OBJECT
public:
explicit DualStateDiagram(QWidget *parent = nullptr);
~DualStateDiagram() override;
protected:
void paintEvent(QPaintEvent *event) override;
void doUpdate() override;
private:
Ui::DualStateDiagram *ui;
};
#endif // DUALSTATEDIAGRAM_H
| [
"grig_p@mail.ru"
] | grig_p@mail.ru |
2d7e02b16530bbd60ea563d5682c1e2081711672 | 8e37565d1f9d0f2ccce02a2ae760da13e5410ad1 | /bubblebutton.h | 6635c5dc561c4b2bc21f74c781da0658d6d79d4b | [] | no_license | YashGovindani/DrawOver | 54599a19496a1f910be269aee57383868f101e5f | 46f09744e1e90043e4acf81dea3dc3076f04ba1c | refs/heads/main | 2023-08-06T19:28:22.730526 | 2021-09-26T12:36:29 | 2021-09-26T12:36:29 | 406,796,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,068 | h | #ifndef BUBBLEBUTTON_H
#define BUBBLEBUTTON_H
#include "minibubblebutton.h"
#include <QPushButton>
#include <QGraphicsDropShadowEffect>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QApplication>
class BubbleButton:public QPushButton
{
private:
BubbleButton(QWidget *loadingView = nullptr);
static BubbleButton *bubbleButton;
int startX;
int startY;
int buttonX;
int buttonY;
bool moved;
bool expanded;
QString cornerRadius;
MiniBubbleButton penButton;
MiniBubbleButton highLighterButton;
MiniBubbleButton backToWorkButton;
MiniBubbleButton clearButton;
MiniBubbleButton eraserButton;
MiniBubbleButton expandButton;
QApplication *a;
public:
static BubbleButton * get(QWidget *loadingView = nullptr);
void mousePressEvent(QMouseEvent*);
void mouseMoveEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
void onClick();
~BubbleButton();
QApplication *getA() const;
void setA(QApplication *value);
void compressAction();
};
#endif // BUBBLEBUTTON_H
| [
"yashgovindani222@gmail.com"
] | yashgovindani222@gmail.com |
9b59ceff4b65bdd9b2efce59f3126fdac5c3cde5 | 19e2519b62e11d8cb5bc901836ce3a47f0906188 | /tests/src/small_string_tests.cpp | 81fb41102dde2ea7eb225c9e4bd5d1d2cd48e0c6 | [
"BSL-1.0"
] | permissive | DebugOfTheRoad/jsoncons | 69010e824a4865a10112cf81abf22fd8f0b1a7a7 | 31c5779565c3731f1cbd882f44186371eea3d0cc | refs/heads/master | 2021-07-04T07:24:25.075667 | 2017-09-26T03:43:55 | 2017-09-26T03:43:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | cpp | // Copyright 2013 Daniel Parker
// Distributed under Boost license
#ifdef __linux__
#define BOOST_TEST_DYN_LINK
#endif
#include <boost/test/unit_test.hpp>
#include <jsoncons/json.hpp>
#include <jsoncons/json_serializer.hpp>
#include <jsoncons/json_filter.hpp>
#include <sstream>
#include <vector>
#include <utility>
#include <ctime>
#include <new>
#include <boost/optional.hpp>
using namespace jsoncons;
BOOST_AUTO_TEST_SUITE(small_string_tests)
BOOST_AUTO_TEST_CASE(test_small_string)
{
json s("ABCD");
BOOST_CHECK(s.type_id() == jsoncons::value_type::small_string_t);
BOOST_CHECK(s.as<std::string>() == std::string("ABCD"));
json t(s);
BOOST_CHECK(t.type_id() == jsoncons::value_type::small_string_t);
BOOST_CHECK(t.as<std::string>() == std::string("ABCD"));
json q;
q = s;
BOOST_CHECK(q.type_id() == jsoncons::value_type::small_string_t);
BOOST_CHECK(q.as<std::string>() == std::string("ABCD"));
}
BOOST_AUTO_TEST_SUITE_END()
| [
"danielaparker@yahoo.com"
] | danielaparker@yahoo.com |
5e0e4ca486de5053a9dff1dad629ada4339deb1c | 210b2d9c0da7de96bd50ca31219741e3bc897770 | /KnockOut/Source.h | 79f74255d6a5d4c88548dbe7201ba319a8ceaa65 | [] | no_license | acesaspa/KnockOut | c896e906289b3ac3483318422a8b90787ab00794 | c8e027b5ccf405ffe9daa1676f8a8ec5a0925cf3 | refs/heads/main | 2023-04-10T20:14:28.564392 | 2021-03-31T23:13:00 | 2021-03-31T23:13:00 | 365,092,532 | 1 | 0 | null | 2021-05-07T02:30:00 | 2021-05-07T02:29:59 | null | UTF-8 | C++ | false | false | 131 | h | #ifndef SOURCE_H
#define SOURCE_H
#include "PowerUp.h"
class Source
{
public:
void passValue(PowerUp& a);
private:
};
#endif
| [
"noahbensler@gmail.com"
] | noahbensler@gmail.com |
1c5acf49becbe5d98c5509a3fc63b7ae0e10815b | ca99bc050dbc58be61a92e04f2a80a4b83cb6000 | /Game/src/Entities/Tux.cpp | 150fd862b5c7e381ea3cbf05b110ecb526a79f82 | [] | no_license | NicolasBeaudrot/angry-tux | e26c619346c63a468ad3711de786e94f5b78a2f1 | 5a8259f57ba59db9071158a775948d06e424a9a8 | refs/heads/master | 2021-01-06T20:41:23.705460 | 2011-04-14T18:28:04 | 2011-04-14T18:28:04 | 32,141,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | cpp | #include "Tux.h"
Tux::Tux(sf::RenderWindow* app
,sf::Vector2i& position
,std::string& path
,int type
,b2World* world) : Entity(app, position, path = "tuxs/" + path, 0){
_type = type;
_fire = false;
//Physics definition
b2BodyDef bd;
bd.position.Set(_position.x, _position.y);
bd.type = b2_dynamicBody;
bd.angularDamping = 0.01f;
b2CircleShape circle;
circle.m_radius = _image->GetWidth() / 2.0f;
b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.3f;
fixtureDef.filter.groupIndex = -type;
_tuxBody = world->CreateBody(&bd);
_tuxBody->CreateFixture(&fixtureDef);
b2MassData mass_data;
mass_data.center = b2Vec2(0,0);
mass_data.mass = 250.0f;
mass_data.I = 600.0f;
_tuxBody->SetMassData(&mass_data);
_sprite.SetCenter(_image->GetWidth()/2, _image->GetHeight()/2);
}
Tux::~Tux() {
}
void Tux::mouseReleased(sf::Vector2f firstPosition, sf::Vector2f secondPosition, float time_elapse) {
firstPosition = Conversion::to_sfmlcoord(firstPosition);
secondPosition = Conversion::to_sfmlcoord(secondPosition);
int K = 1000000;
float angle = Algorithm::getAngle(firstPosition, secondPosition);
std::cout << "Angle: " << angle << std::endl;
_force = b2Vec2(cos(Conversion::to_radian(angle)) * K, sin(Conversion::to_radian(angle)) * K);
_tuxBody->ApplyForce(_force, _tuxBody->GetWorldCenter());
_fire = true;
cpt=0;
}
void Tux::render() {
if (_fire) {
if (_timer.GetElapsedTime() > 0.5) {
if (cpt < 3) {
_tuxBody->ApplyForce(_force, _tuxBody->GetWorldCenter());
cpt++;
} else {
_fire = false;
}
_timer.Reset();
}
}
sf::Vector2i position_sfml = Conversion::to_sfmlcoord(_tuxBody->GetPosition().x, _tuxBody->GetPosition().y);
_sprite.SetPosition(position_sfml.x, position_sfml.y);
_sprite.SetRotation(Conversion::to_degres(_tuxBody->GetAngle()));
_app->Draw(_sprite);
}
| [
"nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad"
] | nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad |
de1fc52ad2829ab563403e348c1edc9263fd0123 | 4fc43da9da433ed8c94e27138c43f2a7e66a1111 | /cs215/Lab1/brewereL1.cpp | aaed1953de4a522fd2cad66576bfaedd59c7359a | [] | no_license | EricRobertBrewer/SonomaState | 59520fd93ceefe09b1d435e3034e88c354d78c60 | c991d2394261ece81535dd5e9056c90a8de55d98 | refs/heads/master | 2021-01-16T18:06:17.457213 | 2012-11-28T08:46:58 | 2012-11-28T08:46:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | /*
Eric Brewer
1/28/08
CS215
Lab1
*/
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
int consonantCount = 0;
int vowelCount = 0;
int wordCount = 0;
int digitCount = 0;
int specialCharCount = 0;
fin.open("words.txt");
string word;
while (fin >> word) {
wordCount++;
for (int i = 0; i < word.length(); i++) {
if (isalpha(word[i])) {
if (word[i] == 'A' || word[i] =='a' || word[i] =='E' || word[i] =='e' || word[i] =='I' || word[i] =='i' || word[i] =='O' || word[i] =='o' || word[i] =='U' || word[i] =='u')
vowelCount++;
else
consonantCount++;
}
else {
if (isdigit(word[i]))
digitCount++;
else
specialCharCount++;
}
}
}
fin.close();
cout << "Words: " << wordCount << "\n"
<< "Vowels: " << vowelCount << "\n"
<< "Consonants: " << consonantCount << "\n"
<< "Digits: " << digitCount << "\n"
<< "Special Characters: " << specialCharCount << "\n";
return 0;
}
| [
"eric.r.brewer@gmail.com"
] | eric.r.brewer@gmail.com |
5922dbee24415a34ec9c93771fec1e7763f9684f | 1b712a2a6ccdd5a8fd9070749205d2dd97e78299 | /算法结构/sap(精).cpp | 8ff3ec2341166160c9ad0d09c64e4f6aa273ea1b | [] | no_license | xsy1996/C_algorithm_codes | b12eff717bbbf19f6872b2da35b532abc8392f37 | 2e9b8ad99d330de39bc000b8c0fa3dc9242b3147 | refs/heads/master | 2020-04-13T12:26:46.975699 | 2018-12-26T17:24:54 | 2018-12-26T17:24:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | cpp | #include<cstdio>
#define min(a,b) ((a)<(b)?(a):(b))
const int MAX=2100000000,MAXn=200+9;
int n,answer,g[MAXn][MAXn],d[MAXn],gap[MAXn],st=1,ed=n;
int sap(int u,int flow)
{
if(u==ed)
return flow;
int ans=0,i,t;
for(i=1;i<=n;++i)
if(g[u][i] && d[u]==d[i]+1)
{
t=sap(i,min(flow-ans,g[u][i]));
g[u][i]-=t,g[i][u]+=t,ans+=t;
if(ans==flow)
return ans;
}
if(d[st]>=n)
return ans;
if(!--gap[d[u]])
d[st]=n;
++gap[++d[u]];
return ans;
}
int main()
{
int m,i,t1,t2,t3;
freopen("ditch.in","r",stdin);freopen("ditch.out","w",stdout);
scanf("%d%d",&m,&n);
for(i=1;i<=m;++i)
{
scanf("%d%d%d",&t1,&t2,&t3);
g[t1][t2]+=t3;
}
for(gap[0]=n;d[st]<n;)
answer+=sap(st,MAX);
printf("%d\n",answer);
return 0;
}
| [
"Xushiyu1996@gmail.com"
] | Xushiyu1996@gmail.com |
616715b35fbdd0b0aa0460ac20ad0f81d15b292e | 8476ceb52232150ef5359b631b942a417acc46e0 | /libs/ofxMapper/src/Vertices.h | da0e318a03cd1042b56a057e33772e10b540867f | [] | no_license | tobiasebsen/ofxMapper | 7b6835e08b2079de8fda58d47a89ab90b8ad9c2a | 09a5c55c32f06aed489897e27af5fe43f5562ea7 | refs/heads/master | 2020-08-28T00:30:38.212153 | 2020-06-24T11:28:20 | 2020-06-24T11:28:20 | 217,534,728 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | #pragma once
#include "ofMain.h"
class Vertices {
public:
Vertices(size_t w, size_t h) : width(w), height(h) {
data = new glm::vec2[w*h];
}
~Vertices() {
delete data;
}
glm::vec2 * data = NULL;
size_t width = 0;
size_t height = 0;
};
typedef shared_ptr<Vertices> VerticesPtr;
| [
"tobiasebsen@gmail.com"
] | tobiasebsen@gmail.com |
7c6b50176cf19d0a442737166862ac48e9e0d812 | c8c6ad39945d24173b257dd8954b475c1d31f47f | /Embedded/Projects/March 2/main.cpp | 33a1a5188ffcb23e76b5bbe95af820742b7f5e5f | [] | no_license | BaiLiping/BLP | 5e75827292c206f1874fae825ad39d8c4bd2c746 | 38d3b60da6d4d0683e9683e556ed05e16484dba4 | refs/heads/master | 2023-08-04T23:22:07.920071 | 2023-07-19T07:16:28 | 2023-07-19T07:16:28 | 173,741,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | cpp | #include <iostream>
//#include <cintstd>
#include <vector>
using namespace std;
int main()
{
vector<uint64_t> lookuptable;
std::vector<uint64_t>::iterator p;
p=lookuptable.begin();
*p=1;
*(p+1)=2;
*(p+2)=3;
cout<<*(p+2)<<endl;
return 0;
}
| [
"blp_engineer@outlook.com"
] | blp_engineer@outlook.com |
f3f4c3e82a8b42e50582a1bb800ab45436bcff7d | 3510a32a7c24394f0fb722989259b3ca39ead5df | /Monster.hpp | f7821cf1b30b46b1fd687e582e7c79a3ee091298 | [] | no_license | realshooky/MMSearch | ac55d812165240b0603263c839d3fbb7f65d6e0d | 9fe4a286dac228d28194f8a8e4d92b4bd8401501 | refs/heads/master | 2020-07-03T08:11:53.025521 | 2019-08-15T03:06:24 | 2019-08-15T03:06:24 | 201,848,442 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | hpp | #include <string>
class Monster
{
public:
Monster();
// setters
void setName(char *);
void setName(std::string&);
void setSize(char *);
void setSize(std::string&);
void setType(char *);
void setType(std::string&);
void setAlignment(char *);
void setAlignment(std::string&);
void setHP_Dice(char *);
void setHP_Dice(std::string&);
void setSpeeds(char *);
void setSpeeds(std::string&);
void setHP(int&);
void setAC(int&);
void setCR(double&);
void setXP(int&);
void setArmors(char *);
void setArmors(std::string&);
//getters
const char * getName() const;
const char * getSize() const;
const char * getType() const;
const char * getAlignment() const;
const char * getHP_Dice() const;
const char * getSpeeds() const;
std::string getNameString() const;
int getHP() const;
int getAC() const;
double getCR() const;
int getXP() const;
const char * getArmors() const;
friend bool operator<(const Monster&, const Monster&);
friend bool operator==(const Monster&, const Monster&);
private:
std::string name, size, type, armors;
std::string alignment, HP_Dice, speeds;
// Armor Class, Challenge Rating, Experience Points
int HP, AC, XP;
double CR;
// Natural Armor?
}; | [
"realshooky"
] | realshooky |
a2d4e0aa7e7da79efed8f9181bc802ff1f3f3892 | 66330f7a1ff0b8447b4245474ab4de48727fd1c5 | /libs/marshalling/core/include/nil/marshalling/types/no_value/basic_type.hpp | 7d294e46d470395825327ea8771bf19b2a49f959 | [
"MIT"
] | permissive | everscalecodes/knapsack-snark | fd3cc6155125ae6ff0fc56aa979f84ba6a8c49c7 | 633515a13906407338a81b9874d964869ddec624 | refs/heads/main | 2023-07-18T06:05:22.319230 | 2021-08-31T16:10:16 | 2021-08-31T16:10:16 | 447,180,824 | 0 | 1 | MIT | 2022-01-12T10:53:21 | 2022-01-12T10:53:20 | null | UTF-8 | C++ | false | false | 4,374 | hpp | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//
#ifndef MARSHALLING_BASIC_NO_VALUE_HPP
#define MARSHALLING_BASIC_NO_VALUE_HPP
#include <type_traits>
#include <nil/marshalling/status_type.hpp>
namespace nil {
namespace marshalling {
namespace types {
namespace detail {
template<typename TFieldBase>
class basic_no_value : public TFieldBase {
using base_impl_type = TFieldBase;
public:
using value_type = unsigned;
using serialized_type = value_type;
basic_no_value() = default;
basic_no_value(const basic_no_value &) = default;
basic_no_value(basic_no_value &&) = default;
~basic_no_value() noexcept = default;
basic_no_value &operator=(const basic_no_value &) = default;
basic_no_value &operator=(basic_no_value &&) = default;
static value_type &value() {
static value_type value = value_type();
return value;
}
static constexpr std::size_t length() {
return 0U;
}
static constexpr std::size_t min_length() {
return length();
}
static constexpr std::size_t max_length() {
return length();
}
static constexpr serialized_type to_serialized(value_type val) {
return static_cast<serialized_type>(val);
}
static constexpr value_type from_serialized(serialized_type val) {
return static_cast<value_type>(val);
}
template<typename TIter>
static status_type read(TIter &iter, std::size_t size) {
static_cast<void>(iter);
static_cast<void>(size);
return status_type::success;
}
template<typename TIter>
static void read_no_status(TIter &iter) {
static_cast<void>(iter);
}
template<typename TIter>
static status_type write(TIter &iter, std::size_t size) {
static_cast<void>(iter);
static_cast<void>(size);
return status_type::success;
}
template<typename TIter>
static void write_no_status(TIter &iter) {
static_cast<void>(iter);
}
};
} // namespace detail
} // namespace types
} // namespace marshalling
} // namespace nil
#endif // MARSHALLING_BASIC_NO_VALUE_HPP
| [
"curryrasul@gmail.com"
] | curryrasul@gmail.com |
8d00b074cfb27b4b5020f56dface31d213234e95 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /ui/ozone/platform/wayland/xdg_surface_wrapper.h | 3aa7240f8dcd4e0d636247eb7214e8ca8ebce57c | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 1,831 | h | // Copyright 2017 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.
#ifndef UI_OZONE_PLATFORM_WAYLAND_XDG_SURFACE_WRAPPER_H_
#define UI_OZONE_PLATFORM_WAYLAND_XDG_SURFACE_WRAPPER_H_
#include "base/strings/string16.h"
#include "ui/ozone/platform/wayland/wayland_object.h"
namespace gfx {
class Rect;
}
namespace ui {
class WaylandConnection;
// Wrapper interface for different xdg shell versions.
class XDGSurfaceWrapper {
public:
virtual ~XDGSurfaceWrapper() {}
// Initializes the surface.
virtual bool Initialize(WaylandConnection* connection,
wl_surface* surface) = 0;
// Sets a native window to maximized state.
virtual void SetMaximized() = 0;
// Unsets a native window from maximized state.
virtual void UnSetMaximized() = 0;
// Sets a native window to fullscreen state.
virtual void SetFullScreen() = 0;
// Unsets a native window from fullscreen state.
virtual void UnSetFullScreen() = 0;
// Sets a native window to minimized state.
virtual void SetMinimized() = 0;
// Tells wayland to start interactive window drag.
virtual void SurfaceMove(WaylandConnection* connection) = 0;
// Tells wayland to start interactive window resize.
virtual void SurfaceResize(WaylandConnection* connection,
uint32_t hittest) = 0;
// Sets a title of a native window.
virtual void SetTitle(const base::string16& title) = 0;
// Sends acknowledge configure event back to wayland.
virtual void AckConfigure() = 0;
// Sets a desired window geometry once wayland requests client to do so.
virtual void SetWindowGeometry(const gfx::Rect& bounds) = 0;
};
} // namespace ui
#endif // UI_OZONE_PLATFORM_WAYLAND_XDG_SURFACE_WRAPPER_H_
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
fa801c65b682a44280459aa78214741d23a16c6a | be5e2f6c52805f40d6108288a851dbb214eef4f1 | /src/muparser/muParserDef.h | 52c676c2c2d5e1530055d70f9c43d8bcc94ba9af | [
"BSD-3-Clause",
"MIT"
] | permissive | ismailqau/isymtecai-chrono-parser | c17e1b769845eab66243f396b3ae259d0bff322e | 9f6f0d1d0493de8332af6885a9ccde95c7d809b2 | refs/heads/master | 2020-03-29T23:42:17.199121 | 2018-09-04T14:47:46 | 2018-09-04T14:47:46 | 150,484,953 | 0 | 0 | BSD-3-Clause | 2018-09-26T20:17:14 | 2018-09-26T20:17:13 | null | UTF-8 | C++ | false | false | 14,249 | h | /*
__________
_____ __ __\______ \_____ _______ ______ ____ _______
/ \ | | \| ___/\__ \ \_ __ \/ ___/_/ __ \\_ __ \
| Y Y \| | /| | / __ \_| | \/\___ \ \ ___/ | | \/
|__|_| /|____/ |____| (____ /|__| /____ > \___ >|__|
\/ \/ \/ \/
Copyright (C) 2014 Ingo Berg
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MUP_DEF_H
#define MUP_DEF_H
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include "muParserFixes.h"
/** \file
\brief This file contains standard definitions used by the parser.
*/
#define MUP_VERSION _T("2.2.5")
#define MUP_VERSION_DATE _T("20150427; GC")
#define MUP_CHARS _T("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
/** \brief If this macro is defined mathematical exceptions (div by zero) will be thrown as exceptions. */
//#define MUP_MATH_EXCEPTIONS
/** \brief Define the base datatype for values.
This datatype must be a built in value type. You can not use custom classes.
It should be working with all types except "int"!
*/
#define MUP_BASETYPE double
/** \brief Activate this option in order to compile with OpenMP support.
OpenMP is used only in the bulk mode it may increase the performance a bit.
*/
//#define MUP_USE_OPENMP
#if defined(_UNICODE)
/** \brief Definition of the basic parser string type. */
#define MUP_STRING_TYPE std::wstring
#if !defined(_T)
#define _T(x) L##x
#endif // not defined _T
#else
#ifndef _T
#define _T(x) x
#endif
/** \brief Definition of the basic parser string type. */
#define MUP_STRING_TYPE std::string
#endif
#if defined(_DEBUG)
/** \brief Debug macro to force an abortion of the programm with a certain message.
*/
#define MUP_FAIL(MSG) \
{ \
bool MSG=false; \
assert(MSG); \
}
/** \brief An assertion that does not kill the program.
This macro is neutralised in UNICODE builds. It's
too difficult to translate.
*/
#define MUP_ASSERT(COND) \
if (!(COND)) \
{ \
stringstream_type ss; \
ss << _T("Assertion \"") _T(#COND) _T("\" failed: ") \
<< __FILE__ << _T(" line ") \
<< __LINE__ << _T("."); \
throw ParserError( ss.str() ); \
}
#else
#define MUP_FAIL(MSG)
#define MUP_ASSERT(COND)
#endif
namespace mu
{
#if defined(_UNICODE)
//------------------------------------------------------------------------------
/** \brief Encapsulate wcout. */
inline std::wostream& console()
{
return std::wcout;
}
/** \brief Encapsulate cin. */
inline std::wistream& console_in()
{
return std::wcin;
}
#else
/** \brief Encapsulate cout.
Used for supporting UNICODE more easily.
*/
inline std::ostream& console()
{
return std::cout;
}
/** \brief Encapsulate cin.
Used for supporting UNICODE more easily.
*/
inline std::istream& console_in()
{
return std::cin;
}
#endif
//------------------------------------------------------------------------------
/** \brief Bytecode values.
\attention The order of the operator entries must match the order in ParserBase::c_DefaultOprt!
*/
enum ECmdCode
{
// The following are codes for built in binary operators
// apart from built in operators the user has the opportunity to
// add user defined operators.
cmLE = 0, ///< Operator item: less or equal
cmGE = 1, ///< Operator item: greater or equal
cmNEQ = 2, ///< Operator item: not equal
cmEQ = 3, ///< Operator item: equals
cmLT = 4, ///< Operator item: less than
cmGT = 5, ///< Operator item: greater than
cmADD = 6, ///< Operator item: add
cmSUB = 7, ///< Operator item: subtract
cmMUL = 8, ///< Operator item: multiply
cmDIV = 9, ///< Operator item: division
cmPOW = 10, ///< Operator item: y to the power of ...
cmLAND = 11,
cmLOR = 12,
cmASSIGN = 13, ///< Operator item: Assignment operator
cmBO = 14, ///< Operator item: opening bracket
cmBC = 15, ///< Operator item: closing bracket
cmIF = 16, ///< For use in the ternary if-then-else operator
cmELSE = 17, ///< For use in the ternary if-then-else operator
cmENDIF = 18, ///< For use in the ternary if-then-else operator
cmARG_SEP = 19, ///< function argument separator
cmVAR = 20, ///< variable item
cmVAL = 21, ///< value item
// For optimization purposes
cmVARPOW2,
cmVARPOW3,
cmVARPOW4,
cmVARMUL,
cmPOW2,
// operators and functions
cmFUNC, ///< Code for a generic function item
cmFUNC_STR, ///< Code for a function with a string parameter
cmFUNC_BULK, ///< Special callbacks for Bulk mode with an additional parameter for the bulk index
cmSTRING, ///< Code for a string token
cmOPRT_BIN, ///< user defined binary operator
cmOPRT_POSTFIX, ///< code for postfix operators
cmOPRT_INFIX, ///< code for infix operators
cmEND, ///< end of formula
cmUNKNOWN ///< uninitialized item
};
//------------------------------------------------------------------------------
/** \brief Types internally used by the parser.
*/
enum ETypeCode
{
tpSTR = 0, ///< String type (Function arguments and constants only, no string variables)
tpDBL = 1, ///< Floating point variables
tpVOID = 2 ///< Undefined type.
};
//------------------------------------------------------------------------------
enum EParserVersionInfo
{
pviBRIEF,
pviFULL
};
//------------------------------------------------------------------------------
/** \brief Parser operator precedence values. */
enum EOprtAssociativity
{
oaLEFT = 0,
oaRIGHT = 1,
oaNONE = 2
};
//------------------------------------------------------------------------------
/** \brief Parser operator precedence values. */
enum EOprtPrecedence
{
// binary operators
prLOR = 1,
prLAND = 2,
prLOGIC = 3, ///< logic operators
prCMP = 4, ///< comparsion operators
prADD_SUB = 5, ///< addition
prMUL_DIV = 6, ///< multiplication/division
prPOW = 7, ///< power operator priority (highest)
// infix operators
prINFIX = 6, ///< Signs have a higher priority than ADD_SUB, but lower than power operator
prPOSTFIX = 6 ///< Postfix operator priority (currently unused)
};
//------------------------------------------------------------------------------
// basic types
/** \brief The numeric datatype used by the parser.
Normally this is a floating point type either single or double precision.
*/
typedef MUP_BASETYPE value_type;
/** \brief The stringtype used by the parser.
Depends on whether UNICODE is used or not.
*/
typedef MUP_STRING_TYPE string_type;
/** \brief The character type used by the parser.
Depends on whether UNICODE is used or not.
*/
typedef string_type::value_type char_type;
/** \brief Typedef for easily using stringstream that respect the parser stringtype. */
typedef std::basic_stringstream<char_type,
std::char_traits<char_type>,
std::allocator<char_type> > stringstream_type;
// Data container types
/** \brief Type used for storing variables. */
typedef std::map<string_type, value_type*> varmap_type;
/** \brief Type used for storing constants. */
typedef std::map<string_type, value_type> valmap_type;
/** \brief Type for assigning a string name to an index in the internal string table. */
typedef std::map<string_type, std::size_t> strmap_type;
// Parser callbacks
/** \brief Callback type used for functions without arguments. */
typedef value_type (*generic_fun_type)();
/** \brief Callback type used for functions without arguments. */
typedef value_type (*fun_type0)();
/** \brief Callback type used for functions with a single arguments. */
typedef value_type (*fun_type1)(value_type);
/** \brief Callback type used for functions with two arguments. */
typedef value_type (*fun_type2)(value_type, value_type);
/** \brief Callback type used for functions with three arguments. */
typedef value_type (*fun_type3)(value_type, value_type, value_type);
/** \brief Callback type used for functions with four arguments. */
typedef value_type (*fun_type4)(value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with five arguments. */
typedef value_type (*fun_type5)(value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with six arguments. */
typedef value_type (*fun_type6)(value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with seven arguments. */
typedef value_type (*fun_type7)(value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with eight arguments. */
typedef value_type (*fun_type8)(value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with nine arguments. */
typedef value_type (*fun_type9)(value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with ten arguments. */
typedef value_type (*fun_type10)(value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions without arguments. */
typedef value_type (*bulkfun_type0)(int, int);
/** \brief Callback type used for functions with a single arguments. */
typedef value_type (*bulkfun_type1)(int, int, value_type);
/** \brief Callback type used for functions with two arguments. */
typedef value_type (*bulkfun_type2)(int, int, value_type, value_type);
/** \brief Callback type used for functions with three arguments. */
typedef value_type (*bulkfun_type3)(int, int, value_type, value_type, value_type);
/** \brief Callback type used for functions with four arguments. */
typedef value_type (*bulkfun_type4)(int, int, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with five arguments. */
typedef value_type (*bulkfun_type5)(int, int, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with six arguments. */
typedef value_type (*bulkfun_type6)(int, int, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with seven arguments. */
typedef value_type (*bulkfun_type7)(int, int, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with eight arguments. */
typedef value_type (*bulkfun_type8)(int, int, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with nine arguments. */
typedef value_type (*bulkfun_type9)(int, int, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with ten arguments. */
typedef value_type (*bulkfun_type10)(int, int, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type, value_type);
/** \brief Callback type used for functions with a variable argument list. */
typedef value_type (*multfun_type)(const value_type*, int);
/** \brief Callback type used for functions taking a string as an argument. */
typedef value_type (*strfun_type1)(const char_type*);
/** \brief Callback type used for functions taking a string and a value as arguments. */
typedef value_type (*strfun_type2)(const char_type*, value_type);
/** \brief Callback type used for functions taking a string and two values as arguments. */
typedef value_type (*strfun_type3)(const char_type*, value_type, value_type);
/** \brief Callback used for functions that identify values in a string. */
typedef int (*identfun_type)(const char_type *sExpr, int *nPos, value_type *fVal);
/** \brief Callback used for variable creation factory functions. */
typedef value_type* (*facfun_type)(const char_type*, void*);
} // end of namespace
#endif
| [
"dmvlas77@googlemail.com"
] | dmvlas77@googlemail.com |
1126ac9d458cd999ea6dcf580c55e5803385803a | 2c55f75c7b671eb4132818d2950b6439ff75464d | /程序设计实验/实验一/输入3组坐标,按指定格式输出.cpp | 846d7b4cfeb32cb73c73968fe7257b4799dac538 | [] | no_license | Monkeyman520/CPP | fb8fcbbcd55f51b3dd945aac180c614b884b1780 | a07df1456e52cbd44579e5e199cd209b3ae23a4c | refs/heads/master | 2020-09-27T12:06:29.300846 | 2018-09-16T03:26:09 | 2018-09-16T03:26:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 396 | cpp | //输入3组坐标,按指定格式输出
#include <iostream>
using namespace std;
int main()
{
char z;
int x1, x2, x3, y1, y2, y3;
cin >> z >> x1 >> z >> y1 >> z >> z >> z >> x2 >> z >> y2 >> z >> z >> z >> x3 >> z >> y3 >>z;
cout << '[' << x1 << ',' << y1 <<']' << endl;
cout << '[' << x2 << ',' << y2 <<']' << endl;
cout << '[' << x3 << ',' << y3 <<']' << endl;
return 0;
}
| [
"1637894214@qq.com"
] | 1637894214@qq.com |
46effb3436023cf959a0f5963ce426d612f7f0c5 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ArenaCamera.cpp | 48b047fa6f49144f1cdf706b0241410033d51e0e | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | #include "ArenaCamera.h"
ArenaCamera::ArenaCamera(Ogre::SceneNode *target1, Ogre::SceneNode *target2, Ogre::Camera *cam) {
mTarget1 = target1;
mTarget2 = target2;
mCamera = cam;
mMinDist = 0.0f;
}
ArenaCamera::~ArenaCamera() {
}
void ArenaCamera::setMinDistanceAway(float dist) {
mMinDist = dist;
}
void ArenaCamera::update() {
Ogre::Vector3 lookAt;
Ogre::Vector3 camPos(mCamera->getPosition());
float distance;
float idealDistance;
float fov = mCamera->getFOVy().valueRadians();
float xDist;
float otherAngle = 90 - fov;
lookAt = (mTarget1->getPosition() + mTarget2->getPosition()) * 0.5f;
xDist = fabs(mTarget1->getPosition().x - mTarget2->getPosition().x);
distance = camPos.z - lookAt.z;
idealDistance = 0.5f * xDist * Ogre::Math::Sin(otherAngle) / Ogre::Math::Sin(0.5f * fov);
if(idealDistance > mMinDist) {
camPos.z = idealDistance;
} else {
camPos.z = mMinDist;
}
mCamera->setPosition(camPos);
mCamera->lookAt(lookAt);
} | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e |
7609df037106a2d77844a03e8e0d6c2a8d6cc8fe | e0504349fceb190be0988b2f2532826b90fa3d16 | /rtos/ConditionVariable.h | dd091ec3d4ee30f2c52ad2c650fccd6c4114378e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CalSol/mbed | 741e84f2dd2343a2088c3a4b68ddc24088e871d9 | da4f23f00bdf450697c735f4b99b77ba04a93314 | refs/heads/master | 2021-06-07T15:27:24.357365 | 2019-06-24T02:06:22 | 2019-06-24T02:06:22 | 31,633,506 | 1 | 2 | Apache-2.0 | 2019-12-05T01:38:21 | 2015-03-04T02:24:28 | C | UTF-8 | C++ | false | false | 6,598 | h | /* mbed Microcontroller Library
* Copyright (c) 2017-2017 ARM Limited
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CONDITIONVARIABLE_H
#define CONDITIONVARIABLE_H
#include <stdint.h>
#include "cmsis_os.h"
#include "rtos/Mutex.h"
#include "rtos/Semaphore.h"
#include "platform/NonCopyable.h"
namespace rtos {
/** \addtogroup rtos */
/** @{*/
struct Waiter;
/** This class provides a safe way to wait for or send notifications of condition changes
*
* This class is used in conjunction with a mutex to safely wait for or
* notify waiters of condition changes to a resource accessible by multiple
* threads.
*
* # Defined behavior
* - All threads waiting on the condition variable wake when
* ConditionVariable::notify_all is called.
* - If one or more threads are waiting on the condition variable at least
* one of them wakes when ConditionVariable::notify is called.
*
* # Undefined behavior
* - The thread which is unblocked on ConditionVariable::notify_one is
* undefined if there are multiple waiters.
* - The order which in which waiting threads acquire the condition variable's
* mutex after ConditionVariable::notify_all is called is undefined.
* - When ConditionVariable::notify_one or ConditionVariable::notify_all is
* called and there are one or more waiters and one or more threads attempting
* to acquire the condition variable's mutex the order in which the mutex is
* acquired is undefined.
* - The behavior of ConditionVariable::wait and ConditionVariable::wait_for
* is undefined if the condition variable's mutex is locked more than once by
* the calling thread.
* - Spurious notifications (not triggered by the application) can occur
* and it is not defined when these occur.
*
* @note Synchronization level: Thread safe
*
* Example:
* @code
* #include "mbed.h"
*
* Mutex mutex;
* ConditionVariable cond(mutex);
*
* // These variables are protected by locking mutex
* uint32_t count = 0;
* bool done = false;
*
* void worker_thread()
* {
* mutex.lock();
* do {
* printf("Worker: Count %lu\r\n", count);
*
* // Wait for a condition to change
* cond.wait();
*
* } while (!done);
* printf("Worker: Exiting\r\n");
* mutex.unlock();
* }
*
* int main() {
* Thread thread;
* thread.start(worker_thread);
*
* for (int i = 0; i < 5; i++) {
*
* mutex.lock();
* // Change count and notify waiters of this
* count++;
* printf("Main: Set count to %lu\r\n", count);
* cond.notify_all();
* mutex.unlock();
*
* wait(1.0);
* }
*
* mutex.lock();
* // Change done and notify waiters of this
* done = true;
* printf("Main: Set done\r\n");
* cond.notify_all();
* mutex.unlock();
*
* thread.join();
* }
* @endcode
*/
class ConditionVariable : private mbed::NonCopyable<ConditionVariable> {
public:
/** Create and Initialize a ConditionVariable object */
ConditionVariable(Mutex &mutex);
/** Wait for a notification
*
* Wait until a notification occurs.
*
* @note - The thread calling this function must be the owner of the
* ConditionVariable's mutex and it must be locked exactly once
* @note - Spurious notifications can occur so the caller of this API
* should check to make sure the condition they are waiting on has
* been met
*
* Example:
* @code
* mutex.lock();
* while (!condition_met) {
* cond.wait();
* }
*
* function_to_handle_condition();
*
* mutex.unlock();
* @endcode
*/
void wait();
/** Wait for a notification or timeout
*
* @param millisec timeout value or osWaitForever in case of no time-out.
* @return true if a timeout occurred, false otherwise.
*
* @note - The thread calling this function must be the owner of the
* ConditionVariable's mutex and it must be locked exactly once
* @note - Spurious notifications can occur so the caller of this API
* should check to make sure the condition they are waiting on has
* been met
*
* Example:
* @code
* mutex.lock();
* Timer timer;
* timer.start();
*
* bool timed_out = false;
* uint32_t time_left = TIMEOUT;
* while (!condition_met && !timed_out) {
* timed_out = cond.wait_for(time_left);
* uint32_t elapsed = timer.read_ms();
* time_left = elapsed > TIMEOUT ? 0 : TIMEOUT - elapsed;
* }
*
* if (condition_met) {
* function_to_handle_condition();
* }
*
* mutex.unlock();
* @endcode
*/
bool wait_for(uint32_t millisec);
/** Notify one waiter on this condition variable that a condition changed.
*
* @note - The thread calling this function must be the owner of the ConditionVariable's mutex
*/
void notify_one();
/** Notify all waiters on this condition variable that a condition changed.
*
* @note - The thread calling this function must be the owner of the ConditionVariable's mutex
*/
void notify_all();
~ConditionVariable();
protected:
struct Waiter {
Waiter();
Semaphore sem;
Waiter *prev;
Waiter *next;
bool in_list;
};
static void _add_wait_list(Waiter **wait_list, Waiter *waiter);
static void _remove_wait_list(Waiter **wait_list, Waiter *waiter);
Mutex &_mutex;
Waiter *_wait_list;
};
}
#endif
/** @}*/
| [
"russ.butler@arm.com"
] | russ.butler@arm.com |
589c1434061776b85d65f578be882d96ecf7ddcb | 40587fed2ea28867795686fe5445ed9e57ef4af8 | /src/utils/solvers/Linear.tcc | afe746b98c9332bb3f82420fc85710166176599a | [] | no_license | JamesZFS/Pharosa | b1a6e84647a40bb0954a08014e027bb1f77d5d2c | c6d550789335b3c33d2c7affc7e776d3e737fdb6 | refs/heads/master | 2020-05-09T18:30:53.371797 | 2020-04-18T07:01:20 | 2020-04-18T07:01:20 | 181,339,719 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,087 | tcc | //
// Created by James on 2019/4/2.
//
// Linear solvers solver
// Solve2D A b == x (n_dim == n, A: matrix)
template<int n>
bool Linear::Solve(real (&A)[n][n], real (&b)[n], real (&x)[n])
{
real M[n][n + 1]; // expand to (n+1) cols
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
M[i][j] = A[i][j];
}
M[i][n] = b[i];
}
for (int k = 0; k < n; ++k) { // n principle component
real col_max = fabsf(M[k][k]), fm;
int maxi = k;
for (int i = k + 1; i < n; ++i) { // find the max in k-th col
if ((fm = fabsf(M[i][k])) > col_max) {
col_max = fm;
maxi = i;
}
}
if (col_max < EPS) { // singular matrix
return false; // solving failed
}
// swap k-th and maxi-th row
for (int j = k; j < n + 1; ++j) {
std::swap(M[k][j], M[maxi][j]);
}
// perform reduction
for (int i = k + 1; i < n; ++i) {
real r = -M[i][k] / M[k][k];
for (int j = k + 1; j < n + 1; ++j) {
M[i][j] += r * M[k][j];
}
}
}
// regressive solving
for (int k = n - 1; k >= 0; --k) {
for (int i = 0; i < k; ++i) {
M[i][n] += -M[i][k] / M[k][k] * M[k][n];
}
x[k] = M[k][n] / M[k][k];
}
return true; // solving success
}
// Solve2D A b == x (n_dim == n, A: matrix) for debuging use
template<int n>
bool Linear::SolveDebug(real (&A)[n][n], real (&b)[n], real (&x)[n])
{
real M[n][n + 1]; // expand to (n+1) cols
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
M[i][j] = A[i][j];
}
M[i][n] = b[i];
}
printf("before reduction:\n");
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n + 1; ++j) {
printf("%.2f ", M[i][j]);
}
printf("\n");
}
printf("\n");
for (int k = 0; k < n; ++k) { // n principle component
real col_max = fabsf(M[k][k]), fm;
int maxi = k;
for (int i = k + 1; i < n; ++i) { // find the max in k-th col
if ((fm = fabsf(M[i][k])) > col_max) {
col_max = fm;
maxi = i;
}
}
if (col_max < EPS) { // singular matrix
return false; // solving failed
}
// swap k-th and maxi-th row
for (int j = k; j < n + 1; ++j) {
std::swap(M[k][j], M[maxi][j]);
}
// perform reduction
for (int i = k + 1; i < n; ++i) {
real r = -M[i][k] / M[k][k];
M[i][k] = 0;
for (int j = k + 1; j < n + 1; ++j) {
M[i][j] += r * M[k][j];
}
}
}
printf("after reduction:\n");
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n + 1; ++j) {
printf("%.2f ", M[i][j]);
}
printf("\n");
}
printf("\n");
// regressive solving
for (int k = n - 1; k >= 0; --k) {
for (int i = 0; i < k; ++i) {
M[i][n] += -M[i][k] / M[k][k] * M[k][n];
M[i][k] = 0;
}
M[k][n] /= M[k][k];
M[k][k] = 1;
x[k] = M[k][n];
}
printf("after solving:\n");
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n + 1; ++j) {
printf("%.2f ", M[i][j]);
}
printf("\n");
}
printf("\n");
return true; // solving success
}
// M: expanded Matrix (n x n+1)
template<int n>
bool Linear::SolveInPlace(real (&M)[n][n + 1])
{
for (int k = 0; k < n; ++k) { // n principle component
real col_max = fabsf(M[k][k]), fm;
int maxi = k;
for (int i = k + 1; i < n; ++i) { // find the max in k-th col
if ((fm = fabsf(M[i][k])) > col_max) {
col_max = fm;
maxi = i;
}
}
if (col_max < EPS) { // singular matrix
return false; // solving failed
}
// swap k-th and maxi-th row
for (int j = k; j < n + 1; ++j) {
std::swap(M[k][j], M[maxi][j]);
}
// perform reduction
for (int i = k + 1; i < n; ++i) {
real r = -M[i][k] / M[k][k];
for (int j = k + 1; j < n + 1; ++j) {
M[i][j] += r * M[k][j];
}
}
}
// regressive solving
for (int k = n - 1; k >= 0; --k) {
for (int i = 0; i < k; ++i) {
M[i][n] += -M[i][k] / M[k][k] * M[k][n];
}
M[k][n] /= M[k][k];
}
return true;
}
bool Linear::Solve2D(real A00, real A01, real A10, real A11, real b0, real b1, real &x0, real &x1)
{
real det = A00 * A11 - A01 * A10;
if (fabsf(det) < EPS) return false; // singular
x0 = (A11 * b0 - A01 * b1) / det;
x1 = (A00 * b1 - A10 * b0) / det;
return true;
}
| [
"962907278@qq.com"
] | 962907278@qq.com |
a0ef254c0cc50088befe4daa5a4a78bc5f018a25 | ff6c94371e939656c2beb21307630446e3b8ccf7 | /CaseGenerator.cpp | 833d3449d028f38ae156d989573eaa52cc5ffaf3 | [] | no_license | competitiveprogramming/Sadia_apu_code_library_DS_and_algorithm | 32217fb3ecdfbc2c1992f5bb07dcf708c2299f8c | 0b9347bc9542ba24432bb9ebee20934c4f3457cf | refs/heads/master | 2021-10-18T22:11:06.243725 | 2019-02-14T18:40:11 | 2019-02-14T18:40:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | #include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<set>
#include<map>
#include<utility>
#include<vector>
#include<string>
#include<stack>
#include<queue>
using namespace std;
int main()
{
freopen("data.txt", "w", stdout);
srand(time(NULL));
int T = rand()%50 + 1;
int R,C,K,r,c,n;
printf("%d\n", T);
while(T--)
{
R = rand()%200 + 1, C = rand()%200 + 1; K = rand()%112500+1;
printf("%d %d %d\n", R,C,K);
for (r=1; r<=R; ++r)
{
for (c=1; c<=C; ++c)
{
n = rand()%20 + 1;
printf("%d ", n);
}
puts("");
}
}
return 0;
}
| [
"s.i.r.computerengineer24@gmail.com"
] | s.i.r.computerengineer24@gmail.com |
60e8e8c09ee24609eb359bd8fb72be63c15f09b0 | f91ad86483e866f8ce7e2fdc962153fd303dda68 | /Source/Game/Game_Accessor.h | 792b009c8547c3120fc91db5ae68666fb00599c6 | [] | no_license | VictorPetersson3/Spelprojekt3_Shmup | 4a3a01ea7df40e089778e448cac0ea56fc32df7c | 51ec519ca16861438c843eb9d6f6abfd321f0e21 | refs/heads/main | 2023-03-07T11:36:37.506543 | 2021-02-28T15:43:28 | 2021-02-28T15:43:28 | 326,771,200 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 452 | h | #pragma once
#include "Game.h"
class CGame;
namespace Studio
{
class GameAccessor
{
public:
static GameAccessor& GetInstance();
private:
GameAccessor() = default;
static GameAccessor ourInstance;
CGame* myGame;
public:
GameAccessor(GameAccessor const&) = delete;
void operator=(GameAccessor const&) = delete;
CGame* GetGame();
void SetGame(CGame* aGame);
};
} | [
"victor.petersson@studerande.thegameassembly.se"
] | victor.petersson@studerande.thegameassembly.se |
72c70e3daabfeae53aef611896d670b66cbdfb7b | 74af5be7e79b5fe789e90c6f64ebbdbe2cf7543d | /SimpleDriver.cpp | 7992a291e702435832932caefce80b66bcd7a473 | [] | no_license | bartek1912/torcs_bot_uwr | ff472d750047fb0491266ef45d1c1e71ac7e6593 | aac21d095182ba3e59bafe80602afd28b882ef41 | refs/heads/master | 2021-01-11T21:55:54.575265 | 2017-01-05T21:07:18 | 2017-01-05T21:07:18 | 78,879,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,647 | cpp | /***************************************************************************
file : SimpleDriver.cpp
copyright : (C) 2007 Daniele Loiacono
***************************************************************************/
/***************************************************************************
* *
* 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "SimpleDriver.h"
const double mnoznik_kier = 8.5711/2;
CarControl SimpleDriver::wDrive(CarState cs)
{
double dir;
int id_mx = TRACK_SENSORS_NUM/2;
for(int i = 0; i < TRACK_SENSORS_NUM; i++)
if(cs.getTrack(i) > cs.getTrack(id_mx))
id_mx = i;
dir = -(id_mx - TRACK_SENSORS_NUM/2)/static_cast<double>(TRACK_SENSORS_NUM) * mnoznik_kier;
double acc = 1, br = 0;
//100 - 30
//200 - 60
//300 - 270
if((cs.getTrack(id_mx) < 150 && cs.getTotalSpeed() > 260)
|| (cs.getTrack(id_mx) < 100 && cs.getTotalSpeed() > 220)
|| (cs.getTrack(id_mx) < 60 && cs.getTotalSpeed() > 150)
|| (cs.getTrack(id_mx) < 50 && cs.getTotalSpeed() > 120)
|| (cs.getTrack(id_mx) < 40 && cs.getTotalSpeed() > 100)
|| (cs.getTrack(id_mx) < 30 && cs.getTotalSpeed() > 85)
|| (cs.getTrack(id_mx) < 20 && cs.getTotalSpeed() > 70))
{
br = 1;
acc = 0;
}
filterABS(cs, br);
return CarControl(acc, br, cs.getGear(), dir, 0.00);
}
float SimpleDriver::filterABS(CarState &cs,float brake) const
{
float speed = cs.getSpeedX() / 3.6;
if (speed < absMinSpeed)
return brake;
float slip = 0.0f;
for (int i = 0; i < 4; i++){
slip += cs.getWheelSpinVel(i) * wheelRadius[i];}
slip = speed - slip/4.0f;
if (slip > absSlip){
brake = brake - (slip - absSlip)/absRange; }
if (brake<0)
return 0;
else
return brake;
}
void
SimpleDriver::onShutdown()
{
// cout << "Bye bye!" << endl;
}
void
SimpleDriver::onRestart()
{
}
/* ABS Filter Constants */
const float SimpleDriver::wheelRadius[4]={0.3179,0.3179,0.3276,0.3276};
const float SimpleDriver::absSlip=2.0;
const float SimpleDriver::absRange=3.0;
const float SimpleDriver::absMinSpeed=3.0; | [
"bnajdecki@gmail.com"
] | bnajdecki@gmail.com |
eac8cef4f41242e89e0d61bd5333fbb42b4b293e | 673cac8e6d3594c6f8f60c4a5be7c843f97c4f38 | /Assistente virtual/04 - Assitente Virtual com Python II/Aula extra com Arduino/CodigoMorseFuncao/CodigoMorseFuncao.ino | df1c06697dfb9406c3073a4d5d36b4daa299fb6b | [
"MIT"
] | permissive | Ivoneideduarte/assistente-virtual-com-python | eb5e924487291f6d5077a92e0500fadaca4b7679 | 7c7e39be5bcdc811a2694d757fd5d0c3817fb55c | refs/heads/master | 2022-11-24T12:41:09.592871 | 2020-08-03T22:12:37 | 2020-08-03T22:12:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | ino | //byte led = 10;
int y = 0;
void setup()
{
pinMode(10, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop()
{
piscaLed(150, 100, 10, 3); //Argumentos
Serial.println("Escrevendo S.");
piscaLed(400, 100, 10, 3);
Serial.println("0.");
piscaLed(150, 100, 10, 3);
Serial.println("S");
Serial.println("Enviado S.O.S "+String(y)+" vez."); //Concatenando variáveis
/*piscaLed(150, 100, 13, 10);
Serial.println("Escrevendo S.");
piscaLed(400, 100, 13, 10);
Serial.println("0.");
piscaLed(150, 100, 13, 10);
Serial.println("S");
Serial.println("Enviado S.O.S");*/
}
//Void é uma função vazia, não retorna nada
int piscaLed(int tempLig, int tempDesl, byte porta, int qtd) //Argumentos
{
for (int x = 0; x < qtd; x++)
{
digitalWrite(porta, HIGH);
delay(tempLig);
digitalWrite(porta, LOW);
delay(tempDesl);
}
y++;
return y; //Retorna o valor do incremento do y
}
| [
"contato.ivoneideduarte@gmail.com"
] | contato.ivoneideduarte@gmail.com |
a21c81cad764d1eaebaf3ff923a13b6f2b740f58 | 1b17cb868c571920dadeeab0295d60783a496fc8 | /HealthMods/SensorsMod/AurigaHL7/2.4/datatype/PIP.h | 5629ba5a3f4888f45a97c38697b8426050882fce | [] | no_license | afmartins85/olamed-modules-src | dc86e2dce4d5c54a450bca95c4775715167cecb9 | ec673ef154ef218f3b7c6593914212b125600ebd | refs/heads/master | 2023-01-07T16:25:29.437031 | 2020-11-05T22:30:07 | 2020-11-05T22:30:07 | 287,022,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,643 | h | /*
* This file is part of Auriga HL7 library.
*
* Auriga HL7 library 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.
*
* Auriga HL7 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Auriga HL7 library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __PIP_v24_H__
#define __PIP_v24_H__
#include "../../common/Util.h"
#include "../datatype/CE.h"
#include "../datatype/DT.h"
#include "../datatype/EI.h"
namespace HL7_24 {
/* Privileges */
class PIP : public HL7Data {
public:
PIP() { this->init(); }
private:
/* Field ID */
enum FIELD_ID {
PIP_1, /* privilege */
PIP_2, /* privilege class */
PIP_3, /* expiration date */
PIP_4, /* activation date */
PIP_5, /* facility (EI) */
FIELD_ID_MAX
};
public:
const char *className() const { return "PIP"; }
PIP *create() const { return new PIP(); }
private:
void init() {
// setName("PIP");
/* Init members */
addObject<CE>(PIP_1, "PIP.1", HL7::initialized, HL7::repetition_off);
addObject<CE>(PIP_2, "PIP.2", HL7::initialized, HL7::repetition_off);
addObject<DT>(PIP_3, "PIP.3", HL7::initialized, HL7::repetition_off);
addObject<DT>(PIP_4, "PIP.4", HL7::initialized, HL7::repetition_off);
addObject<EI>(PIP_5, "PIP.5", HL7::initialized, HL7::repetition_off);
}
public:
/* Getters */
/****************************************
* privilege
*/
CE *getPIP_1(size_t index = 0) {
return (CE *)this->getObjectSafe(index, PIP_1);
}
CE *getPrivilege(size_t index = 0) {
return (CE *)this->getObjectSafe(index, PIP_1);
}
bool isPIP_1(size_t index = 0) {
try {
return this->getObject(index, PIP_1) != NULL;
} catch (...) {
}
return false;
}
bool isPrivilege(size_t index = 0) {
try {
return this->getObject(index, PIP_1) != NULL;
} catch (...) {
}
return false;
}
/****************************************
* privilege class
*/
CE *getPIP_2(size_t index = 0) {
return (CE *)this->getObjectSafe(index, PIP_2);
}
CE *getPrivilegeClass(size_t index = 0) {
return (CE *)this->getObjectSafe(index, PIP_2);
}
bool isPIP_2(size_t index = 0) {
try {
return this->getObject(index, PIP_2) != NULL;
} catch (...) {
}
return false;
}
bool isPrivilegeClass(size_t index = 0) {
try {
return this->getObject(index, PIP_2) != NULL;
} catch (...) {
}
return false;
}
/****************************************
* expiration date
*/
DT *getPIP_3(size_t index = 0) {
return (DT *)this->getObjectSafe(index, PIP_3);
}
DT *getExpirationDate(size_t index = 0) {
return (DT *)this->getObjectSafe(index, PIP_3);
}
bool isPIP_3(size_t index = 0) {
try {
return this->getObject(index, PIP_3) != NULL;
} catch (...) {
}
return false;
}
bool isExpirationDate(size_t index = 0) {
try {
return this->getObject(index, PIP_3) != NULL;
} catch (...) {
}
return false;
}
/****************************************
* activation date
*/
DT *getPIP_4(size_t index = 0) {
return (DT *)this->getObjectSafe(index, PIP_4);
}
DT *getActivationDate(size_t index = 0) {
return (DT *)this->getObjectSafe(index, PIP_4);
}
bool isPIP_4(size_t index = 0) {
try {
return this->getObject(index, PIP_4) != NULL;
} catch (...) {
}
return false;
}
bool isActivationDate(size_t index = 0) {
try {
return this->getObject(index, PIP_4) != NULL;
} catch (...) {
}
return false;
}
/****************************************
* facility (EI)
*/
EI *getPIP_5(size_t index = 0) {
return (EI *)this->getObjectSafe(index, PIP_5);
}
EI *getFacility(size_t index = 0) {
return (EI *)this->getObjectSafe(index, PIP_5);
}
bool isPIP_5(size_t index = 0) {
try {
return this->getObject(index, PIP_5) != NULL;
} catch (...) {
}
return false;
}
bool isFacility(size_t index = 0) {
try {
return this->getObject(index, PIP_5) != NULL;
} catch (...) {
}
return false;
}
}; /* End PIP */
} /* End HL7_24 */
#endif /*__PIP_v24_H__ */
| [
"anderson.fagundes@gmail.com"
] | anderson.fagundes@gmail.com |
90e14f9d004453124383df7afe4f818387c6c68a | 8f514ed747ffd1f62919074d3091d4028e0cd349 | /wkb.cpp | 754409bd01b08d069409fbf626fc98cf0160e0cc | [] | no_license | darkserj/wkb_wrapper | e0e8d5f1adb0ecee5ff113780a011a7a655ad0f0 | 76c6d904b08e67a29664d0d2ecf2e1b2de67f788 | refs/heads/master | 2020-04-04T19:12:42.811426 | 2013-02-04T15:12:49 | 2013-02-04T15:12:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,119 | cpp | //
// wkb.cpp
//
#include "wkb.h"
void ml::make_wkb_point(std::vector<char> &wkb, ml::point_d const &pt) {
wkb.resize(21);
wkb[0] = 1;
*((unsigned int *)&wkb[1]) = 1; // wkb_point
*((double *)&wkb[5]) = pt.x;
*((double *)&wkb[13]) = pt.y;
}
ml::rect_d ml::wkb::bounds() const {
struct bounds_counter {
ml::rect_d r;
bounds_counter() : r(ml::rect_d::void_rect()) {}
void operator()(ml::point_d const *begin, ml::point_d const *end) {
r.bounds(begin,end);
}
ml::rect_d bounds() const {
return r;
}
};
bounds_counter b;
return apply(b).bounds();
}
std::string ml::wkb::to_geo_json() const {
struct point_formatter {
std::stringstream &ss;
unsigned int counter;
bool parts;
point_formatter(std::stringstream &s) : ss(s),counter(0), parts(false) {}
void operator() (ml::point_d const *begin, ml::point_d const *end) {
if (parts) ss << (counter ? ",[" : "[");
ss << "[" << begin->x << "," << begin->y << "]";
for(++begin;begin != end;++begin){
ss << ",[" << begin->x << "," << begin->y << "]";
}
if (parts) ss << "]";
++counter;
}
point_formatter & make_parts(bool p) {parts = p; counter = 0; return *this;}
};
std::stringstream ss;
point_formatter fmt(ss);
ss << std::fixed << std::showpoint << std::setprecision(6);
ss << "{";
switch(type()) {
case wkb_point: {
ss << "\"type\":\"Point\",\"coordinates\":";
apply(fmt);
} break;
case wkb_line_string: {
ss << "\"type\":\"LineString\",\"coordinates\": [";
apply(fmt);
ss << "]";
} break;
case wkb_multi_line_string: {
ss << "\"type\":\"MultiLineString\",\"coordinates\": [";
apply(fmt.make_parts(true));
ss << "]";
} break;
case wkb_polygon: {
ss << "\"type\":\"Polygon\",\"coordinates\": [";
apply(fmt.make_parts(true));
ss << "]";
} break;
case wkb_multi_polygon: {
ss << "\"type\":\"MultiPolygon\",\"coordinates\": [";
for(size_t i=0; i < size(); ++i) {
ss << (i ? ",[" : "[");
polygon(i).apply(fmt.make_parts(true));
ss << "]";
}
ss << "]";
} break;
default: break;
}
ss << "}";
return ss.str();
}
| [
"yershov@corp.mail.ru"
] | yershov@corp.mail.ru |
e798cb21eee4cac59f058fdaf83824bd00147cb1 | cd33de81cbe9f94e9f32bd46f184cdd4ce8b81a1 | /DecathectEngine/src/dcthctpch.h | 3ad27d251f85e1515d2ae733fc939c3b854a39f2 | [
"Apache-2.0"
] | permissive | jharvs97/DecathectEngine | 713133c66b66bb95845a15c09b632c43516c34f2 | b6e6e840843d0de5ebd8a38194a01e53fdd19e03 | refs/heads/master | 2022-03-31T14:25:30.663747 | 2019-11-21T03:07:30 | 2019-11-21T03:07:30 | 219,495,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | #pragma once
#include <iostream>
#include <memory>
#include <utility>
#include <algorithm>
#include <functional>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#ifdef DCTHCT_PLATFORM WINDOWS
#include <Windows.h>
#endif | [
"34911082+jharvs97@users.noreply.github.com"
] | 34911082+jharvs97@users.noreply.github.com |
b788e1003bf2749b3ec34a1259e324dcb635c1d3 | 397403cb1e7fc66e2a849859a9c66ac915b3f9d6 | /Plugins/OSSShading/Intermediate/Build/Win64/UE4Editor/Inc/OSSShading/MaterialExpressionOSSMad.generated.h | 8ab023267696c8eba93538fef911ea5ac7fbaf6f | [] | no_license | seanssoh/HenryAlone | cdc0fb62bbc49f965ab255a5add598dd44501ebb | 3555bbac6823749338682c280161db99fd1e6080 | refs/heads/master | 2021-01-11T03:12:30.710772 | 2016-10-17T16:51:59 | 2016-10-17T16:51:59 | 71,038,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,713 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
C++ class header boilerplate exported from UnrealHeaderTool.
This is automatically generated by the tools.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "ObjectBase.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef OSSSHADING_MaterialExpressionOSSMad_generated_h
#error "MaterialExpressionOSSMad.generated.h already included, missing '#pragma once' in MaterialExpressionOSSMad.h"
#endif
#define OSSSHADING_MaterialExpressionOSSMad_generated_h
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_RPC_WRAPPERS
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUMaterialExpressionOSSMad(); \
friend OSSSHADING_API class UClass* Z_Construct_UClass_UMaterialExpressionOSSMad(); \
public: \
DECLARE_CLASS(UMaterialExpressionOSSMad, UMaterialExpression, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/OSSShading"), NO_API) \
DECLARE_SERIALIZER(UMaterialExpressionOSSMad) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_INCLASS \
private: \
static void StaticRegisterNativesUMaterialExpressionOSSMad(); \
friend OSSSHADING_API class UClass* Z_Construct_UClass_UMaterialExpressionOSSMad(); \
public: \
DECLARE_CLASS(UMaterialExpressionOSSMad, UMaterialExpression, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/OSSShading"), NO_API) \
DECLARE_SERIALIZER(UMaterialExpressionOSSMad) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UMaterialExpressionOSSMad(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UMaterialExpressionOSSMad) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UMaterialExpressionOSSMad); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UMaterialExpressionOSSMad); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UMaterialExpressionOSSMad(UMaterialExpressionOSSMad&&); \
NO_API UMaterialExpressionOSSMad(const UMaterialExpressionOSSMad&); \
public:
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UMaterialExpressionOSSMad(UMaterialExpressionOSSMad&&); \
NO_API UMaterialExpressionOSSMad(const UMaterialExpressionOSSMad&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UMaterialExpressionOSSMad); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UMaterialExpressionOSSMad); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UMaterialExpressionOSSMad)
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_12_PROLOG
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_RPC_WRAPPERS \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_INCLASS \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_INCLASS_NO_PURE_DECLS \
HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID HenryAlone_Plugins_OSSShading_Source_OSSShading_Public_MaterialExpressionOSSMad_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"seanssoh@gmail.com"
] | seanssoh@gmail.com |
cbd3c900068b4bbc2ccdc006afff00ec5d3b2551 | 896a24277984903b4edb89def90d959945eb7ea2 | /examples/Linalg/Linalg3/include/linalg3/Analysis.h | 813fc37b73e020287347dd14207a03303ede3da0 | [
"Apache-2.0"
] | permissive | leonid3000/mlir | 70af93154d76a012ba17b8d79213089864c54e8a | 8c7180e2c37985945c178a8337e8728a605842c3 | refs/heads/master | 2020-07-24T10:24:05.550955 | 2019-09-11T17:18:01 | 2019-09-11T17:18:29 | 207,893,124 | 1 | 0 | Apache-2.0 | 2019-09-11T19:42:35 | 2019-09-11T19:42:33 | null | UTF-8 | C++ | false | false | 1,272 | h | //===- Analysis.h - Linalg dialect Analysis function definitions ----------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#ifndef LINALG3_ANALYSIS_H_
#define LINALG3_ANALYSIS_H_
#include "linalg2/Analysis.h"
namespace mlir {
class AffineMap;
} // namespace mlir
namespace linalg {
/// Given a `map` specification and a subset of its results
/// `[beginResult, endResult)`, returns the inverse map that maps result
/// positions to dim positions.
mlir::AffineMap inverseSubMap(mlir::AffineMap map, unsigned beginResult = 0,
unsigned endResult = 0);
} // namespace linalg
#endif // LINALG3_ANALYSIS_H_
| [
"joker.eph@gmail.com"
] | joker.eph@gmail.com |
de68b5976f403f24076b29c8a1e0600a2c3411d6 | 5012f1a7f9d746c117f04ff56f7ebe6d5fc9128f | /1.Server/2.Midware/KFContrib/KFPlugin/KFInterface.h | b92f4397c236b859145d849755ef30b9fa3f2724 | [
"Apache-2.0"
] | permissive | hw233/KFrame | c9badd576ab7c75f4e5aea2cfb3b20f6f102177f | a7e300c301225d0ba3241abcf81e871d8932f326 | refs/heads/master | 2023-05-11T07:50:30.349114 | 2019-01-25T08:20:11 | 2019-01-25T08:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | h | #ifndef __KF_INTERFACE_H__
#define __KF_INTERFACE_H__
#include "KFInclude.h"
namespace KFrame
{
class KFPluginManage;
class KFInterface
{
public:
KFInterface()
{
_kf_plugin_manage = nullptr;
}
virtual ~KFInterface() {};
// 释放
virtual void Release() {};
// 初始化
virtual void InitModule() = 0;
// 加载配置
virtual void LoadConfig() = 0;
virtual void AfterLoad() = 0;
// 开始初始化
virtual void BeforeRun() = 0;
// 执行一次
virtual void OnceRun() = 0;
// 关闭
virtual void BeforeShut() = 0;
virtual void ShutDown() = 0;
virtual void AfterShut() = 0;
public:
// 类名字
std::string _class_name;
// 插件名字
std::string _plugin_name;
// 插件管理
KFPluginManage* _kf_plugin_manage;
};
}
#endif | [
"lori227@qq.com"
] | lori227@qq.com |
603de64f7c84de637fdaea7a4b3ed83397cf9c63 | 8d15c78f8badb266818cdf67368249148cea46f0 | /AngryBirds/OpenGL/Sprite.h | 4f7f76a07d2a1fc23f9ee1bf77035017bbde6191 | [] | no_license | James81919/AngryBirds | 6470670608f4f0cbc8b7e37811f1fdd70ba2a474 | e5b0c343023da6d9e0ecf3f2e1575089d501c1a0 | refs/heads/master | 2020-03-28T20:24:45.820643 | 2018-09-25T05:08:28 | 2018-09-25T05:08:28 | 148,976,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 972 | h | #ifndef __SPRITE_H__
#define __SPRITE_H__
#include "ShaderLoader.h"
#include "Utilities.h"
class CSprite
{
public:
CSprite();
CSprite(std::string _filepath, GLuint& _shader);
~CSprite();
virtual void Init();
virtual void Update(glm::mat4 _model, glm::mat4 _view, glm::mat4 _projection, glm::vec3 _cameraPos);
virtual void Render();
void SetSprite(std::string _sFilePath);
protected:
std::string
m_sFilePath;
GLuint
m_vbo,
m_vao,
m_ebo,
m_tex,
m_index,
m_shader;
glm::mat4
m_model,
m_view,
m_projection,
m_mvp;
glm::vec3
m_cameraPos;
GLfloat m_vertices[32] = {
// Position // Colour // Tex Coords
-1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f
};
GLuint m_indices[6] = {
0, 1, 2, // First Triangle
0, 2, 3 // Second Triangle
};
};
#endif // !__SPRITE_H__
| [
"jjohnstone2520@gmail.com"
] | jjohnstone2520@gmail.com |
75085833ea1367286331e46ce31d4ed9aadf6283 | 7c63a96fad4257f4959ffeba0868059fc96566fb | /cpp/std-17/m_bancila-modern_cpp_programming_cookbook/ch_01-core_lang/01-auto_keyword.cpp | c9142e5e8e3625db574d09a10e14b37ffdfc860f | [
"MIT"
] | permissive | ordinary-developer/education | b426148f5690f48e0ed4853adfc3740bd038b72c | 526e5cf86f90eab68063bb7c75744226f2c54b8d | refs/heads/master | 2023-08-31T14:42:37.237690 | 2023-08-30T18:15:18 | 2023-08-30T18:15:18 | 91,232,306 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,087 | cpp | // region [how to do it]
#include <iostream>
#include <typeinfo>
#include <cassert>
#include <initializer_list>
namespace example_01 {
void run() {
static_assert(true);
auto i = 42;
auto d = 42.5;
auto s = "text";
auto v = {1, 2, 3};
int i2 = 42;
double d2 = 42.5;
char const* s2 = "text";
std::initializer_list<int> v2 = {1, 2, 3};
assert(typeid(i) == typeid(i2));
assert(typeid(d) == typeid(d2));
assert(typeid(s) == typeid(s2));
assert(typeid(v) == typeid(v2));
std::cout << "typeid(i): " << typeid(i).name() << std::endl;
std::cout << "typeif(d): " << typeid(d).name() << std::endl;
std::cout << "typeif(s): " << typeid(s).name() << std::endl;
std::cout << "typeif(v): " << typeid(v).name() << std::endl;
}
}
#include <cassert>
#include <typeinfo>
#include <string>
#include <vector>
#include <memory>
#include <iostream>
namespace example_02 {
void run() {
auto b = new char[10]{ 0 };
auto s = std::string{ "text" };
auto v = std::vector<int>{ 1, 2, 3 };
auto p = std::make_shared<int>(42);
char* b2 = new char[10]{ 0 };
std::string s2 = std::string{ "text" };
std::vector<int> v2 = std::vector<int>{ 1, 2, 3 };
std::shared_ptr<int> p2 = std::make_shared<int>(42);
assert(typeid(b) == typeid(b2));
assert(typeid(s) == typeid(s2));
assert(typeid(v) == typeid(v2));
assert(typeid(p) == typeid(p2));
std::cout << "typeid(b): " << typeid(b).name() << std::endl;
std::cout << "typeid(s): " << typeid(s).name() << std::endl;
std::cout << "typeid(v): " << typeid(v).name() << std::endl;
std::cout << "typeid(p): " << typeid(p).name() << std::endl;
delete b;
b = nullptr;
delete b2;
b2 = nullptr;
}
}
#include <iostream>
#include <typeinfo>
#include <cctype>
#include <functional>
namespace example_03 {
void run() {
auto upper = [](char const c) { return toupper(c); };
std::function<int(char const)> upper2 =
[](char const c) { return toupper(c); };
std::cout << "typeid(upper): " << typeid(upper).name() << std::endl;
std::cout << "typeid(upper2): " << typeid(upper2).name() << std::endl;
}
}
#include <iostream>
#include <typeinfo>
#include <functional>
namespace example_04 {
void run() {
auto add = [](auto const a, auto const b) { return a + b; };
std::cout << "typeid(add): " << typeid(add).name() << std::endl;
}
}
namespace example_05 {
template <typename F, typename T>
auto apply(F&& f, T value) {
return f(value);
}
void run() {
}
}
// endregion [how to do it]
// region [how it works]
#include <vector>
#include <cstddef>
#include <typeinfo>
#include <cassert>
namespace example_06 {
void run() {
auto v = std::vector<int>{ 1, 2, 3 };
int size1 = v.size();
auto size2 = v.size();
auto size3 = int{ v.size() }; // here an warning will be
std::cout << "typeid(size1): " << typeid(size1).name() << std::endl;
std::cout << "typeid(size2): " << typeid(size2).name() << std::endl;
std::cout << "typeid(size3): " << typeid(size3).name() << std::endl;
}
}
#include <iostream>
namespace example_07 {
class foo {
public:
foo(int const x = 0) : x_{ x } {}
int& get() { return x_; }
private:
int x_;
};
void run() {
foo f{42};
auto x = f.get();
x = x + 100;
std::cout << f.get() << std::endl;
}
}
#include <iostream>
#include <typeinfo>
namespace example_08 {
void run() {
auto l = 42LL;
std::cout << "typeid(l): " << typeid(l).name() << std::endl;
}
}
namespace example_09 {
auto func1(int const i) -> int { return 2 * i; }
auto func2(int const i) { return 2 * i; }
void run() {
}
}
#include <iostream>
namespace example_10 {
class foo {
public:
foo(int const x = 0) : x_{ x } {}
int& get() { return x_; }
private:
int x_;
};
decltype(auto) proxy_get(foo& f) { return f.get(); }
void run() {
auto f = foo{ 42 };
decltype(auto) x = proxy_get(f);
x += 100;
std::cout << f.get() << std::endl;
}
}
#include <iostream>
#include <string>
namespace example_11 {
struct {
template <typename T, typename U>
auto operator() (T const a, U const b) const { return a + b; }
} struct_add;
void run() {
auto lambda_add = [](auto const a, auto const b) { return a + b; };
auto i = lambda_add(40, 2);
using namespace std::literals;
auto s = lambda_add("forty"s, "two"s);
}
}
// endregion [how it works]
typedef void (*ExampleFunction)();
#include <array>
#include <cstddef>
int main() {
const size_t ARRAY_SIZE = 11;
std::array<ExampleFunction, ARRAY_SIZE> examples{ {
&example_01::run, &example_02::run, &example_03::run,
&example_04::run, &example_05::run, &example_06::run,
&example_07::run, &example_08::run, &example_09::run,
&example_10::run, &example_11::run } };
for (const auto & example : examples) {
std::cout << "example => " << std::endl;
example();
std::cout << "end" << std::endl << std::endl;
}
return 0;
}
| [
"merely.ordinary.developer@gmail.com"
] | merely.ordinary.developer@gmail.com |
20dce90ae5d5fbc226a524b2757c9f23b217b270 | 69a22b81c47cfeb711196dabe9299cb070578963 | /DataProcess/ThreadManager.cpp | 54c7735905a54ddde7ae2a6b99384729491b2537 | [] | no_license | nhs635/Havana2 | 6610272c0d1aacfbb73f598792d5d506dbf89bf8 | 34e732a8804ceb6f12c9fe12d4bce524c3c66139 | refs/heads/master | 2023-08-21T22:26:27.201648 | 2023-08-03T05:17:08 | 2023-08-03T05:17:08 | 98,523,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,369 | cpp |
#include <DataProcess/ThreadManager.h>
ThreadManager::ThreadManager(const char* _threadID) :
_running(false)
{
memset(threadID, 0, MAX_LENGTH);
memcpy(threadID, _threadID, strlen(_threadID));
}
ThreadManager::~ThreadManager()
{
if (_thread.joinable())
{
_running = false;
_thread.join();
}
}
void ThreadManager::run()
{
unsigned int frameIndex = 0;
_running = true;
while (_running)
DidAcquireData(frameIndex++);
}
bool ThreadManager::startThreading()
{
if (_thread.joinable())
{
char* msg = nullptr;
sprintf(msg, "ERROR: %s thread is already running: ", threadID);
dumpErrorSystem(-1, msg); //(::GetLastError(), msg);
return false;
}
_thread = std::thread(&ThreadManager::run, this);
printf("%s thread is started.\n", threadID);
return true;
}
void ThreadManager::stopThreading()
{
if (_thread.joinable())
{
DidStopData(); //_running = false;
_thread.join();
}
printf("%s thread is finished normally.\n", threadID);
}
void ThreadManager::dumpErrorSystem(int res, const char* pPreamble)
{
char* pErr = nullptr;
char msg[MAX_LENGTH];
memcpy(msg, pPreamble, strlen(pPreamble));
sprintf(pErr, "Error code (%d)", res);
strcat(msg, pErr);
printf("%s\n", msg);
SendStatusMessage(msg);
}
| [
"nhs635@hanmail.net"
] | nhs635@hanmail.net |
26427a5e08f62cf3d49d7be5f99aa690531d4407 | 2bb27dc9bd3067deebb82f7c57fdac02a915d0d4 | /src/checkpoints.cpp | 5fdc2aee1fce64e782f785ded937fdf9d8eddd5d | [
"MIT"
] | permissive | bedri/proxynode | e46504844abd3f1772c16f37342bce1ca1f8c30a | 5b42796d008a5976703b2c2adcfcafc639c64c8f | refs/heads/master | 2020-05-19T13:14:45.538666 | 2019-05-05T08:36:00 | 2019-05-05T08:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,470 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Prx developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "chainparams.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/foreach.hpp>
namespace Checkpoints
{
/**
* How many times we expect transactions after the last checkpoint to
* be slower. This number is a compromise, as it can't be accurate for
* every system. When reindexing from a fast disk with a slow CPU, it
* can be up to 20, while when downloading from a slow network with a
* fast multicore CPU, it won't be much higher than 1.
*/
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
bool fEnabled = true;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
//! Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks)
{
if (pindex == NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData& data = Params().Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter * fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore * fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter * fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint()
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) {
const uint256& hash = i.second;
BlockMap::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
} // namespace Checkpoints
| [
"root@m5079.contaboserver.net"
] | root@m5079.contaboserver.net |
270c34e612ea2e42d3ab0e88d535f43fc0675810 | d1cee40adee73afdbce5b3582bbe4761b595c4e1 | /back/RtmpLivePushSDK/boost/boost/mpl/bool_fwd.hpp | 79e918103e7bad709afead8741d5a7d58977ce38 | [
"BSL-1.0"
] | permissive | RickyJun/live_plugin | de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb | e4472570eac0d9f388ccac6ee513935488d9577e | refs/heads/master | 2023-05-08T01:49:52.951207 | 2021-05-30T14:09:38 | 2021-05-30T14:09:38 | 345,919,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | hpp |
#ifndef BOOST_MPL_BOOL_FWD_HPP_INCLUDED
#define BOOST_MPL_BOOL_FWD_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: bool_fwd.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#include "adl_barrier.hpp"
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
template< bool C_ > struct bool_;
// shorcuts
typedef bool_<true> true_;
typedef bool_<false> false_;
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
BOOST_MPL_AUX_ADL_BARRIER_DECL(bool_)
BOOST_MPL_AUX_ADL_BARRIER_DECL(true_)
BOOST_MPL_AUX_ADL_BARRIER_DECL(false_)
#endif // BOOST_MPL_BOOL_FWD_HPP_INCLUDED
| [
"wenwenjun@weeget.cn"
] | wenwenjun@weeget.cn |
0be06367f6d122f3f0bf74d50e58f18c0f700ba4 | 33546aee6429d5b8f19a02e14699b6ebb5b34af8 | /src/ui/views/view_unittest.cc | 6af6b3a1612a4d4a55e5a069c0014c15e01e0578 | [
"BSD-3-Clause"
] | permissive | mYoda/CustomBrs | bdbf992c0db0bf2fd1821fa1fd0120ac77ffc011 | 493fc461eb7ea7321c51c6831fe737cfb21fdd3e | refs/heads/master | 2022-11-22T09:11:37.873894 | 2022-11-10T10:02:49 | 2022-11-10T10:02:49 | 24,951,822 | 0 | 1 | null | 2022-11-02T14:39:34 | 2014-10-08T17:22:30 | C++ | UTF-8 | C++ | false | false | 128,594 | cc | // 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 <map>
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ui_strings.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/compositor/test/test_layers.h"
#include "ui/events/event.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/path.h"
#include "ui/gfx/transform.h"
#include "ui/views/background.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/focus/view_storage.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/view_constants_aura.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/native_widget.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/window/dialog_client_view.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/wm/core/window_util.h"
using base::ASCIIToUTF16;
namespace {
// Returns true if |ancestor| is an ancestor of |layer|.
bool LayerIsAncestor(const ui::Layer* ancestor, const ui::Layer* layer) {
while (layer && layer != ancestor)
layer = layer->parent();
return layer == ancestor;
}
// Convenience functions for walking a View tree.
const views::View* FirstView(const views::View* view) {
const views::View* v = view;
while (v->has_children())
v = v->child_at(0);
return v;
}
const views::View* NextView(const views::View* view) {
const views::View* v = view;
const views::View* parent = v->parent();
if (!parent)
return NULL;
int next = parent->GetIndexOf(v) + 1;
if (next != parent->child_count())
return FirstView(parent->child_at(next));
return parent;
}
// Convenience functions for walking a Layer tree.
const ui::Layer* FirstLayer(const ui::Layer* layer) {
const ui::Layer* l = layer;
while (l->children().size() > 0)
l = l->children()[0];
return l;
}
const ui::Layer* NextLayer(const ui::Layer* layer) {
const ui::Layer* parent = layer->parent();
if (!parent)
return NULL;
const std::vector<ui::Layer*> children = parent->children();
size_t index;
for (index = 0; index < children.size(); index++) {
if (children[index] == layer)
break;
}
size_t next = index + 1;
if (next < children.size())
return FirstLayer(children[next]);
return parent;
}
// Given the root nodes of a View tree and a Layer tree, makes sure the two
// trees are in sync.
bool ViewAndLayerTreeAreConsistent(const views::View* view,
const ui::Layer* layer) {
const views::View* v = FirstView(view);
const ui::Layer* l = FirstLayer(layer);
while (v && l) {
// Find the view with a layer.
while (v && !v->layer())
v = NextView(v);
EXPECT_TRUE(v);
if (!v)
return false;
// Check if the View tree and the Layer tree are in sync.
EXPECT_EQ(l, v->layer());
if (v->layer() != l)
return false;
// Check if the visibility states of the View and the Layer are in sync.
EXPECT_EQ(l->IsDrawn(), v->IsDrawn());
if (v->IsDrawn() != l->IsDrawn()) {
for (const views::View* vv = v; vv; vv = vv->parent())
LOG(ERROR) << "V: " << vv << " " << vv->visible() << " "
<< vv->IsDrawn() << " " << vv->layer();
for (const ui::Layer* ll = l; ll; ll = ll->parent())
LOG(ERROR) << "L: " << ll << " " << ll->IsDrawn();
return false;
}
// Check if the size of the View and the Layer are in sync.
EXPECT_EQ(l->bounds(), v->bounds());
if (v->bounds() != l->bounds())
return false;
if (v == view || l == layer)
return v == view && l == layer;
v = NextView(v);
l = NextLayer(l);
}
return false;
}
// Constructs a View tree with the specified depth.
void ConstructTree(views::View* view, int depth) {
if (depth == 0)
return;
int count = base::RandInt(1, 5);
for (int i = 0; i < count; i++) {
views::View* v = new views::View;
view->AddChildView(v);
if (base::RandDouble() > 0.5)
v->SetPaintToLayer(true);
if (base::RandDouble() < 0.2)
v->SetVisible(false);
ConstructTree(v, depth - 1);
}
}
void ScrambleTree(views::View* view) {
int count = view->child_count();
if (count == 0)
return;
for (int i = 0; i < count; i++) {
ScrambleTree(view->child_at(i));
}
if (count > 1) {
int a = base::RandInt(0, count - 1);
int b = base::RandInt(0, count - 1);
views::View* view_a = view->child_at(a);
views::View* view_b = view->child_at(b);
view->ReorderChildView(view_a, b);
view->ReorderChildView(view_b, a);
}
if (!view->layer() && base::RandDouble() < 0.1)
view->SetPaintToLayer(true);
if (base::RandDouble() < 0.1)
view->SetVisible(!view->visible());
}
// Convenience to make constructing a GestureEvent simpler.
class GestureEventForTest : public ui::GestureEvent {
public:
GestureEventForTest(ui::EventType type, int x, int y, int flags)
: GestureEvent(type, x, y, flags, base::TimeDelta(),
ui::GestureEventDetails(type, 0.0f, 0.0f), 0) {
}
private:
DISALLOW_COPY_AND_ASSIGN(GestureEventForTest);
};
} // namespace
namespace views {
typedef ViewsTestBase ViewTest;
// A derived class for testing purpose.
class TestView : public View {
public:
TestView() : View(), delete_on_pressed_(false), native_theme_(NULL) {}
virtual ~TestView() {}
// Reset all test state
void Reset() {
did_change_bounds_ = false;
last_mouse_event_type_ = 0;
location_.SetPoint(0, 0);
received_mouse_enter_ = false;
received_mouse_exit_ = false;
last_gesture_event_type_ = 0;
last_gesture_event_was_handled_ = false;
last_clip_.setEmpty();
accelerator_count_map_.clear();
}
// Exposed as public for testing.
void DoFocus() {
views::View::Focus();
}
void DoBlur() {
views::View::Blur();
}
bool focusable() const { return View::focusable(); }
virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE;
virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE;
virtual bool OnMouseDragged(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE;
// Ignores GestureEvent by default.
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
virtual void Paint(gfx::Canvas* canvas, const CullSet& cull_set) OVERRIDE;
virtual void SchedulePaintInRect(const gfx::Rect& rect) OVERRIDE;
virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE;
virtual void OnNativeThemeChanged(const ui::NativeTheme* native_theme)
OVERRIDE;
// OnBoundsChanged.
bool did_change_bounds_;
gfx::Rect new_bounds_;
// MouseEvent.
int last_mouse_event_type_;
gfx::Point location_;
bool received_mouse_enter_;
bool received_mouse_exit_;
bool delete_on_pressed_;
// Painting.
std::vector<gfx::Rect> scheduled_paint_rects_;
// GestureEvent
int last_gesture_event_type_;
bool last_gesture_event_was_handled_;
// Painting.
SkRect last_clip_;
// Accelerators.
std::map<ui::Accelerator, int> accelerator_count_map_;
// Native theme.
const ui::NativeTheme* native_theme_;
};
// A view subclass that consumes all Gesture events for testing purposes.
class TestViewConsumeGesture : public TestView {
public:
TestViewConsumeGesture() : TestView() {}
virtual ~TestViewConsumeGesture() {}
protected:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
last_gesture_event_type_ = event->type();
location_.SetPoint(event->x(), event->y());
event->StopPropagation();
}
private:
DISALLOW_COPY_AND_ASSIGN(TestViewConsumeGesture);
};
// A view subclass that ignores all Gesture events.
class TestViewIgnoreGesture: public TestView {
public:
TestViewIgnoreGesture() : TestView() {}
virtual ~TestViewIgnoreGesture() {}
private:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
}
DISALLOW_COPY_AND_ASSIGN(TestViewIgnoreGesture);
};
// A view subclass that ignores all scroll-gesture events, but consume all other
// gesture events.
class TestViewIgnoreScrollGestures : public TestViewConsumeGesture {
public:
TestViewIgnoreScrollGestures() {}
virtual ~TestViewIgnoreScrollGestures() {}
private:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
if (event->IsScrollGestureEvent())
return;
TestViewConsumeGesture::OnGestureEvent(event);
}
DISALLOW_COPY_AND_ASSIGN(TestViewIgnoreScrollGestures);
};
////////////////////////////////////////////////////////////////////////////////
// OnBoundsChanged
////////////////////////////////////////////////////////////////////////////////
void TestView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
did_change_bounds_ = true;
new_bounds_ = bounds();
}
TEST_F(ViewTest, OnBoundsChanged) {
TestView v;
gfx::Rect prev_rect(0, 0, 200, 200);
gfx::Rect new_rect(100, 100, 250, 250);
v.SetBoundsRect(prev_rect);
v.Reset();
v.SetBoundsRect(new_rect);
EXPECT_TRUE(v.did_change_bounds_);
EXPECT_EQ(v.new_bounds_, new_rect);
EXPECT_EQ(v.bounds(), new_rect);
}
////////////////////////////////////////////////////////////////////////////////
// MouseEvent
////////////////////////////////////////////////////////////////////////////////
bool TestView::OnMousePressed(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
if (delete_on_pressed_)
delete this;
return true;
}
bool TestView::OnMouseDragged(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
return true;
}
void TestView::OnMouseReleased(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
}
void TestView::OnMouseEntered(const ui::MouseEvent& event) {
received_mouse_enter_ = true;
}
void TestView::OnMouseExited(const ui::MouseEvent& event) {
received_mouse_exit_ = true;
}
TEST_F(ViewTest, MouseEvent) {
TestView* v1 = new TestView();
v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
TestView* v2 = new TestView();
v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
internal::RootView* root =
static_cast<internal::RootView*>(widget->GetRootView());
root->AddChildView(v1);
v1->AddChildView(v2);
v1->Reset();
v2->Reset();
gfx::Point p1(110, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_PRESSED);
EXPECT_EQ(v2->location_.x(), 10);
EXPECT_EQ(v2->location_.y(), 20);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
// Drag event out of bounds. Should still go to v2
v1->Reset();
v2->Reset();
gfx::Point p2(50, 40);
ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, p2, p2,
ui::EF_LEFT_MOUSE_BUTTON, 0);
root->OnMouseDragged(dragged);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_DRAGGED);
EXPECT_EQ(v2->location_.x(), -50);
EXPECT_EQ(v2->location_.y(), -60);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
// Releasted event out of bounds. Should still go to v2
v1->Reset();
v2->Reset();
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), 0,
0);
root->OnMouseDragged(released);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_RELEASED);
EXPECT_EQ(v2->location_.x(), -100);
EXPECT_EQ(v2->location_.y(), -100);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
widget->CloseNow();
}
// Confirm that a view can be deleted as part of processing a mouse press.
TEST_F(ViewTest, DeleteOnPressed) {
TestView* v1 = new TestView();
v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
TestView* v2 = new TestView();
v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
v1->Reset();
v2->Reset();
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
View* root = widget->GetRootView();
root->AddChildView(v1);
v1->AddChildView(v2);
v2->delete_on_pressed_ = true;
gfx::Point point(110, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, point, point,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_EQ(0, v1->child_count());
widget->CloseNow();
}
////////////////////////////////////////////////////////////////////////////////
// GestureEvent
////////////////////////////////////////////////////////////////////////////////
void TestView::OnGestureEvent(ui::GestureEvent* event) {
}
TEST_F(ViewTest, GestureEvent) {
// Views hierarchy for non delivery of GestureEvent.
TestView* v1 = new TestViewConsumeGesture();
v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
TestView* v2 = new TestViewConsumeGesture();
v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
TestView* v3 = new TestViewIgnoreGesture();
v3->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
scoped_ptr<Widget> widget(new Widget());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
internal::RootView* root =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventDispatchDetails details;
root->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
// |v3| completely obscures |v2|, but all the gesture events on |v3| should
// reach |v2| because |v3| doesn't process any gesture events. However, since
// |v2| does process gesture events, gesture events on |v3| or |v2| should not
// reach |v1|.
v1->Reset();
v2->Reset();
v3->Reset();
// Gesture on |v3|
GestureEventForTest g1(ui::ET_GESTURE_TAP, 110, 110, 0);
details = root->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v2->last_gesture_event_type_);
EXPECT_EQ(gfx::Point(10, 10), v2->location_);
EXPECT_EQ(ui::ET_UNKNOWN, v1->last_gesture_event_type_);
// Simulate an up so that RootView is no longer targetting |v3|.
GestureEventForTest g1_up(ui::ET_GESTURE_END, 110, 110, 0);
details = root->OnEventFromSource(&g1_up);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
v1->Reset();
v2->Reset();
v3->Reset();
// Gesture on |v1|
GestureEventForTest g2(ui::ET_GESTURE_TAP, 80, 80, 0);
details = root->OnEventFromSource(&g2);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v1->last_gesture_event_type_);
EXPECT_EQ(gfx::Point(80, 80), v1->location_);
EXPECT_EQ(ui::ET_UNKNOWN, v2->last_gesture_event_type_);
// Send event |g1| again. Even though the coordinates target |v3| it should go
// to |v1| as that is the view the touch was initially down on.
v1->last_gesture_event_type_ = ui::ET_UNKNOWN;
v3->last_gesture_event_type_ = ui::ET_UNKNOWN;
details = root->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v1->last_gesture_event_type_);
EXPECT_EQ(ui::ET_UNKNOWN, v3->last_gesture_event_type_);
EXPECT_EQ("110,110", v1->location_.ToString());
widget->CloseNow();
}
TEST_F(ViewTest, ScrollGestureEvent) {
// Views hierarchy for non delivery of GestureEvent.
TestView* v1 = new TestViewConsumeGesture();
v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
TestView* v2 = new TestViewIgnoreScrollGestures();
v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
TestView* v3 = new TestViewIgnoreGesture();
v3->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
scoped_ptr<Widget> widget(new Widget());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
internal::RootView* root =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventDispatchDetails details;
root->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
// |v3| completely obscures |v2|, but all the gesture events on |v3| should
// reach |v2| because |v3| doesn't process any gesture events. However, since
// |v2| does process gesture events, gesture events on |v3| or |v2| should not
// reach |v1|.
v1->Reset();
v2->Reset();
v3->Reset();
// Gesture on |v3|
GestureEventForTest g1(ui::ET_GESTURE_TAP, 110, 110, 0);
details = root->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v2->last_gesture_event_type_);
EXPECT_EQ(gfx::Point(10, 10), v2->location_);
EXPECT_EQ(ui::ET_UNKNOWN, v1->last_gesture_event_type_);
v2->Reset();
// Send scroll gestures on |v3|. The gesture should reach |v2|, however,
// since it does not process scroll-gesture events, these events should reach
// |v1|.
GestureEventForTest gscroll_begin(ui::ET_GESTURE_SCROLL_BEGIN, 115, 115, 0);
details = root->OnEventFromSource(&gscroll_begin);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_UNKNOWN, v2->last_gesture_event_type_);
EXPECT_EQ(ui::ET_GESTURE_SCROLL_BEGIN, v1->last_gesture_event_type_);
v1->Reset();
// Send a second tap on |v1|. The event should reach |v2| since it is the
// default gesture handler, and not |v1| (even though it is the view under the
// point, and is the scroll event handler).
GestureEventForTest second_tap(ui::ET_GESTURE_TAP, 70, 70, 0);
details = root->OnEventFromSource(&second_tap);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v2->last_gesture_event_type_);
EXPECT_EQ(ui::ET_UNKNOWN, v1->last_gesture_event_type_);
v2->Reset();
GestureEventForTest gscroll_end(ui::ET_GESTURE_SCROLL_END, 50, 50, 0);
details = root->OnEventFromSource(&gscroll_end);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_SCROLL_END, v1->last_gesture_event_type_);
v1->Reset();
// Simulate an up so that RootView is no longer targetting |v3|.
GestureEventForTest g1_up(ui::ET_GESTURE_END, 110, 110, 0);
details = root->OnEventFromSource(&g1_up);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_END, v2->last_gesture_event_type_);
v1->Reset();
v2->Reset();
v3->Reset();
// Gesture on |v1|
GestureEventForTest g2(ui::ET_GESTURE_TAP, 80, 80, 0);
details = root->OnEventFromSource(&g2);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v1->last_gesture_event_type_);
EXPECT_EQ(gfx::Point(80, 80), v1->location_);
EXPECT_EQ(ui::ET_UNKNOWN, v2->last_gesture_event_type_);
// Send event |g1| again. Even though the coordinates target |v3| it should go
// to |v1| as that is the view the touch was initially down on.
v1->last_gesture_event_type_ = ui::ET_UNKNOWN;
v3->last_gesture_event_type_ = ui::ET_UNKNOWN;
details = root->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_EQ(ui::ET_GESTURE_TAP, v1->last_gesture_event_type_);
EXPECT_EQ(ui::ET_UNKNOWN, v3->last_gesture_event_type_);
EXPECT_EQ("110,110", v1->location_.ToString());
widget->CloseNow();
}
////////////////////////////////////////////////////////////////////////////////
// Painting
////////////////////////////////////////////////////////////////////////////////
void TestView::Paint(gfx::Canvas* canvas, const CullSet& cull_set) {
canvas->sk_canvas()->getClipBounds(&last_clip_);
}
void TestView::SchedulePaintInRect(const gfx::Rect& rect) {
scheduled_paint_rects_.push_back(rect);
View::SchedulePaintInRect(rect);
}
void CheckRect(const SkRect& check_rect, const SkRect& target_rect) {
EXPECT_EQ(target_rect.fLeft, check_rect.fLeft);
EXPECT_EQ(target_rect.fRight, check_rect.fRight);
EXPECT_EQ(target_rect.fTop, check_rect.fTop);
EXPECT_EQ(target_rect.fBottom, check_rect.fBottom);
}
TEST_F(ViewTest, RemoveNotification) {
ViewStorage* vs = ViewStorage::GetInstance();
Widget* widget = new Widget;
widget->Init(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
View* v1 = new View;
int s1 = vs->CreateStorageID();
vs->StoreView(s1, v1);
root_view->AddChildView(v1);
View* v11 = new View;
int s11 = vs->CreateStorageID();
vs->StoreView(s11, v11);
v1->AddChildView(v11);
View* v111 = new View;
int s111 = vs->CreateStorageID();
vs->StoreView(s111, v111);
v11->AddChildView(v111);
View* v112 = new View;
int s112 = vs->CreateStorageID();
vs->StoreView(s112, v112);
v11->AddChildView(v112);
View* v113 = new View;
int s113 = vs->CreateStorageID();
vs->StoreView(s113, v113);
v11->AddChildView(v113);
View* v1131 = new View;
int s1131 = vs->CreateStorageID();
vs->StoreView(s1131, v1131);
v113->AddChildView(v1131);
View* v12 = new View;
int s12 = vs->CreateStorageID();
vs->StoreView(s12, v12);
v1->AddChildView(v12);
View* v2 = new View;
int s2 = vs->CreateStorageID();
vs->StoreView(s2, v2);
root_view->AddChildView(v2);
View* v21 = new View;
int s21 = vs->CreateStorageID();
vs->StoreView(s21, v21);
v2->AddChildView(v21);
View* v211 = new View;
int s211 = vs->CreateStorageID();
vs->StoreView(s211, v211);
v21->AddChildView(v211);
size_t stored_views = vs->view_count();
// Try removing a leaf view.
v21->RemoveChildView(v211);
EXPECT_EQ(stored_views - 1, vs->view_count());
EXPECT_EQ(NULL, vs->RetrieveView(s211));
delete v211; // We won't use this one anymore.
// Now try removing a view with a hierarchy of depth 1.
v11->RemoveChildView(v113);
EXPECT_EQ(stored_views - 3, vs->view_count());
EXPECT_EQ(NULL, vs->RetrieveView(s113));
EXPECT_EQ(NULL, vs->RetrieveView(s1131));
delete v113; // We won't use this one anymore.
// Now remove even more.
root_view->RemoveChildView(v1);
EXPECT_EQ(NULL, vs->RetrieveView(s1));
EXPECT_EQ(NULL, vs->RetrieveView(s11));
EXPECT_EQ(NULL, vs->RetrieveView(s12));
EXPECT_EQ(NULL, vs->RetrieveView(s111));
EXPECT_EQ(NULL, vs->RetrieveView(s112));
// Put v1 back for more tests.
root_view->AddChildView(v1);
vs->StoreView(s1, v1);
// Synchronously closing the window deletes the view hierarchy, which should
// remove all its views from ViewStorage.
widget->CloseNow();
EXPECT_EQ(stored_views - 10, vs->view_count());
EXPECT_EQ(NULL, vs->RetrieveView(s1));
EXPECT_EQ(NULL, vs->RetrieveView(s12));
EXPECT_EQ(NULL, vs->RetrieveView(s11));
EXPECT_EQ(NULL, vs->RetrieveView(s12));
EXPECT_EQ(NULL, vs->RetrieveView(s21));
EXPECT_EQ(NULL, vs->RetrieveView(s111));
EXPECT_EQ(NULL, vs->RetrieveView(s112));
}
namespace {
class HitTestView : public View {
public:
explicit HitTestView(bool has_hittest_mask)
: has_hittest_mask_(has_hittest_mask) {
}
virtual ~HitTestView() {}
protected:
// Overridden from View:
virtual bool HasHitTestMask() const OVERRIDE {
return has_hittest_mask_;
}
virtual void GetHitTestMask(HitTestSource source,
gfx::Path* mask) const OVERRIDE {
DCHECK(has_hittest_mask_);
DCHECK(mask);
SkScalar w = SkIntToScalar(width());
SkScalar h = SkIntToScalar(height());
// Create a triangular mask within the bounds of this View.
mask->moveTo(w / 2, 0);
mask->lineTo(w, h);
mask->lineTo(0, h);
mask->close();
}
private:
bool has_hittest_mask_;
DISALLOW_COPY_AND_ASSIGN(HitTestView);
};
gfx::Point ConvertPointToView(View* view, const gfx::Point& p) {
gfx::Point tmp(p);
View::ConvertPointToTarget(view->GetWidget()->GetRootView(), view, &tmp);
return tmp;
}
gfx::Rect ConvertRectToView(View* view, const gfx::Rect& r) {
gfx::Rect tmp(r);
tmp.set_origin(ConvertPointToView(view, r.origin()));
return tmp;
}
void RotateCounterclockwise(gfx::Transform* transform) {
transform->matrix().set3x3(0, -1, 0,
1, 0, 0,
0, 0, 1);
}
void RotateClockwise(gfx::Transform* transform) {
transform->matrix().set3x3( 0, 1, 0,
-1, 0, 0,
0, 0, 1);
}
} // namespace
TEST_F(ViewTest, HitTestMasks) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(params);
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
gfx::Rect v1_bounds = gfx::Rect(0, 0, 100, 100);
HitTestView* v1 = new HitTestView(false);
v1->SetBoundsRect(v1_bounds);
root_view->AddChildView(v1);
gfx::Rect v2_bounds = gfx::Rect(105, 0, 100, 100);
HitTestView* v2 = new HitTestView(true);
v2->SetBoundsRect(v2_bounds);
root_view->AddChildView(v2);
gfx::Point v1_centerpoint = v1_bounds.CenterPoint();
gfx::Point v2_centerpoint = v2_bounds.CenterPoint();
gfx::Point v1_origin = v1_bounds.origin();
gfx::Point v2_origin = v2_bounds.origin();
gfx::Rect r1(10, 10, 110, 15);
gfx::Rect r2(106, 1, 98, 98);
gfx::Rect r3(0, 0, 300, 300);
gfx::Rect r4(115, 342, 200, 10);
// Test HitTestPoint
EXPECT_TRUE(v1->HitTestPoint(ConvertPointToView(v1, v1_centerpoint)));
EXPECT_TRUE(v2->HitTestPoint(ConvertPointToView(v2, v2_centerpoint)));
EXPECT_TRUE(v1->HitTestPoint(ConvertPointToView(v1, v1_origin)));
EXPECT_FALSE(v2->HitTestPoint(ConvertPointToView(v2, v2_origin)));
// Test HitTestRect
EXPECT_TRUE(v1->HitTestRect(ConvertRectToView(v1, r1)));
EXPECT_FALSE(v2->HitTestRect(ConvertRectToView(v2, r1)));
EXPECT_FALSE(v1->HitTestRect(ConvertRectToView(v1, r2)));
EXPECT_TRUE(v2->HitTestRect(ConvertRectToView(v2, r2)));
EXPECT_TRUE(v1->HitTestRect(ConvertRectToView(v1, r3)));
EXPECT_TRUE(v2->HitTestRect(ConvertRectToView(v2, r3)));
EXPECT_FALSE(v1->HitTestRect(ConvertRectToView(v1, r4)));
EXPECT_FALSE(v2->HitTestRect(ConvertRectToView(v2, r4)));
// Test GetEventHandlerForPoint
EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_centerpoint));
EXPECT_EQ(v2, root_view->GetEventHandlerForPoint(v2_centerpoint));
EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_origin));
EXPECT_EQ(root_view, root_view->GetEventHandlerForPoint(v2_origin));
// Test GetTooltipHandlerForPoint
EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_centerpoint));
EXPECT_EQ(v2, root_view->GetTooltipHandlerForPoint(v2_centerpoint));
EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_origin));
EXPECT_EQ(root_view, root_view->GetTooltipHandlerForPoint(v2_origin));
EXPECT_FALSE(v1->GetTooltipHandlerForPoint(v2_origin));
widget->CloseNow();
}
// Tests the correctness of the rect-based targeting algorithm implemented in
// View::GetEventHandlerForRect(). See http://goo.gl/3Jp2BD for a description
// of rect-based targeting.
TEST_F(ViewTest, GetEventHandlerForRect) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(params);
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// Have this hierarchy of views (the coordinates here are all in
// the root view's coordinate space):
// v1 (0, 0, 100, 100)
// v2 (150, 0, 250, 100)
// v3 (0, 200, 150, 100)
// v31 (10, 210, 80, 80)
// v32 (110, 210, 30, 80)
// v4 (300, 200, 100, 100)
// v41 (310, 210, 80, 80)
// v411 (370, 275, 10, 5)
// v5 (450, 197, 30, 36)
// v51 (450, 200, 30, 30)
// The coordinates used for SetBounds are in parent coordinates.
TestView* v1 = new TestView;
v1->SetBounds(0, 0, 100, 100);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(150, 0, 250, 100);
root_view->AddChildView(v2);
TestView* v3 = new TestView;
v3->SetBounds(0, 200, 150, 100);
root_view->AddChildView(v3);
TestView* v4 = new TestView;
v4->SetBounds(300, 200, 100, 100);
root_view->AddChildView(v4);
TestView* v31 = new TestView;
v31->SetBounds(10, 10, 80, 80);
v3->AddChildView(v31);
TestView* v32 = new TestView;
v32->SetBounds(110, 10, 30, 80);
v3->AddChildView(v32);
TestView* v41 = new TestView;
v41->SetBounds(10, 10, 80, 80);
v4->AddChildView(v41);
TestView* v411 = new TestView;
v411->SetBounds(60, 65, 10, 5);
v41->AddChildView(v411);
TestView* v5 = new TestView;
v5->SetBounds(450, 197, 30, 36);
root_view->AddChildView(v5);
TestView* v51 = new TestView;
v51->SetBounds(0, 3, 30, 30);
v5->AddChildView(v51);
// |touch_rect| does not intersect any descendant view of |root_view|.
gfx::Rect touch_rect(105, 105, 30, 45);
View* result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = NULL;
// Covers |v1| by at least 60%.
touch_rect.SetRect(15, 15, 100, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = NULL;
// Intersects |v1| but does not cover it by at least 60%. The center
// of |touch_rect| is within |v1|.
touch_rect.SetRect(50, 50, 5, 10);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = NULL;
// Intersects |v1| but does not cover it by at least 60%. The center
// of |touch_rect| is not within |v1|.
touch_rect.SetRect(95, 96, 21, 22);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = NULL;
// Intersects |v1| and |v2|, but only covers |v2| by at least 60%.
touch_rect.SetRect(95, 10, 300, 120);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v2, result_view);
result_view = NULL;
// Covers both |v1| and |v2| by at least 60%, but the center point
// of |touch_rect| is closer to the center point of |v2|.
touch_rect.SetRect(20, 20, 400, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v2, result_view);
result_view = NULL;
// Covers both |v1| and |v2| by at least 60%, but the center point
// of |touch_rect| is closer to the center point of |v1|.
touch_rect.SetRect(-700, -15, 1050, 110);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = NULL;
// A mouse click within |v1| will target |v1|.
touch_rect.SetRect(15, 15, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = NULL;
// Intersects |v3| and |v31| by at least 60% and the center point
// of |touch_rect| is closer to the center point of |v31|.
touch_rect.SetRect(0, 200, 110, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v31, result_view);
result_view = NULL;
// Intersects |v3| and |v31|, but neither by at least 60%. The
// center point of |touch_rect| lies within |v31|.
touch_rect.SetRect(80, 280, 15, 15);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v31, result_view);
result_view = NULL;
// Covers |v3|, |v31|, and |v32| all by at least 60%, and the
// center point of |touch_rect| is closest to the center point
// of |v32|.
touch_rect.SetRect(0, 200, 200, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = NULL;
// Intersects all of |v3|, |v31|, and |v32|, but only covers
// |v31| and |v32| by at least 60%. The center point of
// |touch_rect| is closest to the center point of |v32|.
touch_rect.SetRect(30, 225, 180, 115);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = NULL;
// A mouse click at the corner of |v3| will target |v3|.
touch_rect.SetRect(0, 200, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v3, result_view);
result_view = NULL;
// A mouse click within |v32| will target |v32|.
touch_rect.SetRect(112, 211, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = NULL;
// Covers all of |v4|, |v41|, and |v411| by at least 60%.
// The center point of |touch_rect| is equally close to
// the center points of |v4| and |v41|.
touch_rect.SetRect(310, 210, 80, 80);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = NULL;
// Intersects all of |v4|, |v41|, and |v411| but only covers
// |v411| by at least 60%.
touch_rect.SetRect(370, 275, 7, 5);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = NULL;
// Intersects |v4| and |v41| but covers neither by at least 60%.
// The center point of |touch_rect| is equally close to the center
// points of |v4| and |v41|.
touch_rect.SetRect(345, 245, 7, 7);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = NULL;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v411|.
touch_rect.SetRect(368, 272, 4, 6);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = NULL;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v41|.
touch_rect.SetRect(365, 270, 7, 7);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = NULL;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v4|.
touch_rect.SetRect(205, 275, 200, 2);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v4, result_view);
result_view = NULL;
// Intersects all of |v4|, |v41|, and |v411| but only covers
// |v41| by at least 60%.
touch_rect.SetRect(310, 210, 61, 66);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = NULL;
// A mouse click within |v411| will target |v411|.
touch_rect.SetRect(372, 275, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = NULL;
// A mouse click within |v41| will target |v41|.
touch_rect.SetRect(350, 215, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = NULL;
// Covers |v3|, |v4|, and all of their descendants by at
// least 60%. The center point of |touch_rect| is closest
// to the center point of |v32|.
touch_rect.SetRect(0, 200, 400, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = NULL;
// Intersects all of |v2|, |v3|, |v32|, |v4|, |v41|, and |v411|.
// Covers |v2|, |v32|, |v4|, |v41|, and |v411| by at least 60%.
// The center point of |touch_rect| is closest to the center
// point of |root_view|.
touch_rect.SetRect(110, 15, 375, 450);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = NULL;
// Covers all views (except |v5| and |v51|) by at least 60%. The
// center point of |touch_rect| is equally close to the center
// points of |v2| and |v32|. One is not a descendant of the other,
// so in this case the view selected is arbitrary (i.e.,
// it depends only on the ordering of nodes in the views
// hierarchy).
touch_rect.SetRect(0, 0, 400, 300);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = NULL;
// Covers |v5| and |v51| by at least 60%, and the center point of
// the touch is located within both views. Since both views share
// the same center point, the child view should be selected.
touch_rect.SetRect(440, 190, 40, 40);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = NULL;
// Covers |v5| and |v51| by at least 60%, but the center point of
// the touch is not located within either view. Since both views
// share the same center point, the child view should be selected.
touch_rect.SetRect(455, 187, 60, 60);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = NULL;
// Covers neither |v5| nor |v51| by at least 60%, but the center
// of the touch is located within |v51|.
touch_rect.SetRect(450, 197, 10, 10);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = NULL;
// Covers neither |v5| nor |v51| by at least 60% but intersects both.
// The center point is located outside of both views.
touch_rect.SetRect(433, 180, 24, 24);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = NULL;
// Only intersects |v5| but does not cover it by at least 60%. The
// center point of the touch region is located within |v5|.
touch_rect.SetRect(449, 196, 3, 3);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v5, result_view);
result_view = NULL;
// A mouse click within |v5| (but not |v51|) should target |v5|.
touch_rect.SetRect(462, 199, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v5, result_view);
result_view = NULL;
// A mouse click |v5| and |v51| should target the child view.
touch_rect.SetRect(452, 226, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = NULL;
// A mouse click on the center of |v5| and |v51| should target
// the child view.
touch_rect.SetRect(465, 215, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = NULL;
widget->CloseNow();
}
TEST_F(ViewTest, NotifyEnterExitOnChild) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(params);
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// Have this hierarchy of views (the coords here are in root coord):
// v1 (0, 0, 100, 100)
// - v11 (0, 0, 20, 30)
// - v111 (5, 5, 5, 15)
// - v12 (50, 10, 30, 90)
// - v121 (60, 20, 10, 10)
// v2 (105, 0, 100, 100)
// - v21 (120, 10, 50, 20)
TestView* v1 = new TestView;
v1->SetBounds(0, 0, 100, 100);
root_view->AddChildView(v1);
v1->set_notify_enter_exit_on_child(true);
TestView* v11 = new TestView;
v11->SetBounds(0, 0, 20, 30);
v1->AddChildView(v11);
TestView* v111 = new TestView;
v111->SetBounds(5, 5, 5, 15);
v11->AddChildView(v111);
TestView* v12 = new TestView;
v12->SetBounds(50, 10, 30, 90);
v1->AddChildView(v12);
TestView* v121 = new TestView;
v121->SetBounds(10, 10, 10, 10);
v12->AddChildView(v121);
TestView* v2 = new TestView;
v2->SetBounds(105, 0, 100, 100);
root_view->AddChildView(v2);
TestView* v21 = new TestView;
v21->SetBounds(15, 10, 50, 20);
v2->AddChildView(v21);
v1->Reset();
v11->Reset();
v111->Reset();
v12->Reset();
v121->Reset();
v2->Reset();
v21->Reset();
// Move the mouse in v111.
gfx::Point p1(6, 6);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, p1, p1, 0, 0);
root_view->OnMouseMoved(move1);
EXPECT_TRUE(v111->received_mouse_enter_);
EXPECT_FALSE(v11->last_mouse_event_type_);
EXPECT_TRUE(v1->received_mouse_enter_);
v111->Reset();
v1->Reset();
// Now, move into v121.
gfx::Point p2(65, 21);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, p2, p2, 0, 0);
root_view->OnMouseMoved(move2);
EXPECT_TRUE(v111->received_mouse_exit_);
EXPECT_TRUE(v121->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v111->Reset();
v121->Reset();
// Now, move into v11.
gfx::Point p3(1, 1);
ui::MouseEvent move3(ui::ET_MOUSE_MOVED, p3, p3, 0, 0);
root_view->OnMouseMoved(move3);
EXPECT_TRUE(v121->received_mouse_exit_);
EXPECT_TRUE(v11->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v121->Reset();
v11->Reset();
// Move to v21.
gfx::Point p4(121, 15);
ui::MouseEvent move4(ui::ET_MOUSE_MOVED, p4, p4, 0, 0);
root_view->OnMouseMoved(move4);
EXPECT_TRUE(v21->received_mouse_enter_);
EXPECT_FALSE(v2->last_mouse_event_type_);
EXPECT_TRUE(v11->received_mouse_exit_);
EXPECT_TRUE(v1->received_mouse_exit_);
v21->Reset();
v11->Reset();
v1->Reset();
// Move to v1.
gfx::Point p5(21, 0);
ui::MouseEvent move5(ui::ET_MOUSE_MOVED, p5, p5, 0, 0);
root_view->OnMouseMoved(move5);
EXPECT_TRUE(v21->received_mouse_exit_);
EXPECT_TRUE(v1->received_mouse_enter_);
v21->Reset();
v1->Reset();
// Now, move into v11.
gfx::Point p6(15, 15);
ui::MouseEvent mouse6(ui::ET_MOUSE_MOVED, p6, p6, 0, 0);
root_view->OnMouseMoved(mouse6);
EXPECT_TRUE(v11->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v11->Reset();
v1->Reset();
// Move back into v1. Although |v1| had already received an ENTER for mouse6,
// and the mouse remains inside |v1| the whole time, it receives another ENTER
// when the mouse leaves v11.
gfx::Point p7(21, 0);
ui::MouseEvent mouse7(ui::ET_MOUSE_MOVED, p7, p7, 0, 0);
root_view->OnMouseMoved(mouse7);
EXPECT_TRUE(v11->received_mouse_exit_);
EXPECT_FALSE(v1->received_mouse_enter_);
widget->CloseNow();
}
TEST_F(ViewTest, Textfield) {
const base::string16 kText = ASCIIToUTF16(
"Reality is that which, when you stop believing it, doesn't go away.");
const base::string16 kExtraText = ASCIIToUTF16("Pretty deep, Philip!");
const base::string16 kEmptyString;
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(params);
View* root_view = widget->GetRootView();
Textfield* textfield = new Textfield();
root_view->AddChildView(textfield);
// Test setting, appending text.
textfield->SetText(kText);
EXPECT_EQ(kText, textfield->text());
textfield->AppendText(kExtraText);
EXPECT_EQ(kText + kExtraText, textfield->text());
textfield->SetText(base::string16());
EXPECT_EQ(kEmptyString, textfield->text());
// Test selection related methods.
textfield->SetText(kText);
EXPECT_EQ(kEmptyString, textfield->GetSelectedText());
textfield->SelectAll(false);
EXPECT_EQ(kText, textfield->text());
textfield->ClearSelection();
EXPECT_EQ(kEmptyString, textfield->GetSelectedText());
widget->CloseNow();
}
// Tests that the Textfield view respond appropiately to cut/copy/paste.
TEST_F(ViewTest, TextfieldCutCopyPaste) {
const base::string16 kNormalText = ASCIIToUTF16("Normal");
const base::string16 kReadOnlyText = ASCIIToUTF16("Read only");
const base::string16 kPasswordText =
ASCIIToUTF16("Password! ** Secret stuff **");
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(params);
View* root_view = widget->GetRootView();
Textfield* normal = new Textfield();
Textfield* read_only = new Textfield();
read_only->SetReadOnly(true);
Textfield* password = new Textfield();
password->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
root_view->AddChildView(normal);
root_view->AddChildView(read_only);
root_view->AddChildView(password);
normal->SetText(kNormalText);
read_only->SetText(kReadOnlyText);
password->SetText(kPasswordText);
//
// Test cut.
//
normal->SelectAll(false);
normal->ExecuteCommand(IDS_APP_CUT);
base::string16 result;
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
EXPECT_EQ(kNormalText, result);
normal->SetText(kNormalText); // Let's revert to the original content.
read_only->SelectAll(false);
read_only->ExecuteCommand(IDS_APP_CUT);
result.clear();
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
// Cut should have failed, so the clipboard content should not have changed.
EXPECT_EQ(kNormalText, result);
password->SelectAll(false);
password->ExecuteCommand(IDS_APP_CUT);
result.clear();
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
// Cut should have failed, so the clipboard content should not have changed.
EXPECT_EQ(kNormalText, result);
//
// Test copy.
//
// Start with |read_only| to observe a change in clipboard text.
read_only->SelectAll(false);
read_only->ExecuteCommand(IDS_APP_COPY);
result.clear();
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
EXPECT_EQ(kReadOnlyText, result);
normal->SelectAll(false);
normal->ExecuteCommand(IDS_APP_COPY);
result.clear();
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
EXPECT_EQ(kNormalText, result);
password->SelectAll(false);
password->ExecuteCommand(IDS_APP_COPY);
result.clear();
clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result);
// Text cannot be copied from an obscured field; the clipboard won't change.
EXPECT_EQ(kNormalText, result);
//
// Test paste.
//
// Attempting to paste kNormalText in a read-only text-field should fail.
read_only->SelectAll(false);
read_only->ExecuteCommand(IDS_APP_PASTE);
EXPECT_EQ(kReadOnlyText, read_only->text());
password->SelectAll(false);
password->ExecuteCommand(IDS_APP_PASTE);
EXPECT_EQ(kNormalText, password->text());
// Copy from |read_only| to observe a change in the normal textfield text.
read_only->SelectAll(false);
read_only->ExecuteCommand(IDS_APP_COPY);
normal->SelectAll(false);
normal->ExecuteCommand(IDS_APP_PASTE);
EXPECT_EQ(kReadOnlyText, normal->text());
widget->CloseNow();
}
////////////////////////////////////////////////////////////////////////////////
// Accelerators
////////////////////////////////////////////////////////////////////////////////
bool TestView::AcceleratorPressed(const ui::Accelerator& accelerator) {
accelerator_count_map_[accelerator]++;
return true;
}
// TODO: these tests were initially commented out when getting aura to
// run. Figure out if still valuable and either nuke or fix.
#if defined(false)
TEST_F(ViewTest, ActivateAccelerator) {
// Register a keyboard accelerator before the view is added to a window.
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestView* view = new TestView();
view->Reset();
view->AddAccelerator(return_accelerator);
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0);
// Create a window and add the view as its child.
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(params);
View* root = widget->GetRootView();
root->AddChildView(view);
widget->Show();
// Get the focus manager.
FocusManager* focus_manager = widget->GetFocusManager();
ASSERT_TRUE(focus_manager);
// Hit the return key and see if it takes effect.
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
// Hit the escape key. Nothing should happen.
ui::Accelerator escape_accelerator(ui::VKEY_ESCAPE, ui::EF_NONE);
EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 0);
// Now register the escape key and hit it again.
view->AddAccelerator(escape_accelerator);
EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
// Remove the return key accelerator.
view->RemoveAccelerator(return_accelerator);
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
// Add it again. Hit the return key and the escape key.
view->AddAccelerator(return_accelerator);
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
// Remove all the accelerators.
view->ResetAccelerators();
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
widget->CloseNow();
}
TEST_F(ViewTest, HiddenViewWithAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestView* view = new TestView();
view->Reset();
view->AddAccelerator(return_accelerator);
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0);
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(params);
View* root = widget->GetRootView();
root->AddChildView(view);
widget->Show();
FocusManager* focus_manager = widget->GetFocusManager();
ASSERT_TRUE(focus_manager);
view->SetVisible(false);
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
view->SetVisible(true);
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
widget->CloseNow();
}
TEST_F(ViewTest, ViewInHiddenWidgetWithAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestView* view = new TestView();
view->Reset();
view->AddAccelerator(return_accelerator);
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0);
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(params);
View* root = widget->GetRootView();
root->AddChildView(view);
FocusManager* focus_manager = widget->GetFocusManager();
ASSERT_TRUE(focus_manager);
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(0, view->accelerator_count_map_[return_accelerator]);
widget->Show();
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
widget->Hide();
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
widget->CloseNow();
}
////////////////////////////////////////////////////////////////////////////////
// Mouse-wheel message rerouting
////////////////////////////////////////////////////////////////////////////////
class ScrollableTestView : public View {
public:
ScrollableTestView() { }
virtual gfx::Size GetPreferredSize() {
return gfx::Size(100, 10000);
}
virtual void Layout() {
SizeToPreferredSize();
}
};
class TestViewWithControls : public View {
public:
TestViewWithControls() {
text_field_ = new Textfield();
AddChildView(text_field_);
}
Textfield* text_field_;
};
class SimpleWidgetDelegate : public WidgetDelegate {
public:
explicit SimpleWidgetDelegate(View* contents) : contents_(contents) { }
virtual void DeleteDelegate() { delete this; }
virtual View* GetContentsView() { return contents_; }
virtual Widget* GetWidget() { return contents_->GetWidget(); }
virtual const Widget* GetWidget() const { return contents_->GetWidget(); }
private:
View* contents_;
};
// Tests that the mouse-wheel messages are correctly rerouted to the window
// under the mouse.
// TODO(jcampan): http://crbug.com/10572 Disabled as it fails on the Vista build
// bot.
// Note that this fails for a variety of reasons:
// - focused view is apparently reset across window activations and never
// properly restored
// - this test depends on you not having any other window visible open under the
// area that it opens the test windows. --beng
TEST_F(ViewTest, DISABLED_RerouteMouseWheelTest) {
TestViewWithControls* view_with_controls = new TestViewWithControls();
Widget* window1 = Widget::CreateWindowWithBounds(
new SimpleWidgetDelegate(view_with_controls),
gfx::Rect(0, 0, 100, 100));
window1->Show();
ScrollView* scroll_view = new ScrollView();
scroll_view->SetContents(new ScrollableTestView());
Widget* window2 = Widget::CreateWindowWithBounds(
new SimpleWidgetDelegate(scroll_view),
gfx::Rect(200, 200, 100, 100));
window2->Show();
EXPECT_EQ(0, scroll_view->GetVisibleRect().y());
// Make the window1 active, as this is what it would be in real-world.
window1->Activate();
// Let's send a mouse-wheel message to the different controls and check that
// it is rerouted to the window under the mouse (effectively scrolling the
// scroll-view).
// First to the Window's HWND.
::SendMessage(view_with_controls->GetWidget()->GetNativeView(),
WM_MOUSEWHEEL, MAKEWPARAM(0, -20), MAKELPARAM(250, 250));
EXPECT_EQ(20, scroll_view->GetVisibleRect().y());
window1->CloseNow();
window2->CloseNow();
}
#endif // false
////////////////////////////////////////////////////////////////////////////////
// Native view hierachy
////////////////////////////////////////////////////////////////////////////////
class ToplevelWidgetObserverView : public View {
public:
ToplevelWidgetObserverView() : toplevel_(NULL) {
}
virtual ~ToplevelWidgetObserverView() {
}
// View overrides:
virtual void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) OVERRIDE {
if (details.is_add) {
toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL;
} else {
toplevel_ = NULL;
}
}
virtual void NativeViewHierarchyChanged() OVERRIDE {
toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL;
}
Widget* toplevel() { return toplevel_; }
private:
Widget* toplevel_;
DISALLOW_COPY_AND_ASSIGN(ToplevelWidgetObserverView);
};
// Test that a view can track the current top level widget by overriding
// View::ViewHierarchyChanged() and View::NativeViewHierarchyChanged().
TEST_F(ViewTest, NativeViewHierarchyChanged) {
scoped_ptr<Widget> toplevel1(new Widget);
Widget::InitParams toplevel1_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
toplevel1_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
toplevel1->Init(toplevel1_params);
scoped_ptr<Widget> toplevel2(new Widget);
Widget::InitParams toplevel2_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
toplevel2_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
toplevel2->Init(toplevel2_params);
Widget* child = new Widget;
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child_params.parent = toplevel1->GetNativeView();
child->Init(child_params);
ToplevelWidgetObserverView* observer_view =
new ToplevelWidgetObserverView();
EXPECT_EQ(NULL, observer_view->toplevel());
child->SetContentsView(observer_view);
EXPECT_EQ(toplevel1, observer_view->toplevel());
Widget::ReparentNativeView(child->GetNativeView(),
toplevel2->GetNativeView());
EXPECT_EQ(toplevel2, observer_view->toplevel());
observer_view->parent()->RemoveChildView(observer_view);
EXPECT_EQ(NULL, observer_view->toplevel());
// Make |observer_view| |child|'s contents view again so that it gets deleted
// with the widget.
child->SetContentsView(observer_view);
}
////////////////////////////////////////////////////////////////////////////////
// Transformations
////////////////////////////////////////////////////////////////////////////////
class TransformPaintView : public TestView {
public:
TransformPaintView() {}
virtual ~TransformPaintView() {}
void ClearScheduledPaintRect() {
scheduled_paint_rect_ = gfx::Rect();
}
gfx::Rect scheduled_paint_rect() const { return scheduled_paint_rect_; }
// Overridden from View:
virtual void SchedulePaintInRect(const gfx::Rect& rect) OVERRIDE {
gfx::Rect xrect = ConvertRectToParent(rect);
scheduled_paint_rect_.Union(xrect);
}
private:
gfx::Rect scheduled_paint_rect_;
DISALLOW_COPY_AND_ASSIGN(TransformPaintView);
};
TEST_F(ViewTest, TransformPaint) {
TransformPaintView* v1 = new TransformPaintView();
v1->SetBoundsRect(gfx::Rect(0, 0, 500, 300));
TestView* v2 = new TestView();
v2->SetBoundsRect(gfx::Rect(100, 100, 200, 100));
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
widget->Show();
View* root = widget->GetRootView();
root->AddChildView(v1);
v1->AddChildView(v2);
// At this moment, |v2| occupies (100, 100) to (300, 200) in |root|.
v1->ClearScheduledPaintRect();
v2->SchedulePaint();
EXPECT_EQ(gfx::Rect(100, 100, 200, 100), v1->scheduled_paint_rect());
// Rotate |v1| counter-clockwise.
gfx::Transform transform;
RotateCounterclockwise(&transform);
transform.matrix().set(1, 3, 500.0);
v1->SetTransform(transform);
// |v2| now occupies (100, 200) to (200, 400) in |root|.
v1->ClearScheduledPaintRect();
v2->SchedulePaint();
EXPECT_EQ(gfx::Rect(100, 200, 100, 200), v1->scheduled_paint_rect());
widget->CloseNow();
}
TEST_F(ViewTest, TransformEvent) {
TestView* v1 = new TestView();
v1->SetBoundsRect(gfx::Rect(0, 0, 500, 300));
TestView* v2 = new TestView();
v2->SetBoundsRect(gfx::Rect(100, 100, 200, 100));
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
View* root = widget->GetRootView();
root->AddChildView(v1);
v1->AddChildView(v2);
// At this moment, |v2| occupies (100, 100) to (300, 200) in |root|.
// Rotate |v1| counter-clockwise.
gfx::Transform transform(v1->GetTransform());
RotateCounterclockwise(&transform);
transform.matrix().set(1, 3, 500.0);
v1->SetTransform(transform);
// |v2| now occupies (100, 200) to (200, 400) in |root|.
v1->Reset();
v2->Reset();
gfx::Point p1(110, 210);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_EQ(0, v1->last_mouse_event_type_);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_);
EXPECT_EQ(190, v2->location_.x());
EXPECT_EQ(10, v2->location_.y());
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), 0,
0);
root->OnMouseReleased(released);
// Now rotate |v2| inside |v1| clockwise.
transform = v2->GetTransform();
RotateClockwise(&transform);
transform.matrix().set(0, 3, 100.f);
v2->SetTransform(transform);
// Now, |v2| occupies (100, 100) to (200, 300) in |v1|, and (100, 300) to
// (300, 400) in |root|.
v1->Reset();
v2->Reset();
gfx::Point point2(110, 320);
ui::MouseEvent p2(ui::ET_MOUSE_PRESSED, point2, point2,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p2);
EXPECT_EQ(0, v1->last_mouse_event_type_);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_);
EXPECT_EQ(10, v2->location_.x());
EXPECT_EQ(20, v2->location_.y());
root->OnMouseReleased(released);
v1->SetTransform(gfx::Transform());
v2->SetTransform(gfx::Transform());
TestView* v3 = new TestView();
v3->SetBoundsRect(gfx::Rect(10, 10, 20, 30));
v2->AddChildView(v3);
// Rotate |v3| clockwise with respect to |v2|.
transform = v1->GetTransform();
RotateClockwise(&transform);
transform.matrix().set(0, 3, 30.f);
v3->SetTransform(transform);
// Scale |v2| with respect to |v1| along both axis.
transform = v2->GetTransform();
transform.matrix().set(0, 0, 0.8f);
transform.matrix().set(1, 1, 0.5f);
v2->SetTransform(transform);
// |v3| occupies (108, 105) to (132, 115) in |root|.
v1->Reset();
v2->Reset();
v3->Reset();
gfx::Point point(112, 110);
ui::MouseEvent p3(ui::ET_MOUSE_PRESSED, point, point,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p3);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_);
EXPECT_EQ(10, v3->location_.x());
EXPECT_EQ(25, v3->location_.y());
root->OnMouseReleased(released);
v1->SetTransform(gfx::Transform());
v2->SetTransform(gfx::Transform());
v3->SetTransform(gfx::Transform());
v1->Reset();
v2->Reset();
v3->Reset();
// Rotate |v3| clockwise with respect to |v2|, and scale it along both axis.
transform = v3->GetTransform();
RotateClockwise(&transform);
transform.matrix().set(0, 3, 30.f);
// Rotation sets some scaling transformation. Using SetScale would overwrite
// that and pollute the rotation. So combine the scaling with the existing
// transforamtion.
gfx::Transform scale;
scale.Scale(0.8f, 0.5f);
transform.ConcatTransform(scale);
v3->SetTransform(transform);
// Translate |v2| with respect to |v1|.
transform = v2->GetTransform();
transform.matrix().set(0, 3, 10.f);
transform.matrix().set(1, 3, 10.f);
v2->SetTransform(transform);
// |v3| now occupies (120, 120) to (144, 130) in |root|.
gfx::Point point3(124, 125);
ui::MouseEvent p4(ui::ET_MOUSE_PRESSED, point3, point3,
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p4);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_);
EXPECT_EQ(10, v3->location_.x());
EXPECT_EQ(25, v3->location_.y());
root->OnMouseReleased(released);
widget->CloseNow();
}
TEST_F(ViewTest, TransformVisibleBound) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = viewport_bounds;
widget->Init(params);
widget->GetRootView()->SetBoundsRect(viewport_bounds);
View* viewport = new View;
widget->SetContentsView(viewport);
View* contents = new View;
viewport->AddChildView(contents);
viewport->SetBoundsRect(viewport_bounds);
contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200));
View* child = new View;
contents->AddChildView(child);
child->SetBoundsRect(gfx::Rect(10, 90, 50, 50));
EXPECT_EQ(gfx::Rect(0, 0, 50, 10), child->GetVisibleBounds());
// Rotate |child| counter-clockwise
gfx::Transform transform;
RotateCounterclockwise(&transform);
transform.matrix().set(1, 3, 50.f);
child->SetTransform(transform);
EXPECT_EQ(gfx::Rect(40, 0, 10, 50), child->GetVisibleBounds());
widget->CloseNow();
}
////////////////////////////////////////////////////////////////////////////////
// OnVisibleBoundsChanged()
class VisibleBoundsView : public View {
public:
VisibleBoundsView() : received_notification_(false) {}
virtual ~VisibleBoundsView() {}
bool received_notification() const { return received_notification_; }
void set_received_notification(bool received) {
received_notification_ = received;
}
private:
// Overridden from View:
virtual bool NeedsNotificationWhenVisibleBoundsChange() const OVERRIDE {
return true;
}
virtual void OnVisibleBoundsChanged() OVERRIDE {
received_notification_ = true;
}
bool received_notification_;
DISALLOW_COPY_AND_ASSIGN(VisibleBoundsView);
};
TEST_F(ViewTest, OnVisibleBoundsChanged) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = viewport_bounds;
widget->Init(params);
widget->GetRootView()->SetBoundsRect(viewport_bounds);
View* viewport = new View;
widget->SetContentsView(viewport);
View* contents = new View;
viewport->AddChildView(contents);
viewport->SetBoundsRect(viewport_bounds);
contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200));
// Create a view that cares about visible bounds notifications, and position
// it just outside the visible bounds of the viewport.
VisibleBoundsView* child = new VisibleBoundsView;
contents->AddChildView(child);
child->SetBoundsRect(gfx::Rect(10, 110, 50, 50));
// The child bound should be fully clipped.
EXPECT_TRUE(child->GetVisibleBounds().IsEmpty());
// Now scroll the contents, but not enough to make the child visible.
contents->SetY(contents->y() - 1);
// We should have received the notification since the visible bounds may have
// changed (even though they didn't).
EXPECT_TRUE(child->received_notification());
EXPECT_TRUE(child->GetVisibleBounds().IsEmpty());
child->set_received_notification(false);
// Now scroll the contents, this time by enough to make the child visible by
// one pixel.
contents->SetY(contents->y() - 10);
EXPECT_TRUE(child->received_notification());
EXPECT_EQ(1, child->GetVisibleBounds().height());
child->set_received_notification(false);
widget->CloseNow();
}
TEST_F(ViewTest, SetBoundsPaint) {
TestView top_view;
TestView* child_view = new TestView;
top_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100));
top_view.scheduled_paint_rects_.clear();
child_view->SetBoundsRect(gfx::Rect(10, 10, 20, 20));
top_view.AddChildView(child_view);
top_view.scheduled_paint_rects_.clear();
child_view->SetBoundsRect(gfx::Rect(30, 30, 20, 20));
EXPECT_EQ(2U, top_view.scheduled_paint_rects_.size());
// There should be 2 rects, spanning from (10, 10) to (50, 50).
gfx::Rect paint_rect = top_view.scheduled_paint_rects_[0];
paint_rect.Union(top_view.scheduled_paint_rects_[1]);
EXPECT_EQ(gfx::Rect(10, 10, 40, 40), paint_rect);
}
// Assertions around painting and focus gain/lost.
TEST_F(ViewTest, FocusBlurPaints) {
TestView parent_view;
TestView* child_view1 = new TestView; // Owned by |parent_view|.
parent_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100));
child_view1->SetBoundsRect(gfx::Rect(0, 0, 20, 20));
parent_view.AddChildView(child_view1);
parent_view.scheduled_paint_rects_.clear();
child_view1->scheduled_paint_rects_.clear();
// Focus change shouldn't trigger paints.
child_view1->DoFocus();
EXPECT_TRUE(parent_view.scheduled_paint_rects_.empty());
EXPECT_TRUE(child_view1->scheduled_paint_rects_.empty());
child_view1->DoBlur();
EXPECT_TRUE(parent_view.scheduled_paint_rects_.empty());
EXPECT_TRUE(child_view1->scheduled_paint_rects_.empty());
}
// Verifies SetBounds(same bounds) doesn't trigger a SchedulePaint().
TEST_F(ViewTest, SetBoundsSameBoundsDoesntSchedulePaint) {
TestView view;
view.SetBoundsRect(gfx::Rect(0, 0, 100, 100));
view.InvalidateLayout();
view.scheduled_paint_rects_.clear();
view.SetBoundsRect(gfx::Rect(0, 0, 100, 100));
EXPECT_TRUE(view.scheduled_paint_rects_.empty());
}
// Verifies AddChildView() and RemoveChildView() schedule appropriate paints.
TEST_F(ViewTest, AddAndRemoveSchedulePaints) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
// We have to put the View hierarchy into a Widget or no paints will be
// scheduled.
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = viewport_bounds;
widget->Init(params);
widget->GetRootView()->SetBoundsRect(viewport_bounds);
TestView* parent_view = new TestView;
widget->SetContentsView(parent_view);
parent_view->SetBoundsRect(viewport_bounds);
parent_view->scheduled_paint_rects_.clear();
View* child_view = new View;
child_view->SetBoundsRect(gfx::Rect(0, 0, 20, 20));
parent_view->AddChildView(child_view);
ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size());
EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front());
parent_view->scheduled_paint_rects_.clear();
parent_view->RemoveChildView(child_view);
scoped_ptr<View> child_deleter(child_view);
ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size());
EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front());
widget->CloseNow();
}
// Tests conversion methods with a transform.
TEST_F(ViewTest, ConversionsWithTransform) {
TestView top_view;
// View hierarchy used to test scale transforms.
TestView* child = new TestView;
TestView* child_child = new TestView;
// View used to test a rotation transform.
TestView* child_2 = new TestView;
top_view.AddChildView(child);
child->AddChildView(child_child);
top_view.SetBoundsRect(gfx::Rect(0, 0, 1000, 1000));
child->SetBoundsRect(gfx::Rect(7, 19, 500, 500));
gfx::Transform transform;
transform.Scale(3.0, 4.0);
child->SetTransform(transform);
child_child->SetBoundsRect(gfx::Rect(17, 13, 100, 100));
transform.MakeIdentity();
transform.Scale(5.0, 7.0);
child_child->SetTransform(transform);
top_view.AddChildView(child_2);
child_2->SetBoundsRect(gfx::Rect(700, 725, 100, 100));
transform.MakeIdentity();
RotateClockwise(&transform);
child_2->SetTransform(transform);
// Sanity check to make sure basic transforms act as expected.
{
gfx::Transform transform;
transform.Translate(110.0, -110.0);
transform.Scale(100.0, 55.0);
transform.Translate(1.0, 1.0);
// convert to a 3x3 matrix.
const SkMatrix& matrix = transform.matrix();
EXPECT_EQ(210, matrix.getTranslateX());
EXPECT_EQ(-55, matrix.getTranslateY());
EXPECT_EQ(100, matrix.getScaleX());
EXPECT_EQ(55, matrix.getScaleY());
EXPECT_EQ(0, matrix.getSkewX());
EXPECT_EQ(0, matrix.getSkewY());
}
{
gfx::Transform transform;
transform.Translate(1.0, 1.0);
gfx::Transform t2;
t2.Scale(100.0, 55.0);
gfx::Transform t3;
t3.Translate(110.0, -110.0);
transform.ConcatTransform(t2);
transform.ConcatTransform(t3);
// convert to a 3x3 matrix
const SkMatrix& matrix = transform.matrix();
EXPECT_EQ(210, matrix.getTranslateX());
EXPECT_EQ(-55, matrix.getTranslateY());
EXPECT_EQ(100, matrix.getScaleX());
EXPECT_EQ(55, matrix.getScaleY());
EXPECT_EQ(0, matrix.getSkewX());
EXPECT_EQ(0, matrix.getSkewY());
}
// Conversions from child->top and top->child.
{
gfx::Point point(5, 5);
View::ConvertPointToTarget(child, &top_view, &point);
EXPECT_EQ(22, point.x());
EXPECT_EQ(39, point.y());
gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f);
View::ConvertRectToTarget(child, &top_view, &rect);
EXPECT_FLOAT_EQ(22.0f, rect.x());
EXPECT_FLOAT_EQ(39.0f, rect.y());
EXPECT_FLOAT_EQ(30.0f, rect.width());
EXPECT_FLOAT_EQ(80.0f, rect.height());
point.SetPoint(22, 39);
View::ConvertPointToTarget(&top_view, child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
rect.SetRect(22.0f, 39.0f, 30.0f, 80.0f);
View::ConvertRectToTarget(&top_view, child, &rect);
EXPECT_FLOAT_EQ(5.0f, rect.x());
EXPECT_FLOAT_EQ(5.0f, rect.y());
EXPECT_FLOAT_EQ(10.0f, rect.width());
EXPECT_FLOAT_EQ(20.0f, rect.height());
}
// Conversions from child_child->top and top->child_child.
{
gfx::Point point(5, 5);
View::ConvertPointToTarget(child_child, &top_view, &point);
EXPECT_EQ(133, point.x());
EXPECT_EQ(211, point.y());
gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f);
View::ConvertRectToTarget(child_child, &top_view, &rect);
EXPECT_FLOAT_EQ(133.0f, rect.x());
EXPECT_FLOAT_EQ(211.0f, rect.y());
EXPECT_FLOAT_EQ(150.0f, rect.width());
EXPECT_FLOAT_EQ(560.0f, rect.height());
point.SetPoint(133, 211);
View::ConvertPointToTarget(&top_view, child_child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
rect.SetRect(133.0f, 211.0f, 150.0f, 560.0f);
View::ConvertRectToTarget(&top_view, child_child, &rect);
EXPECT_FLOAT_EQ(5.0f, rect.x());
EXPECT_FLOAT_EQ(5.0f, rect.y());
EXPECT_FLOAT_EQ(10.0f, rect.width());
EXPECT_FLOAT_EQ(20.0f, rect.height());
}
// Conversions from child_child->child and child->child_child
{
gfx::Point point(5, 5);
View::ConvertPointToTarget(child_child, child, &point);
EXPECT_EQ(42, point.x());
EXPECT_EQ(48, point.y());
gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f);
View::ConvertRectToTarget(child_child, child, &rect);
EXPECT_FLOAT_EQ(42.0f, rect.x());
EXPECT_FLOAT_EQ(48.0f, rect.y());
EXPECT_FLOAT_EQ(50.0f, rect.width());
EXPECT_FLOAT_EQ(140.0f, rect.height());
point.SetPoint(42, 48);
View::ConvertPointToTarget(child, child_child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
rect.SetRect(42.0f, 48.0f, 50.0f, 140.0f);
View::ConvertRectToTarget(child, child_child, &rect);
EXPECT_FLOAT_EQ(5.0f, rect.x());
EXPECT_FLOAT_EQ(5.0f, rect.y());
EXPECT_FLOAT_EQ(10.0f, rect.width());
EXPECT_FLOAT_EQ(20.0f, rect.height());
}
// Conversions from top_view to child with a value that should be negative.
// This ensures we don't round up with negative numbers.
{
gfx::Point point(6, 18);
View::ConvertPointToTarget(&top_view, child, &point);
EXPECT_EQ(-1, point.x());
EXPECT_EQ(-1, point.y());
float error = 0.01f;
gfx::RectF rect(6.0f, 18.0f, 10.0f, 39.0f);
View::ConvertRectToTarget(&top_view, child, &rect);
EXPECT_NEAR(-0.33f, rect.x(), error);
EXPECT_NEAR(-0.25f, rect.y(), error);
EXPECT_NEAR(3.33f, rect.width(), error);
EXPECT_NEAR(9.75f, rect.height(), error);
}
// Rect conversions from top_view->child_2 and child_2->top_view.
{
gfx::RectF rect(50.0f, 55.0f, 20.0f, 30.0f);
View::ConvertRectToTarget(child_2, &top_view, &rect);
EXPECT_FLOAT_EQ(615.0f, rect.x());
EXPECT_FLOAT_EQ(775.0f, rect.y());
EXPECT_FLOAT_EQ(30.0f, rect.width());
EXPECT_FLOAT_EQ(20.0f, rect.height());
rect.SetRect(615.0f, 775.0f, 30.0f, 20.0f);
View::ConvertRectToTarget(&top_view, child_2, &rect);
EXPECT_FLOAT_EQ(50.0f, rect.x());
EXPECT_FLOAT_EQ(55.0f, rect.y());
EXPECT_FLOAT_EQ(20.0f, rect.width());
EXPECT_FLOAT_EQ(30.0f, rect.height());
}
}
// Tests conversion methods to and from screen coordinates.
TEST_F(ViewTest, ConversionsToFromScreen) {
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
View* child = new View;
widget->GetRootView()->AddChildView(child);
child->SetBounds(10, 10, 100, 200);
gfx::Transform t;
t.Scale(0.5, 0.5);
child->SetTransform(t);
gfx::Point point_in_screen(100, 90);
gfx::Point point_in_child(80,60);
gfx::Point point = point_in_screen;
View::ConvertPointFromScreen(child, &point);
EXPECT_EQ(point_in_child.ToString(), point.ToString());
View::ConvertPointToScreen(child, &point);
EXPECT_EQ(point_in_screen.ToString(), point.ToString());
}
// Tests conversion methods for rectangles.
TEST_F(ViewTest, ConvertRectWithTransform) {
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(params);
View* root = widget->GetRootView();
TestView* v1 = new TestView;
TestView* v2 = new TestView;
root->AddChildView(v1);
v1->AddChildView(v2);
v1->SetBoundsRect(gfx::Rect(10, 10, 500, 500));
v2->SetBoundsRect(gfx::Rect(20, 20, 100, 200));
// |v2| now occupies (30, 30) to (130, 230) in |widget|
gfx::Rect rect(5, 5, 15, 40);
EXPECT_EQ(gfx::Rect(25, 25, 15, 40), v2->ConvertRectToParent(rect));
EXPECT_EQ(gfx::Rect(35, 35, 15, 40), v2->ConvertRectToWidget(rect));
// Rotate |v2|
gfx::Transform t2;
RotateCounterclockwise(&t2);
t2.matrix().set(1, 3, 100.f);
v2->SetTransform(t2);
// |v2| now occupies (30, 30) to (230, 130) in |widget|
EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect));
EXPECT_EQ(gfx::Rect(35, 110, 40, 15), v2->ConvertRectToWidget(rect));
// Scale down |v1|
gfx::Transform t1;
t1.Scale(0.5, 0.5);
v1->SetTransform(t1);
// The rectangle should remain the same for |v1|.
EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect));
// |v2| now occupies (20, 20) to (120, 70) in |widget|
EXPECT_EQ(gfx::Rect(22, 60, 21, 8).ToString(),
v2->ConvertRectToWidget(rect).ToString());
widget->CloseNow();
}
class ObserverView : public View {
public:
ObserverView();
virtual ~ObserverView();
void ResetTestState();
bool has_add_details() const { return has_add_details_; }
bool has_remove_details() const { return has_remove_details_; }
const ViewHierarchyChangedDetails& add_details() const {
return add_details_;
}
const ViewHierarchyChangedDetails& remove_details() const {
return remove_details_;
}
private:
// View:
virtual void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) OVERRIDE;
bool has_add_details_;
bool has_remove_details_;
ViewHierarchyChangedDetails add_details_;
ViewHierarchyChangedDetails remove_details_;
DISALLOW_COPY_AND_ASSIGN(ObserverView);
};
ObserverView::ObserverView()
: has_add_details_(false),
has_remove_details_(false) {
}
ObserverView::~ObserverView() {}
void ObserverView::ResetTestState() {
has_add_details_ = false;
has_remove_details_ = false;
add_details_ = ViewHierarchyChangedDetails();
remove_details_ = ViewHierarchyChangedDetails();
}
void ObserverView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add) {
has_add_details_ = true;
add_details_ = details;
} else {
has_remove_details_ = true;
remove_details_ = details;
}
}
// Verifies that the ViewHierarchyChanged() notification is sent correctly when
// a child view is added or removed to all the views in the hierarchy (up and
// down).
// The tree looks like this:
// v1
// +-- v2
// +-- v3
// +-- v4 (starts here, then get reparented to v1)
TEST_F(ViewTest, ViewHierarchyChanged) {
ObserverView v1;
ObserverView* v3 = new ObserverView();
// Add |v3| to |v2|.
scoped_ptr<ObserverView> v2(new ObserverView());
v2->AddChildView(v3);
// Make sure both |v2| and |v3| receive the ViewHierarchyChanged()
// notification.
EXPECT_TRUE(v2->has_add_details());
EXPECT_FALSE(v2->has_remove_details());
EXPECT_EQ(v2.get(), v2->add_details().parent);
EXPECT_EQ(v3, v2->add_details().child);
EXPECT_EQ(NULL, v2->add_details().move_view);
EXPECT_TRUE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
EXPECT_EQ(v2.get(), v3->add_details().parent);
EXPECT_EQ(v3, v3->add_details().child);
EXPECT_EQ(NULL, v3->add_details().move_view);
// Reset everything to the initial state.
v2->ResetTestState();
v3->ResetTestState();
// Add |v2| to v1.
v1.AddChildView(v2.get());
// Verifies that |v2| is the child view *added* and the parent view is |v1|.
// Make sure all the views (v1, v2, v3) received _that_ information.
EXPECT_TRUE(v1.has_add_details());
EXPECT_FALSE(v1.has_remove_details());
EXPECT_EQ(&v1, v1.add_details().parent);
EXPECT_EQ(v2.get(), v1.add_details().child);
EXPECT_EQ(NULL, v1.add_details().move_view);
EXPECT_TRUE(v2->has_add_details());
EXPECT_FALSE(v2->has_remove_details());
EXPECT_EQ(&v1, v2->add_details().parent);
EXPECT_EQ(v2.get(), v2->add_details().child);
EXPECT_EQ(NULL, v2->add_details().move_view);
EXPECT_TRUE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
EXPECT_EQ(&v1, v3->add_details().parent);
EXPECT_EQ(v2.get(), v3->add_details().child);
EXPECT_EQ(NULL, v3->add_details().move_view);
// Reset everything to the initial state.
v1.ResetTestState();
v2->ResetTestState();
v3->ResetTestState();
// Remove |v2| from |v1|.
v1.RemoveChildView(v2.get());
// Verifies that |v2| is the child view *removed* and the parent view is |v1|.
// Make sure all the views (v1, v2, v3) received _that_ information.
EXPECT_FALSE(v1.has_add_details());
EXPECT_TRUE(v1.has_remove_details());
EXPECT_EQ(&v1, v1.remove_details().parent);
EXPECT_EQ(v2.get(), v1.remove_details().child);
EXPECT_EQ(NULL, v1.remove_details().move_view);
EXPECT_FALSE(v2->has_add_details());
EXPECT_TRUE(v2->has_remove_details());
EXPECT_EQ(&v1, v2->remove_details().parent);
EXPECT_EQ(v2.get(), v2->remove_details().child);
EXPECT_EQ(NULL, v2->remove_details().move_view);
EXPECT_FALSE(v3->has_add_details());
EXPECT_TRUE(v3->has_remove_details());
EXPECT_EQ(&v1, v3->remove_details().parent);
EXPECT_EQ(v3, v3->remove_details().child);
EXPECT_EQ(NULL, v3->remove_details().move_view);
// Verifies notifications when reparenting a view.
ObserverView* v4 = new ObserverView();
// Add |v4| to |v2|.
v2->AddChildView(v4);
// Reset everything to the initial state.
v1.ResetTestState();
v2->ResetTestState();
v3->ResetTestState();
v4->ResetTestState();
// Reparent |v4| to |v1|.
v1.AddChildView(v4);
// Verifies that all views receive the correct information for all the child,
// parent and move views.
// |v1| is the new parent, |v4| is the child for add, |v2| is the old parent.
EXPECT_TRUE(v1.has_add_details());
EXPECT_FALSE(v1.has_remove_details());
EXPECT_EQ(&v1, v1.add_details().parent);
EXPECT_EQ(v4, v1.add_details().child);
EXPECT_EQ(v2.get(), v1.add_details().move_view);
// |v2| is the old parent, |v4| is the child for remove, |v1| is the new
// parent.
EXPECT_FALSE(v2->has_add_details());
EXPECT_TRUE(v2->has_remove_details());
EXPECT_EQ(v2.get(), v2->remove_details().parent);
EXPECT_EQ(v4, v2->remove_details().child);
EXPECT_EQ(&v1, v2->remove_details().move_view);
// |v3| is not impacted by this operation, and hence receives no notification.
EXPECT_FALSE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
// |v4| is the reparented child, so it receives notifications for the remove
// and then the add. |v2| is its old parent, |v1| is its new parent.
EXPECT_TRUE(v4->has_remove_details());
EXPECT_TRUE(v4->has_add_details());
EXPECT_EQ(v2.get(), v4->remove_details().parent);
EXPECT_EQ(&v1, v4->add_details().parent);
EXPECT_EQ(v4, v4->add_details().child);
EXPECT_EQ(v4, v4->remove_details().child);
EXPECT_EQ(&v1, v4->remove_details().move_view);
EXPECT_EQ(v2.get(), v4->add_details().move_view);
}
// Verifies if the child views added under the root are all deleted when calling
// RemoveAllChildViews.
// The tree looks like this:
// root
// +-- child1
// +-- foo
// +-- bar0
// +-- bar1
// +-- bar2
// +-- child2
// +-- child3
TEST_F(ViewTest, RemoveAllChildViews) {
View root;
View* child1 = new View;
root.AddChildView(child1);
for (int i = 0; i < 2; ++i)
root.AddChildView(new View);
View* foo = new View;
child1->AddChildView(foo);
// Add some nodes to |foo|.
for (int i = 0; i < 3; ++i)
foo->AddChildView(new View);
EXPECT_EQ(3, root.child_count());
EXPECT_EQ(1, child1->child_count());
EXPECT_EQ(3, foo->child_count());
// Now remove all child views from root.
root.RemoveAllChildViews(true);
EXPECT_EQ(0, root.child_count());
EXPECT_FALSE(root.has_children());
}
TEST_F(ViewTest, Contains) {
View v1;
View* v2 = new View;
View* v3 = new View;
v1.AddChildView(v2);
v2->AddChildView(v3);
EXPECT_FALSE(v1.Contains(NULL));
EXPECT_TRUE(v1.Contains(&v1));
EXPECT_TRUE(v1.Contains(v2));
EXPECT_TRUE(v1.Contains(v3));
EXPECT_FALSE(v2->Contains(NULL));
EXPECT_TRUE(v2->Contains(v2));
EXPECT_FALSE(v2->Contains(&v1));
EXPECT_TRUE(v2->Contains(v3));
EXPECT_FALSE(v3->Contains(NULL));
EXPECT_TRUE(v3->Contains(v3));
EXPECT_FALSE(v3->Contains(&v1));
EXPECT_FALSE(v3->Contains(v2));
}
// Verifies if GetIndexOf() returns the correct index for the specified child
// view.
// The tree looks like this:
// root
// +-- child1
// +-- foo1
// +-- child2
TEST_F(ViewTest, GetIndexOf) {
View root;
View* child1 = new View;
root.AddChildView(child1);
View* child2 = new View;
root.AddChildView(child2);
View* foo1 = new View;
child1->AddChildView(foo1);
EXPECT_EQ(-1, root.GetIndexOf(NULL));
EXPECT_EQ(-1, root.GetIndexOf(&root));
EXPECT_EQ(0, root.GetIndexOf(child1));
EXPECT_EQ(1, root.GetIndexOf(child2));
EXPECT_EQ(-1, root.GetIndexOf(foo1));
EXPECT_EQ(-1, child1->GetIndexOf(NULL));
EXPECT_EQ(-1, child1->GetIndexOf(&root));
EXPECT_EQ(-1, child1->GetIndexOf(child1));
EXPECT_EQ(-1, child1->GetIndexOf(child2));
EXPECT_EQ(0, child1->GetIndexOf(foo1));
EXPECT_EQ(-1, child2->GetIndexOf(NULL));
EXPECT_EQ(-1, child2->GetIndexOf(&root));
EXPECT_EQ(-1, child2->GetIndexOf(child2));
EXPECT_EQ(-1, child2->GetIndexOf(child1));
EXPECT_EQ(-1, child2->GetIndexOf(foo1));
}
// Verifies that the child views can be reordered correctly.
TEST_F(ViewTest, ReorderChildren) {
View root;
View* child = new View();
root.AddChildView(child);
View* foo1 = new View();
child->AddChildView(foo1);
View* foo2 = new View();
child->AddChildView(foo2);
View* foo3 = new View();
child->AddChildView(foo3);
foo1->SetFocusable(true);
foo2->SetFocusable(true);
foo3->SetFocusable(true);
ASSERT_EQ(0, child->GetIndexOf(foo1));
ASSERT_EQ(1, child->GetIndexOf(foo2));
ASSERT_EQ(2, child->GetIndexOf(foo3));
ASSERT_EQ(foo2, foo1->GetNextFocusableView());
ASSERT_EQ(foo3, foo2->GetNextFocusableView());
ASSERT_EQ(NULL, foo3->GetNextFocusableView());
// Move |foo2| at the end.
child->ReorderChildView(foo2, -1);
ASSERT_EQ(0, child->GetIndexOf(foo1));
ASSERT_EQ(1, child->GetIndexOf(foo3));
ASSERT_EQ(2, child->GetIndexOf(foo2));
ASSERT_EQ(foo3, foo1->GetNextFocusableView());
ASSERT_EQ(foo2, foo3->GetNextFocusableView());
ASSERT_EQ(NULL, foo2->GetNextFocusableView());
// Move |foo1| at the end.
child->ReorderChildView(foo1, -1);
ASSERT_EQ(0, child->GetIndexOf(foo3));
ASSERT_EQ(1, child->GetIndexOf(foo2));
ASSERT_EQ(2, child->GetIndexOf(foo1));
ASSERT_EQ(NULL, foo1->GetNextFocusableView());
ASSERT_EQ(foo2, foo1->GetPreviousFocusableView());
ASSERT_EQ(foo2, foo3->GetNextFocusableView());
ASSERT_EQ(foo1, foo2->GetNextFocusableView());
// Move |foo2| to the front.
child->ReorderChildView(foo2, 0);
ASSERT_EQ(0, child->GetIndexOf(foo2));
ASSERT_EQ(1, child->GetIndexOf(foo3));
ASSERT_EQ(2, child->GetIndexOf(foo1));
ASSERT_EQ(NULL, foo1->GetNextFocusableView());
ASSERT_EQ(foo3, foo1->GetPreviousFocusableView());
ASSERT_EQ(foo3, foo2->GetNextFocusableView());
ASSERT_EQ(foo1, foo3->GetNextFocusableView());
}
// Verifies that GetViewByID returns the correctly child view from the specified
// ID.
// The tree looks like this:
// v1
// +-- v2
// +-- v3
// +-- v4
TEST_F(ViewTest, GetViewByID) {
View v1;
const int kV1ID = 1;
v1.set_id(kV1ID);
View v2;
const int kV2ID = 2;
v2.set_id(kV2ID);
View v3;
const int kV3ID = 3;
v3.set_id(kV3ID);
View v4;
const int kV4ID = 4;
v4.set_id(kV4ID);
const int kV5ID = 5;
v1.AddChildView(&v2);
v2.AddChildView(&v3);
v2.AddChildView(&v4);
EXPECT_EQ(&v1, v1.GetViewByID(kV1ID));
EXPECT_EQ(&v2, v1.GetViewByID(kV2ID));
EXPECT_EQ(&v4, v1.GetViewByID(kV4ID));
EXPECT_EQ(NULL, v1.GetViewByID(kV5ID)); // No V5 exists.
EXPECT_EQ(NULL, v2.GetViewByID(kV1ID)); // It can get only from child views.
const int kGroup = 1;
v3.SetGroup(kGroup);
v4.SetGroup(kGroup);
View::Views views;
v1.GetViewsInGroup(kGroup, &views);
EXPECT_EQ(2U, views.size());
View::Views::const_iterator i(std::find(views.begin(), views.end(), &v3));
EXPECT_NE(views.end(), i);
i = std::find(views.begin(), views.end(), &v4);
EXPECT_NE(views.end(), i);
}
TEST_F(ViewTest, AddExistingChild) {
View v1, v2, v3;
v1.AddChildView(&v2);
v1.AddChildView(&v3);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
// Check that there's no change in order when adding at same index.
v1.AddChildViewAt(&v2, 0);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
v1.AddChildViewAt(&v3, 1);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
// Add it at a different index and check for change in order.
v1.AddChildViewAt(&v2, 1);
EXPECT_EQ(1, v1.GetIndexOf(&v2));
EXPECT_EQ(0, v1.GetIndexOf(&v3));
v1.AddChildViewAt(&v2, 0);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
// Check that calling |AddChildView()| does not change the order.
v1.AddChildView(&v2);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
v1.AddChildView(&v3);
EXPECT_EQ(0, v1.GetIndexOf(&v2));
EXPECT_EQ(1, v1.GetIndexOf(&v3));
}
////////////////////////////////////////////////////////////////////////////////
// Layers
////////////////////////////////////////////////////////////////////////////////
namespace {
// Test implementation of LayerAnimator.
class TestLayerAnimator : public ui::LayerAnimator {
public:
TestLayerAnimator();
const gfx::Rect& last_bounds() const { return last_bounds_; }
// LayerAnimator.
virtual void SetBounds(const gfx::Rect& bounds) OVERRIDE;
protected:
virtual ~TestLayerAnimator() { }
private:
gfx::Rect last_bounds_;
DISALLOW_COPY_AND_ASSIGN(TestLayerAnimator);
};
TestLayerAnimator::TestLayerAnimator()
: ui::LayerAnimator(base::TimeDelta::FromMilliseconds(0)) {
}
void TestLayerAnimator::SetBounds(const gfx::Rect& bounds) {
last_bounds_ = bounds;
}
} // namespace
class ViewLayerTest : public ViewsTestBase {
public:
ViewLayerTest() : widget_(NULL) {}
virtual ~ViewLayerTest() {
}
// Returns the Layer used by the RootView.
ui::Layer* GetRootLayer() {
return widget()->GetLayer();
}
virtual void SetUp() OVERRIDE {
ViewTest::SetUp();
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 200, 200);
widget_->Init(params);
widget_->Show();
widget_->GetRootView()->SetBounds(0, 0, 200, 200);
}
virtual void TearDown() OVERRIDE {
widget_->CloseNow();
ViewsTestBase::TearDown();
}
Widget* widget() { return widget_; }
private:
Widget* widget_;
};
TEST_F(ViewLayerTest, LayerToggling) {
// Because we lazily create textures the calls to DrawTree are necessary to
// ensure we trigger creation of textures.
ui::Layer* root_layer = widget()->GetLayer();
View* content_view = new View;
widget()->SetContentsView(content_view);
// Create v1, give it a bounds and verify everything is set up correctly.
View* v1 = new View;
v1->SetPaintToLayer(true);
EXPECT_TRUE(v1->layer() != NULL);
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
content_view->AddChildView(v1);
ASSERT_TRUE(v1->layer() != NULL);
EXPECT_EQ(root_layer, v1->layer()->parent());
EXPECT_EQ(gfx::Rect(20, 30, 140, 150), v1->layer()->bounds());
// Create v2 as a child of v1 and do basic assertion testing.
View* v2 = new View;
v1->AddChildView(v2);
EXPECT_TRUE(v2->layer() == NULL);
v2->SetBoundsRect(gfx::Rect(10, 20, 30, 40));
v2->SetPaintToLayer(true);
ASSERT_TRUE(v2->layer() != NULL);
EXPECT_EQ(v1->layer(), v2->layer()->parent());
EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds());
// Turn off v1s layer. v2 should still have a layer but its parent should have
// changed.
v1->SetPaintToLayer(false);
EXPECT_TRUE(v1->layer() == NULL);
EXPECT_TRUE(v2->layer() != NULL);
EXPECT_EQ(root_layer, v2->layer()->parent());
ASSERT_EQ(1u, root_layer->children().size());
EXPECT_EQ(root_layer->children()[0], v2->layer());
// The bounds of the layer should have changed to be relative to the root view
// now.
EXPECT_EQ(gfx::Rect(30, 50, 30, 40), v2->layer()->bounds());
// Make v1 have a layer again and verify v2s layer is wired up correctly.
gfx::Transform transform;
transform.Scale(2.0, 2.0);
v1->SetTransform(transform);
EXPECT_TRUE(v1->layer() != NULL);
EXPECT_TRUE(v2->layer() != NULL);
EXPECT_EQ(root_layer, v1->layer()->parent());
EXPECT_EQ(v1->layer(), v2->layer()->parent());
ASSERT_EQ(1u, root_layer->children().size());
EXPECT_EQ(root_layer->children()[0], v1->layer());
ASSERT_EQ(1u, v1->layer()->children().size());
EXPECT_EQ(v1->layer()->children()[0], v2->layer());
EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds());
}
// Verifies turning on a layer wires up children correctly.
TEST_F(ViewLayerTest, NestedLayerToggling) {
View* content_view = new View;
widget()->SetContentsView(content_view);
// Create v1, give it a bounds and verify everything is set up correctly.
View* v1 = new View;
content_view->AddChildView(v1);
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
View* v2 = new View;
v1->AddChildView(v2);
View* v3 = new View;
v3->SetPaintToLayer(true);
v2->AddChildView(v3);
ASSERT_TRUE(v3->layer() != NULL);
// At this point we have v1-v2-v3. v3 has a layer, v1 and v2 don't.
v1->SetPaintToLayer(true);
EXPECT_EQ(v1->layer(), v3->layer()->parent());
}
TEST_F(ViewLayerTest, LayerAnimator) {
View* content_view = new View;
widget()->SetContentsView(content_view);
View* v1 = new View;
content_view->AddChildView(v1);
v1->SetPaintToLayer(true);
EXPECT_TRUE(v1->layer() != NULL);
TestLayerAnimator* animator = new TestLayerAnimator();
v1->layer()->SetAnimator(animator);
gfx::Rect bounds(1, 2, 3, 4);
v1->SetBoundsRect(bounds);
EXPECT_EQ(bounds, animator->last_bounds());
// TestLayerAnimator doesn't update the layer.
EXPECT_NE(bounds, v1->layer()->bounds());
}
// Verifies the bounds of a layer are updated if the bounds of ancestor that
// doesn't have a layer change.
TEST_F(ViewLayerTest, BoundsChangeWithLayer) {
View* content_view = new View;
widget()->SetContentsView(content_view);
View* v1 = new View;
content_view->AddChildView(v1);
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
View* v2 = new View;
v2->SetBoundsRect(gfx::Rect(10, 11, 40, 50));
v1->AddChildView(v2);
v2->SetPaintToLayer(true);
ASSERT_TRUE(v2->layer() != NULL);
EXPECT_EQ(gfx::Rect(30, 41, 40, 50), v2->layer()->bounds());
v1->SetPosition(gfx::Point(25, 36));
EXPECT_EQ(gfx::Rect(35, 47, 40, 50), v2->layer()->bounds());
v2->SetPosition(gfx::Point(11, 12));
EXPECT_EQ(gfx::Rect(36, 48, 40, 50), v2->layer()->bounds());
// Bounds of the layer should change even if the view is not invisible.
v1->SetVisible(false);
v1->SetPosition(gfx::Point(20, 30));
EXPECT_EQ(gfx::Rect(31, 42, 40, 50), v2->layer()->bounds());
v2->SetVisible(false);
v2->SetBoundsRect(gfx::Rect(10, 11, 20, 30));
EXPECT_EQ(gfx::Rect(30, 41, 20, 30), v2->layer()->bounds());
}
// Make sure layers are positioned correctly in RTL.
TEST_F(ViewLayerTest, BoundInRTL) {
std::string locale = l10n_util::GetApplicationLocale(std::string());
base::i18n::SetICUDefaultLocale("he");
View* view = new View;
widget()->SetContentsView(view);
int content_width = view->width();
// |v1| is initially not attached to anything. So its layer will have the same
// bounds as the view.
View* v1 = new View;
v1->SetPaintToLayer(true);
v1->SetBounds(10, 10, 20, 10);
EXPECT_EQ(gfx::Rect(10, 10, 20, 10),
v1->layer()->bounds());
// Once |v1| is attached to the widget, its layer will get RTL-appropriate
// bounds.
view->AddChildView(v1);
EXPECT_EQ(gfx::Rect(content_width - 30, 10, 20, 10),
v1->layer()->bounds());
gfx::Rect l1bounds = v1->layer()->bounds();
// Now attach a View to the widget first, then create a layer for it. Make
// sure the bounds are correct.
View* v2 = new View;
v2->SetBounds(50, 10, 30, 10);
EXPECT_FALSE(v2->layer());
view->AddChildView(v2);
v2->SetPaintToLayer(true);
EXPECT_EQ(gfx::Rect(content_width - 80, 10, 30, 10),
v2->layer()->bounds());
gfx::Rect l2bounds = v2->layer()->bounds();
view->SetPaintToLayer(true);
EXPECT_EQ(l1bounds, v1->layer()->bounds());
EXPECT_EQ(l2bounds, v2->layer()->bounds());
// Move one of the views. Make sure the layer is positioned correctly
// afterwards.
v1->SetBounds(v1->x() - 5, v1->y(), v1->width(), v1->height());
l1bounds.set_x(l1bounds.x() + 5);
EXPECT_EQ(l1bounds, v1->layer()->bounds());
view->SetPaintToLayer(false);
EXPECT_EQ(l1bounds, v1->layer()->bounds());
EXPECT_EQ(l2bounds, v2->layer()->bounds());
// Move a view again.
v2->SetBounds(v2->x() + 5, v2->y(), v2->width(), v2->height());
l2bounds.set_x(l2bounds.x() - 5);
EXPECT_EQ(l2bounds, v2->layer()->bounds());
// Reset locale.
base::i18n::SetICUDefaultLocale(locale);
}
// Makes sure a transform persists after toggling the visibility.
TEST_F(ViewLayerTest, ToggleVisibilityWithTransform) {
View* view = new View;
gfx::Transform transform;
transform.Scale(2.0, 2.0);
view->SetTransform(transform);
widget()->SetContentsView(view);
EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0));
view->SetVisible(false);
EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0));
view->SetVisible(true);
EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0));
}
// Verifies a transform persists after removing/adding a view with a transform.
TEST_F(ViewLayerTest, ResetTransformOnLayerAfterAdd) {
View* view = new View;
gfx::Transform transform;
transform.Scale(2.0, 2.0);
view->SetTransform(transform);
widget()->SetContentsView(view);
EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0));
ASSERT_TRUE(view->layer() != NULL);
EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0));
View* parent = view->parent();
parent->RemoveChildView(view);
parent->AddChildView(view);
EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0));
ASSERT_TRUE(view->layer() != NULL);
EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0));
}
// Makes sure that layer visibility is correct after toggling View visibility.
TEST_F(ViewLayerTest, ToggleVisibilityWithLayer) {
View* content_view = new View;
widget()->SetContentsView(content_view);
// The view isn't attached to a widget or a parent view yet. But it should
// still have a layer, but the layer should not be attached to the root
// layer.
View* v1 = new View;
v1->SetPaintToLayer(true);
EXPECT_TRUE(v1->layer());
EXPECT_FALSE(LayerIsAncestor(widget()->GetCompositor()->root_layer(),
v1->layer()));
// Once the view is attached to a widget, its layer should be attached to the
// root layer and visible.
content_view->AddChildView(v1);
EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(),
v1->layer()));
EXPECT_TRUE(v1->layer()->IsDrawn());
v1->SetVisible(false);
EXPECT_FALSE(v1->layer()->IsDrawn());
v1->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsDrawn());
widget()->Hide();
EXPECT_FALSE(v1->layer()->IsDrawn());
widget()->Show();
EXPECT_TRUE(v1->layer()->IsDrawn());
}
// Tests that the layers in the subtree are orphaned after a View is removed
// from the parent.
TEST_F(ViewLayerTest, OrphanLayerAfterViewRemove) {
View* content_view = new View;
widget()->SetContentsView(content_view);
View* v1 = new View;
content_view->AddChildView(v1);
View* v2 = new View;
v1->AddChildView(v2);
v2->SetPaintToLayer(true);
EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(),
v2->layer()));
EXPECT_TRUE(v2->layer()->IsDrawn());
content_view->RemoveChildView(v1);
EXPECT_FALSE(LayerIsAncestor(widget()->GetCompositor()->root_layer(),
v2->layer()));
// Reparent |v2|.
content_view->AddChildView(v2);
delete v1;
v1 = NULL;
EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(),
v2->layer()));
EXPECT_TRUE(v2->layer()->IsDrawn());
}
class PaintTrackingView : public View {
public:
PaintTrackingView() : painted_(false) {
}
bool painted() const { return painted_; }
void set_painted(bool value) { painted_ = value; }
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
painted_ = true;
}
private:
bool painted_;
DISALLOW_COPY_AND_ASSIGN(PaintTrackingView);
};
// Makes sure child views with layers aren't painted when paint starts at an
// ancestor.
TEST_F(ViewLayerTest, DontPaintChildrenWithLayers) {
PaintTrackingView* content_view = new PaintTrackingView;
widget()->SetContentsView(content_view);
content_view->SetPaintToLayer(true);
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
GetRootLayer()->SchedulePaint(gfx::Rect(0, 0, 10, 10));
content_view->set_painted(false);
// content_view no longer has a dirty rect. Paint from the root and make sure
// PaintTrackingView isn't painted.
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_FALSE(content_view->painted());
// Make content_view have a dirty rect, paint the layers and make sure
// PaintTrackingView is painted.
content_view->layer()->SchedulePaint(gfx::Rect(0, 0, 10, 10));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_TRUE(content_view->painted());
}
// Tests that the visibility of child layers are updated correctly when a View's
// visibility changes.
TEST_F(ViewLayerTest, VisibilityChildLayers) {
View* v1 = new View;
v1->SetPaintToLayer(true);
widget()->SetContentsView(v1);
View* v2 = new View;
v1->AddChildView(v2);
View* v3 = new View;
v2->AddChildView(v3);
v3->SetVisible(false);
View* v4 = new View;
v4->SetPaintToLayer(true);
v3->AddChildView(v4);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_FALSE(v4->layer()->IsDrawn());
v2->SetVisible(false);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_FALSE(v4->layer()->IsDrawn());
v2->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_FALSE(v4->layer()->IsDrawn());
v2->SetVisible(false);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_FALSE(v4->layer()->IsDrawn());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
v3->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_FALSE(v4->layer()->IsDrawn());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
// Reparent |v3| to |v1|.
v1->AddChildView(v3);
EXPECT_TRUE(v1->layer()->IsDrawn());
EXPECT_TRUE(v4->layer()->IsDrawn());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
}
// This test creates a random View tree, and then randomly reorders child views,
// reparents views etc. Unrelated changes can appear to break this test. So
// marking this as FLAKY.
TEST_F(ViewLayerTest, DISABLED_ViewLayerTreesInSync) {
View* content = new View;
content->SetPaintToLayer(true);
widget()->SetContentsView(content);
widget()->Show();
ConstructTree(content, 5);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
}
// Verifies when views are reordered the layer is also reordered. The widget is
// providing the parent layer.
TEST_F(ViewLayerTest, ReorderUnderWidget) {
View* content = new View;
widget()->SetContentsView(content);
View* c1 = new View;
c1->SetPaintToLayer(true);
content->AddChildView(c1);
View* c2 = new View;
c2->SetPaintToLayer(true);
content->AddChildView(c2);
ui::Layer* parent_layer = c1->layer()->parent();
ASSERT_TRUE(parent_layer);
ASSERT_EQ(2u, parent_layer->children().size());
EXPECT_EQ(c1->layer(), parent_layer->children()[0]);
EXPECT_EQ(c2->layer(), parent_layer->children()[1]);
// Move c1 to the front. The layers should have moved too.
content->ReorderChildView(c1, -1);
EXPECT_EQ(c1->layer(), parent_layer->children()[1]);
EXPECT_EQ(c2->layer(), parent_layer->children()[0]);
}
// Verifies that the layer of a view can be acquired properly.
TEST_F(ViewLayerTest, AcquireLayer) {
View* content = new View;
widget()->SetContentsView(content);
scoped_ptr<View> c1(new View);
c1->SetPaintToLayer(true);
EXPECT_TRUE(c1->layer());
content->AddChildView(c1.get());
scoped_ptr<ui::Layer> layer(c1->AcquireLayer());
EXPECT_EQ(layer.get(), c1->layer());
scoped_ptr<ui::Layer> layer2(c1->RecreateLayer());
EXPECT_NE(c1->layer(), layer2.get());
// Destroy view before destroying layer.
c1.reset();
}
// Verify the z-order of the layers as a result of calling RecreateLayer().
TEST_F(ViewLayerTest, RecreateLayerZOrder) {
scoped_ptr<View> v(new View());
v->SetPaintToLayer(true);
View* v1 = new View();
v1->SetPaintToLayer(true);
v->AddChildView(v1);
View* v2 = new View();
v2->SetPaintToLayer(true);
v->AddChildView(v2);
// Test the initial z-order.
const std::vector<ui::Layer*>& child_layers_pre = v->layer()->children();
ASSERT_EQ(2u, child_layers_pre.size());
EXPECT_EQ(v1->layer(), child_layers_pre[0]);
EXPECT_EQ(v2->layer(), child_layers_pre[1]);
scoped_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer());
// Test the new layer order. We expect: |v1| |v1_old_layer| |v2|.
// for |v1| and |v2|.
const std::vector<ui::Layer*>& child_layers_post = v->layer()->children();
ASSERT_EQ(3u, child_layers_post.size());
EXPECT_EQ(v1->layer(), child_layers_post[0]);
EXPECT_EQ(v1_old_layer, child_layers_post[1]);
EXPECT_EQ(v2->layer(), child_layers_post[2]);
}
// Verify the z-order of the layers as a result of calling RecreateLayer when
// the widget is the parent with the layer.
TEST_F(ViewLayerTest, RecreateLayerZOrderWidgetParent) {
View* v = new View();
widget()->SetContentsView(v);
View* v1 = new View();
v1->SetPaintToLayer(true);
v->AddChildView(v1);
View* v2 = new View();
v2->SetPaintToLayer(true);
v->AddChildView(v2);
ui::Layer* root_layer = GetRootLayer();
// Test the initial z-order.
const std::vector<ui::Layer*>& child_layers_pre = root_layer->children();
ASSERT_EQ(2u, child_layers_pre.size());
EXPECT_EQ(v1->layer(), child_layers_pre[0]);
EXPECT_EQ(v2->layer(), child_layers_pre[1]);
scoped_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer());
// Test the new layer order. We expect: |v1| |v1_old_layer| |v2|.
const std::vector<ui::Layer*>& child_layers_post = root_layer->children();
ASSERT_EQ(3u, child_layers_post.size());
EXPECT_EQ(v1->layer(), child_layers_post[0]);
EXPECT_EQ(v1_old_layer, child_layers_post[1]);
EXPECT_EQ(v2->layer(), child_layers_post[2]);
}
// Verifies RecreateLayer() moves all Layers over, even those that don't have
// a View.
TEST_F(ViewLayerTest, RecreateLayerMovesNonViewChildren) {
View v;
v.SetPaintToLayer(true);
View child;
child.SetPaintToLayer(true);
v.AddChildView(&child);
ASSERT_TRUE(v.layer() != NULL);
ASSERT_EQ(1u, v.layer()->children().size());
EXPECT_EQ(v.layer()->children()[0], child.layer());
ui::Layer layer(ui::LAYER_NOT_DRAWN);
v.layer()->Add(&layer);
v.layer()->StackAtBottom(&layer);
scoped_ptr<ui::Layer> old_layer(v.RecreateLayer());
// All children should be moved from old layer to new layer.
ASSERT_TRUE(old_layer.get() != NULL);
EXPECT_TRUE(old_layer->children().empty());
// And new layer should have the two children.
ASSERT_TRUE(v.layer() != NULL);
ASSERT_EQ(2u, v.layer()->children().size());
EXPECT_EQ(v.layer()->children()[0], &layer);
EXPECT_EQ(v.layer()->children()[1], child.layer());
}
class BoundsTreeTestView : public View {
public:
BoundsTreeTestView() {}
virtual void PaintChildren(gfx::Canvas* canvas,
const CullSet& cull_set) OVERRIDE {
// Save out a copy of the cull_set before calling the base implementation.
last_cull_set_.clear();
if (cull_set.cull_set_) {
for (base::hash_set<intptr_t>::iterator it = cull_set.cull_set_->begin();
it != cull_set.cull_set_->end();
++it) {
last_cull_set_.insert(reinterpret_cast<View*>(*it));
}
}
View::PaintChildren(canvas, cull_set);
}
std::set<View*> last_cull_set_;
};
TEST_F(ViewLayerTest, BoundsTreePaintUpdatesCullSet) {
BoundsTreeTestView* test_view = new BoundsTreeTestView;
widget()->SetContentsView(test_view);
View* v1 = new View();
v1->SetBoundsRect(gfx::Rect(10, 15, 150, 151));
test_view->AddChildView(v1);
View* v2 = new View();
v2->SetBoundsRect(gfx::Rect(20, 33, 40, 50));
v1->AddChildView(v2);
// Schedule a full-view paint to get everyone's rectangles updated.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Now we have test_view - v1 - v2. Damage to only test_view should only
// return root_view and test_view.
test_view->SchedulePaintInRect(gfx::Rect(0, 0, 1, 1));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_EQ(2U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
// Damage to v1 only should only return root_view, test_view, and v1.
test_view->SchedulePaintInRect(gfx::Rect(11, 16, 1, 1));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_EQ(3U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v1));
// A Damage rect inside v2 should get all 3 views back in the |last_cull_set_|
// on call to TestView::Paint(), along with the widget root view.
test_view->SchedulePaintInRect(gfx::Rect(31, 49, 1, 1));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_EQ(4U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v1));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v2));
}
TEST_F(ViewLayerTest, BoundsTreeSetBoundsChangesCullSet) {
BoundsTreeTestView* test_view = new BoundsTreeTestView;
widget()->SetContentsView(test_view);
View* v1 = new View;
v1->SetBoundsRect(gfx::Rect(5, 6, 100, 101));
test_view->AddChildView(v1);
View* v2 = new View;
v2->SetBoundsRect(gfx::Rect(20, 33, 40, 50));
v1->AddChildView(v2);
// Schedule a full-view paint to get everyone's rectangles updated.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Move v1 to a new origin out of the way of our next query.
v1->SetBoundsRect(gfx::Rect(50, 60, 100, 101));
// The move will force a repaint.
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Schedule a paint with damage rect where v1 used to be.
test_view->SchedulePaintInRect(gfx::Rect(5, 6, 10, 11));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Should only have picked up root_view and test_view.
EXPECT_EQ(2U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
}
TEST_F(ViewLayerTest, BoundsTreeLayerChangeMakesNewTree) {
BoundsTreeTestView* test_view = new BoundsTreeTestView;
widget()->SetContentsView(test_view);
View* v1 = new View;
v1->SetBoundsRect(gfx::Rect(5, 10, 15, 20));
test_view->AddChildView(v1);
View* v2 = new View;
v2->SetBoundsRect(gfx::Rect(1, 2, 3, 4));
v1->AddChildView(v2);
// Schedule a full-view paint to get everyone's rectangles updated.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Set v1 to paint to its own layer, it should remove itself from the
// test_view heiarchy and no longer intersect with damage rects in that cull
// set.
v1->SetPaintToLayer(true);
// Schedule another full-view paint.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// v1 and v2 should no longer be present in the test_view cull_set.
EXPECT_EQ(2U, test_view->last_cull_set_.size());
EXPECT_EQ(0U, test_view->last_cull_set_.count(v1));
EXPECT_EQ(0U, test_view->last_cull_set_.count(v2));
// Now set v1 back to not painting to a layer.
v1->SetPaintToLayer(false);
// Schedule another full-view paint.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// We should be back to the full cull set including v1 and v2.
EXPECT_EQ(4U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v1));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v2));
}
TEST_F(ViewLayerTest, BoundsTreeRemoveChildRemovesBounds) {
BoundsTreeTestView* test_view = new BoundsTreeTestView;
widget()->SetContentsView(test_view);
View* v1 = new View;
v1->SetBoundsRect(gfx::Rect(5, 10, 15, 20));
test_view->AddChildView(v1);
View* v2 = new View;
v2->SetBoundsRect(gfx::Rect(1, 2, 3, 4));
v1->AddChildView(v2);
// Schedule a full-view paint to get everyone's rectangles updated.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Now remove v1 from the root view.
test_view->RemoveChildView(v1);
// Schedule another full-view paint.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// v1 and v2 should no longer be present in the test_view cull_set.
EXPECT_EQ(2U, test_view->last_cull_set_.size());
EXPECT_EQ(0U, test_view->last_cull_set_.count(v1));
EXPECT_EQ(0U, test_view->last_cull_set_.count(v2));
// View v1 and v2 are no longer part of view hierarchy and therefore won't be
// deleted with that hierarchy.
delete v1;
}
TEST_F(ViewLayerTest, BoundsTreeMoveViewMovesBounds) {
BoundsTreeTestView* test_view = new BoundsTreeTestView;
widget()->SetContentsView(test_view);
// Build hierarchy v1 - v2 - v3.
View* v1 = new View;
v1->SetBoundsRect(gfx::Rect(20, 30, 150, 160));
test_view->AddChildView(v1);
View* v2 = new View;
v2->SetBoundsRect(gfx::Rect(5, 10, 40, 50));
v1->AddChildView(v2);
View* v3 = new View;
v3->SetBoundsRect(gfx::Rect(1, 2, 3, 4));
v2->AddChildView(v3);
// Schedule a full-view paint and ensure all views are present in the cull.
test_view->SchedulePaintInRect(test_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
EXPECT_EQ(5U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v1));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v2));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v3));
// Build an unrelated view hierarchy and move v2 in to it.
scoped_ptr<Widget> test_widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(10, 10, 500, 500);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
test_widget->Init(params);
test_widget->Show();
BoundsTreeTestView* widget_view = new BoundsTreeTestView;
test_widget->SetContentsView(widget_view);
widget_view->AddChildView(v2);
// Now schedule full-view paints in both widgets.
test_view->SchedulePaintInRect(test_view->bounds());
widget_view->SchedulePaintInRect(widget_view->bounds());
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor());
// Only v1 should be present in the first cull set.
EXPECT_EQ(3U, test_view->last_cull_set_.size());
EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView()));
EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view));
EXPECT_EQ(1U, test_view->last_cull_set_.count(v1));
// We should find v2 and v3 in the widget_view cull_set.
EXPECT_EQ(4U, widget_view->last_cull_set_.size());
EXPECT_EQ(1U, widget_view->last_cull_set_.count(test_widget->GetRootView()));
EXPECT_EQ(1U, widget_view->last_cull_set_.count(widget_view));
EXPECT_EQ(1U, widget_view->last_cull_set_.count(v2));
EXPECT_EQ(1U, widget_view->last_cull_set_.count(v3));
}
TEST_F(ViewTest, FocusableAssertions) {
// View subclasses may change insets based on whether they are focusable,
// which effects the preferred size. To avoid preferred size changing around
// these Views need to key off the last value set to SetFocusable(), not
// whether the View is focusable right now. For this reason it's important
// that focusable() return the last value passed to SetFocusable and not
// whether the View is focusable right now.
TestView view;
view.SetFocusable(true);
EXPECT_TRUE(view.focusable());
view.SetEnabled(false);
EXPECT_TRUE(view.focusable());
view.SetFocusable(false);
EXPECT_FALSE(view.focusable());
}
// Creates a widget of TYPE_CONTROL.
// The caller takes ownership of the returned widget.
Widget* CreateControlWidget(aura::Window* parent, const gfx::Rect& bounds) {
Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
params.parent = parent;
params.bounds = bounds;
Widget* widget = new Widget();
widget->Init(params);
return widget;
}
// Returns a view with a layer with the passed in |bounds| and |layer_name|.
// The caller takes ownership of the returned view.
View* CreateViewWithLayer(const gfx::Rect& bounds,
const char* layer_name) {
View* view = new View();
view->SetBoundsRect(bounds);
view->SetPaintToLayer(true);
view->layer()->set_name(layer_name);
return view;
}
// Test that RecreateWindowLayers() recreates the layers for all child windows
// and all child views and that the z-order of the recreated layers matches that
// of the original layers.
// Test hierarchy:
// w1
// +-- v1
// +-- v2 (no layer)
// +-- v3 (no layer)
// +-- v4
// +-- w2
// +-- v5
// +-- v6
// +-- v7
// +-- v8
// +-- v9
TEST_F(ViewTest, RecreateLayers) {
Widget* w1 = CreateControlWidget(GetContext(), gfx::Rect(0, 0, 100, 100));
w1->GetNativeView()->layer()->set_name("w1");
View* v2 = new View();
v2->SetBounds(0, 1, 100, 101);
View* v3 = new View();
v3->SetBounds(0, 2, 100, 102);
View* w2_host_view = new View();
View* v1 = CreateViewWithLayer(gfx::Rect(0, 3, 100, 103), "v1");
ui::Layer* v1_layer = v1->layer();
w1->GetRootView()->AddChildView(v1);
w1->GetRootView()->AddChildView(v2);
v2->AddChildView(v3);
View* v4 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v4");
ui::Layer* v4_layer = v4->layer();
v2->AddChildView(v4);
w1->GetRootView()->AddChildView(w2_host_view);
View* v7 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v7");
ui::Layer* v7_layer = v7->layer();
w1->GetRootView()->AddChildView(v7);
View* v8 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v8");
ui::Layer* v8_layer = v8->layer();
v7->AddChildView(v8);
View* v9 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v9");
ui::Layer* v9_layer = v9->layer();
v7->AddChildView(v9);
Widget* w2 = CreateControlWidget(w1->GetNativeView(),
gfx::Rect(0, 5, 100, 105));
w2->GetNativeView()->layer()->set_name("w2");
w2->GetNativeView()->SetProperty(kHostViewKey, w2_host_view);
View* v5 = CreateViewWithLayer(gfx::Rect(0, 6, 100, 106), "v5");
w2->GetRootView()->AddChildView(v5);
View* v6 = CreateViewWithLayer(gfx::Rect(0, 7, 100, 107), "v6");
ui::Layer* v6_layer = v6->layer();
v5->AddChildView(v6);
// Test the initial order of the layers.
ui::Layer* w1_layer = w1->GetNativeView()->layer();
ASSERT_EQ("w1", w1_layer->name());
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer));
ui::Layer* w2_layer = w1_layer->children()[2];
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer));
ui::Layer* v5_layer = w2_layer->children()[0];
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer));
{
scoped_ptr<ui::LayerTreeOwner> cloned_owner(
wm::RecreateLayers(w1->GetNativeView()));
EXPECT_EQ(w1_layer, cloned_owner->root());
EXPECT_NE(w1_layer, w1->GetNativeView()->layer());
// The old layers should still exist and have the same hierarchy.
ASSERT_EQ("w1", w1_layer->name());
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer));
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer));
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer));
EXPECT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_layer));
ASSERT_EQ(4u, w1_layer->children().size());
EXPECT_EQ(v1_layer, w1_layer->children()[0]);
EXPECT_EQ(v4_layer, w1_layer->children()[1]);
EXPECT_EQ(w2_layer, w1_layer->children()[2]);
EXPECT_EQ(v7_layer, w1_layer->children()[3]);
ASSERT_EQ(1u, w2_layer->children().size());
EXPECT_EQ(v5_layer, w2_layer->children()[0]);
ASSERT_EQ(1u, v5_layer->children().size());
EXPECT_EQ(v6_layer, v5_layer->children()[0]);
ASSERT_EQ(0u, v6_layer->children().size());
EXPECT_EQ(2u, v7_layer->children().size());
EXPECT_EQ(v8_layer, v7_layer->children()[0]);
EXPECT_EQ(v9_layer, v7_layer->children()[1]);
// The cloned layers should have the same hierarchy as old.
ui::Layer* w1_new_layer = w1->GetNativeView()->layer();
EXPECT_EQ("w1", w1_new_layer->name());
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_new_layer));
ui::Layer* w2_new_layer = w1_new_layer->children()[2];
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_new_layer));
ui::Layer* v5_new_layer = w2_new_layer->children()[0];
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_new_layer));
ui::Layer* v7_new_layer = w1_new_layer->children()[3];
ASSERT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_new_layer));
}
// The views and the widgets are destroyed when AuraTestHelper::TearDown()
// destroys root_window().
}
// Verifies when a view is deleted it is removed from ViewStorage.
TEST_F(ViewTest, UpdateViewStorageOnDelete) {
ViewStorage* view_storage = ViewStorage::GetInstance();
const int storage_id = view_storage->CreateStorageID();
{
View view;
view_storage->StoreView(storage_id, &view);
}
EXPECT_TRUE(view_storage->RetrieveView(storage_id) == NULL);
}
////////////////////////////////////////////////////////////////////////////////
// NativeTheme
////////////////////////////////////////////////////////////////////////////////
void TestView::OnNativeThemeChanged(const ui::NativeTheme* native_theme) {
native_theme_ = native_theme;
}
TEST_F(ViewTest, OnNativeThemeChanged) {
TestView* test_view = new TestView();
EXPECT_FALSE(test_view->native_theme_);
TestView* test_view_child = new TestView();
EXPECT_FALSE(test_view_child->native_theme_);
// Child view added before the widget hierarchy exists should get the
// new native theme notification.
test_view->AddChildView(test_view_child);
scoped_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(params);
widget->GetRootView()->AddChildView(test_view);
EXPECT_TRUE(test_view->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view->native_theme_);
EXPECT_TRUE(test_view_child->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view_child->native_theme_);
// Child view added after the widget hierarchy exists should also get the
// notification.
TestView* test_view_child_2 = new TestView();
test_view->AddChildView(test_view_child_2);
EXPECT_TRUE(test_view_child_2->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view_child_2->native_theme_);
widget->CloseNow();
}
} // namespace views
| [
"nechayukanton@gmail.com"
] | nechayukanton@gmail.com |
dcae953085f64c856b18d1055c3c99f6d4a6bb71 | bcdd4c17ee83923d4696d35e00c5bf32e8794860 | /src/libraries/CVK_2/CVK_ShaderMinimal.cpp | fe61e9f7643d9879593591534ae2acb443a8241f | [] | no_license | marcelpohl/EZR | fa332802e57c104fba70b08f3f16f346e86aa5bf | a84961eef2caad3771482f5bf6c988871e8e2440 | refs/heads/master | 2021-07-17T20:10:19.930722 | 2018-07-11T12:34:59 | 2018-07-11T12:34:59 | 134,305,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | cpp | #include "CVK_ShaderMinimal.h"
CVK::ShaderMinimal::ShaderMinimal( GLuint shader_mask, const char** shaderPaths)
{
// generate shader program
GenerateShaderProgramm(shader_mask, shaderPaths);
// matrices
m_modelMatrixID = glGetUniformLocation(m_ProgramID, "modelMatrix");
m_viewMatrixID = glGetUniformLocation(m_ProgramID, "viewMatrix");
m_projectionMatrixID = glGetUniformLocation(m_ProgramID, "projectionMatrix");
}
void CVK::ShaderMinimal::updateModelMatrix(glm::mat4 modelmatrix) const
{
glUniformMatrix4fv(m_modelMatrixID, 1, GL_FALSE, glm::value_ptr(modelmatrix));
}
void CVK::ShaderMinimal::update()
{
CVK::Camera* cam = CVK::State::getInstance()->getCamera();
glm::mat4 projection, viewmatrix;
if (cam != nullptr)
{
viewmatrix = *cam->getView();
projection = *cam->getProjection()->getProjMatrix();
}
glUniformMatrix4fv(m_viewMatrixID, 1, GL_FALSE, glm::value_ptr(viewmatrix));
glUniformMatrix4fv(m_projectionMatrixID, 1, GL_FALSE, glm::value_ptr(projection));
}
void CVK::ShaderMinimal::update( CVK::Node* node)
{
}
| [
"senshi86@gmail.com"
] | senshi86@gmail.com |
74b6d146a6408b89b685f8db465ddb3061bcf377 | 19194c2f2c07ab3537f994acfbf6b34ea9b55ae7 | /android-33/android/text/style/TtsSpan_MoneyBuilder.hpp | cb518b40589fa155dc820850d117a0fe6d007f72 | [
"GPL-3.0-only"
] | permissive | YJBeetle/QtAndroidAPI | e372609e9db0f96602da31b8417c9f5972315cae | ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c | refs/heads/Qt6 | 2023-08-05T03:14:11.842336 | 2023-07-24T08:35:31 | 2023-07-24T08:35:31 | 249,539,770 | 19 | 4 | Apache-2.0 | 2022-03-14T12:15:32 | 2020-03-23T20:42:54 | C++ | UTF-8 | C++ | false | false | 1,813 | hpp | #pragma once
#include "../../../JString.hpp"
#include "./TtsSpan_MoneyBuilder.def.hpp"
namespace android::text::style
{
// Fields
// Constructors
inline TtsSpan_MoneyBuilder::TtsSpan_MoneyBuilder()
: android::text::style::TtsSpan_SemioticClassBuilder(
"android.text.style.TtsSpan$MoneyBuilder",
"()V"
) {}
// Methods
inline android::text::style::TtsSpan_MoneyBuilder TtsSpan_MoneyBuilder::setCurrency(JString arg0) const
{
return callObjectMethod(
"setCurrency",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$MoneyBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_MoneyBuilder TtsSpan_MoneyBuilder::setFractionalPart(JString arg0) const
{
return callObjectMethod(
"setFractionalPart",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$MoneyBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_MoneyBuilder TtsSpan_MoneyBuilder::setIntegerPart(JString arg0) const
{
return callObjectMethod(
"setIntegerPart",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$MoneyBuilder;",
arg0.object<jstring>()
);
}
inline android::text::style::TtsSpan_MoneyBuilder TtsSpan_MoneyBuilder::setIntegerPart(jlong arg0) const
{
return callObjectMethod(
"setIntegerPart",
"(J)Landroid/text/style/TtsSpan$MoneyBuilder;",
arg0
);
}
inline android::text::style::TtsSpan_MoneyBuilder TtsSpan_MoneyBuilder::setQuantity(JString arg0) const
{
return callObjectMethod(
"setQuantity",
"(Ljava/lang/String;)Landroid/text/style/TtsSpan$MoneyBuilder;",
arg0.object<jstring>()
);
}
} // namespace android::text::style
// Base class headers
#include "./TtsSpan_Builder.hpp"
#include "./TtsSpan_SemioticClassBuilder.hpp"
#ifdef QT_ANDROID_API_AUTOUSE
using namespace android::text::style;
#endif
| [
"YJBeetle@gmail.com"
] | YJBeetle@gmail.com |
629d429407ef0e7a08c9c63c90e573fef16cd165 | d1ba96b3467fea007f85a2a44ca8724329d195b7 | /Final Submission/Sourcecode/Client/Debug/debug/moc_dialog.cpp | a42e3e6aa05c0cb06ac49dd256b84779bd487fe5 | [] | no_license | Team-Chimera/Comm-Audio | 9caa5c72adf75a2bfddfc06b9fc2766d08f6c370 | 5b6ea3e9419f5f7a026651dc994fbfb2f1c7d5f9 | refs/heads/master | 2016-09-06T04:12:27.576781 | 2015-04-09T05:37:10 | 2015-04-09T05:37:10 | 30,979,831 | 0 | 5 | null | 2015-04-09T05:37:10 | 2015-02-18T18:31:53 | C | UTF-8 | C++ | false | false | 3,307 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'dialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../comm-audio/sourcecode/client/dialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'dialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Dialog_t {
QByteArrayData data[3];
char stringdata[25];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Dialog_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Dialog_t qt_meta_stringdata_Dialog = {
{
QT_MOC_LITERAL(0, 0, 6), // "Dialog"
QT_MOC_LITERAL(1, 7, 16), // "connectMulticast"
QT_MOC_LITERAL(2, 24, 0) // ""
},
"Dialog\0connectMulticast\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Dialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Bool,
0 // eod
};
void Dialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Dialog *_t = static_cast<Dialog *>(_o);
switch (_id) {
case 0: { bool _r = _t->connectMulticast();
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break;
default: ;
}
}
}
const QMetaObject Dialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_Dialog.data,
qt_meta_data_Dialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Dialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Dialog::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Dialog.stringdata))
return static_cast<void*>(const_cast< Dialog*>(this));
return QDialog::qt_metacast(_clname);
}
int Dialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"rhealauzon@gmail.com"
] | rhealauzon@gmail.com |
244c5a3748d59cddc50bc1edf6c96b8318b2fad7 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_new_log_2709.cpp | f3367127fc3ea934fcf3c74d72810c122edabffc | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35 | cpp | die(_("unrecognized width:%s"), s); | [
"993273596@qq.com"
] | 993273596@qq.com |
4020aad18c0c0ec683c070575c725d6a2ada2e4f | 0dc20516079aaae4756d28e67db7cae9c0d33708 | /jxy/jxy_src/jxysvr/src/dll/sdu/algorithm/sdmd5.cpp | 82fb050e2dc91d5035af5e434941ea18208fa67e | [] | no_license | psymicgit/dummy | 149365d586f0d4083a7a5719ad7c7268e7dc4bc3 | 483f2d410f353ae4c42abdfe4c606ed542186053 | refs/heads/master | 2020-12-24T07:48:56.132871 | 2017-08-05T07:20:18 | 2017-08-05T07:20:18 | 32,851,013 | 3 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 12,527 | cpp |
#include "sdmd5.h"
#include "sdfile.h"
#include "sdfilemapping.h"
#include "sdstring.h"
namespace SGDP
{
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
const static int ChunkSize = 4096;
static VOID MD5Transform(UINT32 [4], UCHAR [64]);
static VOID Encode(UCHAR *, UINT32 *, unsigned int);
static VOID Decode(UINT32 *, UCHAR *, unsigned int);
static VOID MD5_memcpy(UINT8*, UINT8*, unsigned int);
static VOID MD5_memset(UINT8*, int, unsigned int);
static UCHAR PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
/*
MD5 initialization. Begins an MD5 operation, writing a SDNew context.
*/
VOID SDMD5Init(SMD5Context *context) /* context */
{
context->count[0] = context->count[1] = 0;
/*
Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
VOID SDMD5Update(SMD5Context *context, /* context */
UCHAR *input, /* input block */
unsigned int inputLen) /* length of input block */
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int)((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((UINT32)inputLen << 3))
< ((UINT32)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT32)inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen)
{
MD5_memcpy
((UINT8*)&context->buffer[index], (UINT8*)input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
/* Buffer remaining input */
MD5_memcpy((UINT8*)&context->buffer[index], (UINT8*)&input[i], inputLen-i);
}
/* MD5 finalization. Ends an MD5 message-digest operation, writing the
the message digest and zeroizing the context.
*/
VOID SDMD5Final (UCHAR digest[16], /* message digest */
SMD5Context *context) /* context */
{
UCHAR bits[8];
unsigned int index, padLen;
/* Save number of bits */
Encode (bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
SDMD5Update (context, PADDING, padLen);
/* Append length (before padding) */
SDMD5Update (context, bits, 8);
/* Store state in digest */
Encode (digest, context->state, 16);
/* Zeroize sensitive information.
*/
MD5_memset ((UINT8*)context, 0, sizeof (*context));
}
/* MD5 basic transformation. Transforms state based on block.
*/
static VOID MD5Transform(UINT32 state[4],UCHAR block[64])
{
UINT32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information.
*/
MD5_memset((UINT8*)x, 0, sizeof (x));
}
/* Encodes input (UINT32) into output (UCHAR). Assumes len is
a multiple of 4.
*/
static VOID Encode (UCHAR *output,UINT32 *input,unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
{
output[j] = (UCHAR)(input[i] & 0xff);
output[j+1] = (UCHAR)((input[i] >> 8) & 0xff);
output[j+2] = (UCHAR)((input[i] >> 16) & 0xff);
output[j+3] = (UCHAR)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (UCHAR) into output (UINT32). Assumes len is
a multiple of 4.
*/
static VOID Decode(UINT32 *output, UCHAR *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
{
output[i] = ((UINT32)input[j]) | (((UINT32)input[j+1]) << 8) |
(((UINT32)input[j+2]) << 16) | (((UINT32)input[j+3]) << 24);
}
}
/* Note: Replace "for loop" with standard memcpy if possible.
*/
static VOID MD5_memcpy(UINT8* output, UINT8* input, unsigned int len)
{
unsigned int i;
for (i = 0; i < len; i++)
{
output[i] = input[i];
}
}
/* Note: Replace "for loop" with standard memset if possible.
*/
static VOID MD5_memset(UINT8* output, int value, unsigned int len)
{
unsigned int i;
for (i = 0; i < len; i++)
{
((char *)output)[i] = (char)value;
}
}
VOID SDMD5(UCHAR acDigest[16], UCHAR* pInput, UINT32 dwInLen)
{
SMD5Context mCtx;
SDMD5Init(&mCtx);
ULONG lastPos = 0;
while(lastPos < dwInLen)
{
if(dwInLen - lastPos < ChunkSize)
{
SDMD5Update(&mCtx, pInput + lastPos, dwInLen - lastPos);
lastPos = dwInLen;
}
else
{
SDMD5Update(&mCtx, pInput + lastPos, ChunkSize);
lastPos += ChunkSize;
}
}
SDMD5Final(acDigest, &mCtx);
}
BOOL SDFileMD5(UCHAR acDigest[16], const TCHAR* pszFileName, BOOL bFileMapping)
{
if (bFileMapping)
{
SFileMapping fileMap;
if(!SDFileMapping(fileMap, pszFileName))
{
return FALSE;
}
SMD5Context mCtx;
SDMD5Init(&mCtx);
ULONG lastPos = 0;
while(lastPos < fileMap.size)
{
if(fileMap.size - lastPos < ChunkSize)
{
SDMD5Update(&mCtx, ((UCHAR*)fileMap.mem) + lastPos, fileMap.size - lastPos);
lastPos = fileMap.size;
}
else
{
SDMD5Update(&mCtx, ((UCHAR*)fileMap.mem) + lastPos, ChunkSize);
lastPos += ChunkSize;
}
}
SDMD5Final(acDigest, &mCtx);
SDFileUnMapping(fileMap);
return TRUE;
}
else
{
if (!SDFileExists(pszFileName))
{
return FALSE;
}
CSDFile file;
#ifdef UNICODE
file.Open((pszFileName), _SDT("rb"));
#else
file.Open(pszFileName, "rb");
#endif
SMD5Context mCtx;
SDMD5Init(&mCtx);
UCHAR buf[ChunkSize];
while(!file.Eof())
{
UINT32 size = file.Read(buf, sizeof(buf));
SDMD5Update(&mCtx, buf, size);
}
SDMD5Final(acDigest, &mCtx);
file.Close();
return TRUE;
}
}
}
| [
"wuzili1234@gmail.com"
] | wuzili1234@gmail.com |
923b681d1e3b359c140134d4c02d8afad1d8535f | 719b9668d421765586405b8478927b026f7e0336 | /projects/lang/runtime/runtime.cpp | 136af4369f8b1f01bbb3f8f04607fcc3c3287492 | [
"MIT"
] | permissive | yut148/taichi | f8208084483f1e2f7aad258fc1e046385d796576 | fecb8557e80a294d98347d71b1ad0fd2f43865b0 | refs/heads/master | 2022-02-23T17:43:19.995584 | 2019-10-02T15:15:51 | 2019-10-02T15:15:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,507 | cpp | // This file will only be compiled with clang into llvm bitcode
// Generated bitcode will likely get inline for performance.
#include <type_traits>
#include <atomic>
#define FORCEINLINE __attribute__((always_inline))
#define STRUCT_FIELD(S, F) \
extern "C" decltype(S::F) S##_get_##F(S *s) { \
return s->F; \
} \
extern "C" decltype(S::F) *S##_get_ptr_##F(S *s) { \
return &(s->F); \
} \
extern "C" void S##_set_##F(S *s, decltype(S::F) f) { \
s->F = f; \
}
#define STRUCT_FIELD_ARRAY(S, F) \
extern "C" std::remove_all_extents_t<decltype(S::F)> S##_get_##F(S *s, \
int i) { \
return s->F[i]; \
} \
extern "C" void S##_set_##F(S *s, int i, \
std::remove_all_extents_t<decltype(S::F)> f) { \
s->F[i] = f; \
}
using float32 = float;
constexpr int taichi_max_num_indices = 4;
constexpr int taichi_max_num_args = 8;
using uint8 = uint8_t;
using Ptr = uint8 *;
using ContextArgType = long long;
extern "C" {
int printf(const char *, ...);
struct PhysicalCoordinates {
int val[taichi_max_num_indices];
};
STRUCT_FIELD_ARRAY(PhysicalCoordinates, val);
struct Context {
void *buffer;
ContextArgType args[taichi_max_num_args];
void *leaves;
int num_leaves;
void *cpu_profiler;
Ptr runtime;
};
STRUCT_FIELD_ARRAY(Context, args);
STRUCT_FIELD(Context, runtime);
STRUCT_FIELD(Context, buffer);
float32 atomic_add_cpu_f32(volatile float32 *dest, float32 inc) {
float32 old_val;
float32 new_val;
do {
old_val = *dest;
new_val = old_val + inc;
#if defined(__clang__)
} while (!__atomic_compare_exchange(dest, &old_val, &new_val, true,
std::memory_order::memory_order_seq_cst,
std::memory_order::memory_order_seq_cst));
#else
} while (!__atomic_compare_exchange((float32 *)dest, &old_val, &new_val, true,
std::memory_order::memory_order_seq_cst,
std::memory_order::memory_order_seq_cst));
#endif
return old_val;
}
// These structures are accessible by both the LLVM backend and this C++ runtime
// file here (for building complex runtime functions in C++)
// These structs contain some "template parameters"
// Common Attributes
struct StructMeta {
int snode_id;
std::size_t element_size;
int max_num_elements;
Ptr (*lookup_element)(Ptr, Ptr, int i);
Ptr (*from_parent_element)(Ptr);
bool (*is_active)(Ptr, Ptr, int i);
int (*get_num_elements)(Ptr, Ptr);
void (*refine_coordinates)(PhysicalCoordinates *inp_coord,
PhysicalCoordinates *refined_coord,
int index);
};
STRUCT_FIELD(StructMeta, snode_id)
STRUCT_FIELD(StructMeta, element_size)
STRUCT_FIELD(StructMeta, max_num_elements)
STRUCT_FIELD(StructMeta, get_num_elements);
STRUCT_FIELD(StructMeta, lookup_element);
STRUCT_FIELD(StructMeta, from_parent_element);
STRUCT_FIELD(StructMeta, refine_coordinates);
STRUCT_FIELD(StructMeta, is_active);
// Specialized Attributes and functions
struct DenseMeta : public StructMeta {
bool bitmasked;
int morton_dim;
};
STRUCT_FIELD(DenseMeta, bitmasked)
STRUCT_FIELD(DenseMeta, morton_dim)
void Dense_activate(Ptr meta, Ptr node, int i) {
}
bool Dense_is_active(Ptr meta, Ptr node, int i) {
return true;
}
void *Dense_lookup_element(Ptr meta, Ptr node, int i) {
return node + ((StructMeta *)meta)->element_size * i;
}
int Dense_get_num_elements(Ptr meta, Ptr node) {
return ((StructMeta *)meta)->max_num_elements;
}
struct RootMeta : public StructMeta {
int tag;
};
STRUCT_FIELD(RootMeta, tag);
void Root_activate(Ptr meta, Ptr node, int i) {
}
bool Root_is_active(Ptr meta, Ptr node, int i) {
return true;
}
void *Root_lookup_element(Ptr meta, Ptr node, int i) {
// only one element
return node;
}
int Root_get_num_elements(Ptr meta, Ptr node) {
return 1;
}
void *taichi_allocate_aligned(std::size_t size, int alignment);
void *taichi_allocate(std::size_t size) {
return taichi_allocate_aligned(size, 1);
}
void ___stubs___() {
printf("");
taichi_allocate(1);
taichi_allocate_aligned(1, 1);
}
struct Element {
uint8 *element;
int loop_bounds[2];
PhysicalCoordinates pcoord;
};
STRUCT_FIELD(Element, element);
STRUCT_FIELD(Element, pcoord);
STRUCT_FIELD_ARRAY(Element, loop_bounds);
struct ElementList {
Element *elements;
int tail;
};
void ElementList_initialize(ElementList *element_list) {
element_list->elements = (Element *)taichi_allocate(1024 * 1024 * 1024);
element_list->tail = 0;
}
void ElementList_insert(ElementList *element_list, Element *element) {
element_list->elements[element_list->tail] = *element;
element_list->tail++;
}
void ElementList_clear(ElementList *element_list) {
element_list->tail = 0;
}
// Is "runtime" a correct name, even if it is created after the data layout is
// materialized?
struct Runtime {
ElementList *element_lists[1024];
};
STRUCT_FIELD_ARRAY(Runtime, element_lists);
Ptr Runtime_initialize(Runtime **runtime_ptr,
int num_snodes,
uint64_t root_size,
int root_id) {
*runtime_ptr = (Runtime *)taichi_allocate(sizeof(Runtime));
Runtime *runtime = *runtime_ptr;
printf("Initializing runtime with %d elements\n", num_snodes);
for (int i = 0; i < num_snodes; i++) {
runtime->element_lists[i] =
(ElementList *)taichi_allocate(sizeof(ElementList));
ElementList_initialize(runtime->element_lists[i]);
}
// Assuming num_snodes - 1 is the root
auto root_ptr = taichi_allocate(root_size);
Element elem;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = 1;
elem.element = (Ptr)root_ptr;
for (int i = 0; i < taichi_max_num_indices; i++) {
elem.pcoord.val[i] = 0;
}
ElementList_insert(runtime->element_lists[root_id], &elem);
printf("Runtime initialized.\n");
return (Ptr)root_ptr;
}
// "Element", "component" are different concepts
// ultimately all function calls here will be inlined
void element_listgen(Runtime *runtime, StructMeta *parent, StructMeta *child) {
auto parent_list = runtime->element_lists[parent->snode_id];
int num_parent_elements = parent_list->tail;
// printf("num_parent_elements %d\n", num_parent_elements);
auto child_list = runtime->element_lists[child->snode_id];
for (int i = 0; i < num_parent_elements; i++) {
auto element = parent_list->elements[i];
auto ch_component = child->from_parent_element(element.element);
int ch_num_elements = child->get_num_elements((Ptr)child, ch_component);
// printf("ch_num_parent_elements %d\n", ch_num_elements);
for (int j = 0; j < ch_num_elements; j++) {
auto ch_element = child->lookup_element((Ptr)child, element.element, j);
// printf("j %d\n", j);
if (child->is_active((Ptr)child, ch_component, j)) {
// printf("j! %d\n", j);
Element elem;
elem.element = ch_element;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = child->get_num_elements((Ptr)child, ch_element);
PhysicalCoordinates refined_coord;
child->refine_coordinates(&element.pcoord, &refined_coord, j);
/*
printf("snode id %d\n", child->snode_id);
for (int k = 0; k < taichi_max_num_indices; k++) {
printf(" %d\n", refined_coord.val[k]);
}
*/
elem.pcoord = refined_coord;
ElementList_insert(child_list, &elem);
}
}
}
}
void for_each_block(Context *context,
int snode_id,
void (*task)(Context *, Element *)) {
auto list = ((Runtime *)context->runtime)->element_lists[snode_id];
for (int i = 0; i < list->tail; i++) {
task(context, &list->elements[i]);
}
}
int ti_cuda_tid_x() {
return 0;
}
void cuda_add(float *a, float *b, float *c) {
auto i = ti_cuda_tid_x();
c[i] = a[i] + b[i];
}
}
| [
"yuanmhu@gmail.com"
] | yuanmhu@gmail.com |
b9afce1ab16e25e9f29f2ef4c4468f5750598d66 | 331af263b0a55ab97f32ea43777eb6bb0a69b620 | /300. Longest Increasing Subsequence.cpp | 80a2a828f80be13d69bf47e42eadb9813b836884 | [] | no_license | yanjunp-cmu/LeetCode | 3369683dd1d80b94726ab398083dbc377d4ef82b | 84dfcccb0fcb1debd45c982c132ba020e7e92d74 | refs/heads/master | 2020-07-12T08:11:53.560397 | 2020-01-17T17:48:13 | 2020-01-17T17:48:13 | 204,762,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.empty()) return 0;
vector<int> dp(nums.size(), 1);
int result = 1;
for (int i = 1; i < nums.size(); i++){
for (int j = 0; j < i; j++){
if(nums[j] < nums[i]){
dp[i] = max(dp[j] + 1, dp[i]);
}
}
result = max(result, dp[i]);
}
return result;
}
}; | [
"yanjunp@andrew.cmu.edu"
] | yanjunp@andrew.cmu.edu |
48a05db09bbb3f86f408101869e51cbd0a771f61 | 7c713739a64b22af2256f07d75447acf178586ac | /Source.cpp | 26c53f98834eca9a9813ea03665612702839d94a | [
"MIT"
] | permissive | kenjinote/SortingAlgorithmAnimations | 10c7cd5f4b233377093aa8444ea07b2431ae2ad1 | c42cc79c2c604c219ce2112bdc9ea6f126a1f1ad | refs/heads/master | 2023-02-23T17:16:47.612291 | 2023-02-08T15:05:06 | 2023-02-08T15:05:06 | 59,730,507 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,948 | cpp | #pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include <windows.h>
TCHAR szClassName[] = TEXT("Window");
void Update(HWND hWnd)
{
Sleep(5);
InvalidateRect(hWnd, 0, 0);
UpdateWindow(hWnd);
}
VOID InsertionSortStep(HWND hWnd, int* pList, SIZE_T size)
{
for (SIZE_T i = 1; i < size; ++i)
{
const int tmp = pList[i];
if (pList[i - 1] > tmp)
{
SIZE_T j = i;
do {
pList[j] = pList[j - 1];
Update(hWnd);
--j;
} while (j > 0 && pList[j - 1] > tmp);
pList[j] = tmp;
Update(hWnd);
}
}
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND hButton;
static LPINT lpData;
static SIZE_T nMaxSize = 32;
switch (msg)
{
case WM_CREATE:
hButton = CreateWindow(TEXT("BUTTON"), TEXT("ソート"), WS_VISIBLE | WS_CHILD, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0);
lpData = (LPINT)GlobalAlloc(0, sizeof(INT) * nMaxSize);
for (SIZE_T i = 0; i < nMaxSize; ++i)
{
lpData[i] = (int)i + 1;
}
break;
case WM_SIZE:
MoveWindow(hButton, 10, 10, 256, 32, TRUE);
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
EnableWindow(hButton, FALSE);
for (SIZE_T i = 0; i < nMaxSize; ++i)
{
const int temp = lpData[i];
SIZE_T index = rand() % nMaxSize;
lpData[i] = lpData[index];
lpData[index] = temp;
}
Update(hWnd);
InsertionSortStep(hWnd, lpData, nMaxSize);
InvalidateRect(hWnd, 0, 1);
EnableWindow(hButton, TRUE);
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
for (SIZE_T i = 0; i < nMaxSize; ++i)
{
RECT rect1 = { 10,50 + 20 * (int)i,lpData[i] * 10 + 10, 50 + 20 * (int)i + 10 };
RECT rect2 = { lpData[i] * 10 + 10,50 + 20 * (int)i,(int)nMaxSize * 10 + 10, 50 + 20 * (int)i + 10 };
FillRect(hdc, &rect1, (HBRUSH)GetStockObject(BLACK_BRUSH));
FillRect(hdc, &rect2, (HBRUSH)GetStockObject(WHITE_BRUSH));
}
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
GlobalFree(lpData);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreInst, LPSTR pCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASS wndclass = {
CS_HREDRAW | CS_VREDRAW,
WndProc,
0,
0,
hInstance,
0,
LoadCursor(0,IDC_ARROW),
(HBRUSH)(COLOR_WINDOW + 1),
0,
szClassName
};
RegisterClass(&wndclass);
HWND hWnd = CreateWindow(
szClassName,
TEXT("ソートアルゴリズムのアニメーション表示"),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
CW_USEDEFAULT,
0,
CW_USEDEFAULT,
0,
0,
0,
hInstance,
0
);
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
| [
"kenji256@gmail.com"
] | kenji256@gmail.com |
9424fed3d189f375b2c430a3bd828a575457bc64 | 9097b4172997abadd081a19789dc505f91759cea | /Sound Visualizer/Bar.hpp | b7f7da5ed0bc5eaf6503ec2bc0bec81ad5cdb99e | [] | no_license | veiyas/Sound-Visualizer | 65a0d14ca175560883a41d4a0d0566e43b0e785f | bde2ab6a16efc10e224e5d3f94226dd542b2d9f0 | refs/heads/master | 2020-07-27T10:56:01.925060 | 2019-10-16T21:20:14 | 2019-10-16T21:20:14 | 209,063,782 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | hpp | #pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Constants.hpp"
#include <vector>
#include <memory>
#include <iostream>
class Bar
{
public:
Bar(GLfloat x_coord, GLfloat height, GLfloat z_coord);
~Bar();
void render();
private:
//OpenGL magic
GLuint vao = 0; // Vertex array object, the main handle for geometry
const int nverts; // Number of vertices in the vertex array
const int ntris; // Number of triangles in the index array (may be zero)
GLuint vertexbuffer; // Buffer ID to bind to GL_ARRAY_BUFFER
GLuint indexbuffer; // Buffer ID to bind to GL_ELEMENT_ARRAY_BUFFER
}; | [
"david.rk97@gmail.com"
] | david.rk97@gmail.com |
33f8ae8d68ef4f321e22c8cd662d6e921519e817 | c6401d48085c920367e271032d6af5e48e7ab0c8 | /StacksAndQueues/PriorityQueueNode.hpp | 73d3507a7a2e00e6e02958a3cc4d68d2ccd73060 | [
"MIT"
] | permissive | Bartleby2718/Introduction-To-Algorithms--CLRS- | bf4a0705ec154149065e2801614de6564e4e70be | cc1445e9cc926e9a021caad61d7ff56d57bdc6e2 | refs/heads/master | 2020-05-22T13:18:23.243475 | 2019-07-25T02:42:15 | 2019-07-25T02:42:58 | 186,355,777 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | hpp | //
// Created by bartl on 06/21/2019.
//
#ifndef STACKSANDQUEUES_PRIORITYQUEUENODE_H
#define STACKSANDQUEUES_PRIORITYQUEUENODE_H
template<class T>
struct Node
{
unsigned index;
T element;
string toString()
{
return to_string(element) + "(index: " + to_string(index) + ")";
}
};
template<class T>
bool operator<(const Node<T> &lhs, const Node<T> &rhs)
{
return lhs.index < rhs.index;
}
template<class T>
bool operator>(const Node<T> &lhs, const Node<T> &rhs)
{
return operator<(rhs, lhs);
}
#endif //STACKSANDQUEUES_PRIORITYQUEUENODE_H
| [
"bartleby2718@gmail.com"
] | bartleby2718@gmail.com |
230f1ac4bfa289ee33b50ef4079aef99b2bf102b | 1441bc7fee74a372af6ba63a8a4dc04100e6255c | /aria-HW/part_c.cpp | 096d0398c594c302c8888ab6cf2c7ba6721b1c1d | [] | no_license | Chen-Yu-Qiang/class | b9931f9be9dbfc4156531c8cbbfa4b3b9b6740a2 | 46470e472eb74223d3cc69d3e0da31c4f63e6ce2 | refs/heads/master | 2023-07-13T14:41:46.858478 | 2021-08-29T04:41:34 | 2021-08-29T04:41:34 | 400,951,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,657 | cpp |
#include "Aria.h"
int main(int argc, char **argv)
{
ArRobot robot;
ArSonarDevice sonar;
robot.addRangeDevice(&sonar);
Aria::init();
ArSimpleConnector connector(&argc, argv);
if (!connector.connectRobot(&robot))
{
printf("Could not connect to robot... exiting\n");
Aria::shutdown();
Aria::exit(1);
}
robot.comInt(ArCommands::ENABLE, 1);
robot.runAsync(false);
// Used to perform actions when keyboard keys are pressed
ArKeyHandler keyHandler;
Aria::setKeyHandler(&keyHandler);
// ArRobot contains an exit action for the Escape key. It also
// stores a pointer to the keyhandler so that other parts of the program can
// use the same keyhandler.
robot.attachKeyHandler(&keyHandler);
printf("You may press escape to exit\n");
// TODO: control the robot
// Start of controling
// 1. Lock the robot
robot.lock();
// 2. Write your control code here,
// e.g. robot.setVel(150);
robot.setVel(0);
// 3. Unlock the robot
robot.unlock();
// 4. Sleep a while and let the robot move
while (true)
{
int ch=keyHandler.getKey();
printf("%f %f %f push key:%d\n", robot.getX(), robot.getY(), robot.getTh(),ch);
if(ch==256){
robot.setVel(150);
robot.setRotVel(0);
}else if (ch==257)
{
robot.setVel(-150);
robot.setRotVel(0);
}else if (ch==258)
{
robot.setVel(0);
robot.setRotVel(50);
}else if (ch==259)
{
robot.setVel(0);
robot.setRotVel(-50);
}else{
robot.setVel(0);
robot.setRotVel(0);
}
ArUtil::sleep(100);
}
// End of controling
Aria::shutdown();
Aria::exit(0);
}
| [
"a@example.com"
] | a@example.com |
d48b1b4a5a0e4d70187070f5dec74d1e82074855 | e52d6cf6d24dc646415e9c4ac8ad7c801f4554fa | /Nsplit/CRFsparse/util.h | 39a407b7fb36b634b341843f64ef4e8b230f4298 | [] | no_license | a061105/AugmentedLimitedMem | aaf5c70133732014a4b322cfe9b79037bbc12067 | 5aa84702bc5f7ecaa9f761c0779aadf89ad26fd5 | refs/heads/master | 2020-12-24T06:54:16.792123 | 2016-08-12T03:41:14 | 2016-08-12T03:41:14 | 53,838,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | h | #ifndef UTIL
#define UTIL
#include<map>
#include<vector>
#include<string>
#include<cmath>
#include <iomanip> // std::setprecision
#include <fstream>
#include <set>
using namespace std;
void split(string str, string pattern, vector<string>& tokens);
double maximum(double* values, int size);
double maximum(double* values, int size,int &posi);
int expOverSumExp(double *values, double *prob, int size);
double logSumExp(double* values, int size);
double normalize(double* values, int size);
void dataToFeatures( vector<vector<pair<int,double> > >& data, int dim, //intput
vector<vector<pair<int,double> > >& features //output
);
void softThd(double* w, vector<int> &act_set, double t_lambda);
void softThd(double* w, int size, double t_lambda);
double softThd(const double &x,const double &thd);
double l1_norm(double* w, int size);
double l1_norm(vector<double>& w);
double l2_norm(double* w,int size);
void shuffle(vector<int>& arr);
double sign(double v);
typedef vector<pair<int,double> > Feature;
#endif
| [
"a061105@gmail.com"
] | a061105@gmail.com |
d8337f6d5fb0d2dad253755205f5b82ebb371c8c | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/content/renderer/gpu/input_handler_proxy.cc | 1f88e6278419d316e6f3872e392b5e0f14a207ab | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 16,078 | cc | // Copyright (c) 2013 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 "content/renderer/gpu/input_handler_proxy.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "content/renderer/gpu/input_handler_proxy_client.h"
#include "third_party/WebKit/public/platform/Platform.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/base/latency_info.h"
using WebKit::WebFloatPoint;
using WebKit::WebFloatSize;
using WebKit::WebGestureEvent;
using WebKit::WebInputEvent;
using WebKit::WebMouseWheelEvent;
using WebKit::WebPoint;
using WebKit::WebTouchEvent;
namespace {
void SendScrollLatencyUma(const WebInputEvent& event,
const ui::LatencyInfo& latency_info) {
if (!(event.type == WebInputEvent::GestureScrollBegin ||
event.type == WebInputEvent::GestureScrollUpdate ||
event.type == WebInputEvent::GestureScrollUpdateWithoutPropagation))
return;
ui::LatencyInfo::LatencyMap::const_iterator it =
latency_info.latency_components.find(std::make_pair(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0));
if (it == latency_info.latency_components.end())
return;
base::TimeDelta delta = base::TimeTicks::HighResNow() - it->second.event_time;
for (size_t i = 0; i < it->second.event_count; ++i) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Latency.RendererImpl.GestureScroll",
delta.InMicroseconds(),
0,
200000,
100);
}
} // namespace
}
namespace content {
InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler)
: client_(NULL),
input_handler_(input_handler),
#ifndef NDEBUG
expect_scroll_update_end_(false),
expect_pinch_update_end_(false),
#endif
gesture_scroll_on_impl_thread_(false),
gesture_pinch_on_impl_thread_(false),
fling_may_be_active_on_main_thread_(false),
fling_overscrolled_horizontally_(false),
fling_overscrolled_vertically_(false) {
input_handler_->BindToClient(this);
}
InputHandlerProxy::~InputHandlerProxy() {}
void InputHandlerProxy::WillShutdown() {
input_handler_ = NULL;
DCHECK(client_);
client_->WillShutdown();
}
void InputHandlerProxy::SetClient(InputHandlerProxyClient* client) {
DCHECK(!client_ || !client);
client_ = client;
}
InputHandlerProxy::EventDisposition
InputHandlerProxy::HandleInputEventWithLatencyInfo(
const WebInputEvent& event,
const ui::LatencyInfo& latency_info) {
DCHECK(input_handler_);
SendScrollLatencyUma(event, latency_info);
InputHandlerProxy::EventDisposition disposition = HandleInputEvent(event);
if (disposition != DID_NOT_HANDLE)
input_handler_->SetLatencyInfoForInputEvent(latency_info);
return disposition;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleInputEvent(
const WebInputEvent& event) {
DCHECK(client_);
DCHECK(input_handler_);
if (event.type == WebInputEvent::MouseWheel) {
const WebMouseWheelEvent& wheel_event =
*static_cast<const WebMouseWheelEvent*>(&event);
if (wheel_event.scrollByPage) {
// TODO(jamesr): We don't properly handle scroll by page in the compositor
// thread, so punt it to the main thread. http://crbug.com/236639
return DID_NOT_HANDLE;
}
cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
gfx::Point(wheel_event.x, wheel_event.y), cc::InputHandler::Wheel);
switch (scroll_status) {
case cc::InputHandler::ScrollStarted: {
TRACE_EVENT_INSTANT2(
"renderer",
"InputHandlerProxy::handle_input wheel scroll",
TRACE_EVENT_SCOPE_THREAD,
"deltaX",
-wheel_event.deltaX,
"deltaY",
-wheel_event.deltaY);
bool did_scroll = input_handler_->ScrollBy(
gfx::Point(wheel_event.x, wheel_event.y),
gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY));
input_handler_->ScrollEnd();
return did_scroll ? DID_HANDLE : DROP_EVENT;
}
case cc::InputHandler::ScrollIgnored:
// TODO(jamesr): This should be DROP_EVENT, but in cases where we fail
// to properly sync scrollability it's safer to send the event to the
// main thread. Change back to DROP_EVENT once we have synchronization
// bugs sorted out.
return DID_NOT_HANDLE;
case cc::InputHandler::ScrollOnMainThread:
return DID_NOT_HANDLE;
}
} else if (event.type == WebInputEvent::GestureScrollBegin) {
DCHECK(!gesture_scroll_on_impl_thread_);
#ifndef NDEBUG
DCHECK(!expect_scroll_update_end_);
expect_scroll_update_end_ = true;
#endif
const WebGestureEvent& gesture_event =
*static_cast<const WebGestureEvent*>(&event);
cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
gfx::Point(gesture_event.x, gesture_event.y),
cc::InputHandler::Gesture);
switch (scroll_status) {
case cc::InputHandler::ScrollStarted:
gesture_scroll_on_impl_thread_ = true;
return DID_HANDLE;
case cc::InputHandler::ScrollOnMainThread:
return DID_NOT_HANDLE;
case cc::InputHandler::ScrollIgnored:
return DROP_EVENT;
}
} else if (event.type == WebInputEvent::GestureScrollUpdate) {
#ifndef NDEBUG
DCHECK(expect_scroll_update_end_);
#endif
if (!gesture_scroll_on_impl_thread_ && !gesture_pinch_on_impl_thread_)
return DID_NOT_HANDLE;
const WebGestureEvent& gesture_event =
*static_cast<const WebGestureEvent*>(&event);
bool did_scroll = input_handler_->ScrollBy(
gfx::Point(gesture_event.x, gesture_event.y),
gfx::Vector2dF(-gesture_event.data.scrollUpdate.deltaX,
-gesture_event.data.scrollUpdate.deltaY));
return did_scroll ? DID_HANDLE : DROP_EVENT;
} else if (event.type == WebInputEvent::GestureScrollEnd) {
#ifndef NDEBUG
DCHECK(expect_scroll_update_end_);
expect_scroll_update_end_ = false;
#endif
input_handler_->ScrollEnd();
if (!gesture_scroll_on_impl_thread_)
return DID_NOT_HANDLE;
gesture_scroll_on_impl_thread_ = false;
return DID_HANDLE;
} else if (event.type == WebInputEvent::GesturePinchBegin) {
#ifndef NDEBUG
DCHECK(!expect_pinch_update_end_);
expect_pinch_update_end_ = true;
#endif
input_handler_->PinchGestureBegin();
gesture_pinch_on_impl_thread_ = true;
return DID_HANDLE;
} else if (event.type == WebInputEvent::GesturePinchEnd) {
#ifndef NDEBUG
DCHECK(expect_pinch_update_end_);
expect_pinch_update_end_ = false;
#endif
gesture_pinch_on_impl_thread_ = false;
input_handler_->PinchGestureEnd();
return DID_HANDLE;
} else if (event.type == WebInputEvent::GesturePinchUpdate) {
#ifndef NDEBUG
DCHECK(expect_pinch_update_end_);
#endif
const WebGestureEvent& gesture_event =
*static_cast<const WebGestureEvent*>(&event);
input_handler_->PinchGestureUpdate(
gesture_event.data.pinchUpdate.scale,
gfx::Point(gesture_event.x, gesture_event.y));
return DID_HANDLE;
} else if (event.type == WebInputEvent::GestureFlingStart) {
const WebGestureEvent& gesture_event =
*static_cast<const WebGestureEvent*>(&event);
return HandleGestureFling(gesture_event);
} else if (event.type == WebInputEvent::GestureFlingCancel) {
if (CancelCurrentFling())
return DID_HANDLE;
else if (!fling_may_be_active_on_main_thread_)
return DROP_EVENT;
} else if (event.type == WebInputEvent::TouchStart) {
const WebTouchEvent& touch_event =
*static_cast<const WebTouchEvent*>(&event);
if (!input_handler_->HaveTouchEventHandlersAt(touch_event.touches[0]
.position))
return DROP_EVENT;
} else if (WebInputEvent::isKeyboardEventType(event.type)) {
CancelCurrentFling();
}
return DID_NOT_HANDLE;
}
InputHandlerProxy::EventDisposition
InputHandlerProxy::HandleGestureFling(
const WebGestureEvent& gesture_event) {
cc::InputHandler::ScrollStatus scroll_status;
if (gesture_event.sourceDevice == WebGestureEvent::Touchpad) {
scroll_status = input_handler_->ScrollBegin(
gfx::Point(gesture_event.x, gesture_event.y),
cc::InputHandler::NonBubblingGesture);
} else {
if (!gesture_scroll_on_impl_thread_)
scroll_status = cc::InputHandler::ScrollOnMainThread;
else
scroll_status = input_handler_->FlingScrollBegin();
}
#ifndef NDEBUG
expect_scroll_update_end_ = false;
#endif
switch (scroll_status) {
case cc::InputHandler::ScrollStarted: {
if (gesture_event.sourceDevice == WebGestureEvent::Touchpad)
input_handler_->ScrollEnd();
fling_curve_.reset(client_->CreateFlingAnimationCurve(
gesture_event.sourceDevice,
WebFloatPoint(gesture_event.data.flingStart.velocityX,
gesture_event.data.flingStart.velocityY),
WebKit::WebSize()));
fling_overscrolled_horizontally_ = false;
fling_overscrolled_vertically_ = false;
TRACE_EVENT_ASYNC_BEGIN0(
"renderer",
"InputHandlerProxy::HandleGestureFling::started",
this);
fling_parameters_.delta =
WebFloatPoint(gesture_event.data.flingStart.velocityX,
gesture_event.data.flingStart.velocityY);
fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y);
fling_parameters_.globalPoint =
WebPoint(gesture_event.globalX, gesture_event.globalY);
fling_parameters_.modifiers = gesture_event.modifiers;
fling_parameters_.sourceDevice = gesture_event.sourceDevice;
input_handler_->ScheduleAnimation();
return DID_HANDLE;
}
case cc::InputHandler::ScrollOnMainThread: {
TRACE_EVENT_INSTANT0("renderer",
"InputHandlerProxy::HandleGestureFling::"
"scroll_on_main_thread",
TRACE_EVENT_SCOPE_THREAD);
fling_may_be_active_on_main_thread_ = true;
return DID_NOT_HANDLE;
}
case cc::InputHandler::ScrollIgnored: {
TRACE_EVENT_INSTANT0(
"renderer",
"InputHandlerProxy::HandleGestureFling::ignored",
TRACE_EVENT_SCOPE_THREAD);
if (gesture_event.sourceDevice == WebGestureEvent::Touchpad) {
// We still pass the curve to the main thread if there's nothing
// scrollable, in case something
// registers a handler before the curve is over.
return DID_NOT_HANDLE;
}
return DROP_EVENT;
}
}
return DID_NOT_HANDLE;
}
void InputHandlerProxy::Animate(base::TimeTicks time) {
if (!fling_curve_)
return;
double monotonic_time_sec = (time - base::TimeTicks()).InSecondsF();
if (!fling_parameters_.startTime) {
fling_parameters_.startTime = monotonic_time_sec;
input_handler_->ScheduleAnimation();
return;
}
if (fling_curve_->apply(monotonic_time_sec - fling_parameters_.startTime,
this)) {
input_handler_->ScheduleAnimation();
} else {
TRACE_EVENT_INSTANT0("renderer",
"InputHandlerProxy::animate::flingOver",
TRACE_EVENT_SCOPE_THREAD);
CancelCurrentFling();
}
}
void InputHandlerProxy::MainThreadHasStoppedFlinging() {
fling_may_be_active_on_main_thread_ = false;
}
void InputHandlerProxy::DidOverscroll(const cc::DidOverscrollParams& params) {
DCHECK(client_);
if (fling_curve_) {
static const int kFlingOverscrollThreshold = 1;
fling_overscrolled_horizontally_ |=
std::abs(params.accumulated_overscroll.x()) >=
kFlingOverscrollThreshold;
fling_overscrolled_vertically_ |=
std::abs(params.accumulated_overscroll.y()) >=
kFlingOverscrollThreshold;
}
client_->DidOverscroll(params);
}
bool InputHandlerProxy::CancelCurrentFling() {
bool had_fling_animation = fling_curve_;
if (had_fling_animation &&
fling_parameters_.sourceDevice == WebGestureEvent::Touchscreen) {
input_handler_->ScrollEnd();
TRACE_EVENT_ASYNC_END0(
"renderer",
"InputHandlerProxy::HandleGestureFling::started",
this);
}
TRACE_EVENT_INSTANT1("renderer",
"InputHandlerProxy::CancelCurrentFling",
TRACE_EVENT_SCOPE_THREAD,
"had_fling_animation",
had_fling_animation);
fling_curve_.reset();
gesture_scroll_on_impl_thread_ = false;
fling_parameters_ = WebKit::WebActiveWheelFlingParameters();
return had_fling_animation;
}
bool InputHandlerProxy::TouchpadFlingScroll(
const WebFloatSize& increment) {
WebMouseWheelEvent synthetic_wheel;
synthetic_wheel.type = WebInputEvent::MouseWheel;
synthetic_wheel.deltaX = increment.width;
synthetic_wheel.deltaY = increment.height;
synthetic_wheel.hasPreciseScrollingDeltas = true;
synthetic_wheel.x = fling_parameters_.point.x;
synthetic_wheel.y = fling_parameters_.point.y;
synthetic_wheel.globalX = fling_parameters_.globalPoint.x;
synthetic_wheel.globalY = fling_parameters_.globalPoint.y;
synthetic_wheel.modifiers = fling_parameters_.modifiers;
InputHandlerProxy::EventDisposition disposition =
HandleInputEvent(synthetic_wheel);
switch (disposition) {
case DID_HANDLE:
return true;
case DROP_EVENT:
break;
case DID_NOT_HANDLE:
TRACE_EVENT_INSTANT0("renderer",
"InputHandlerProxy::scrollBy::AbortFling",
TRACE_EVENT_SCOPE_THREAD);
// If we got a DID_NOT_HANDLE, that means we need to deliver wheels on the
// main thread. In this case we need to schedule a commit and transfer the
// fling curve over to the main thread and run the rest of the wheels from
// there. This can happen when flinging a page that contains a scrollable
// subarea that we can't scroll on the thread if the fling starts outside
// the subarea but then is flung "under" the pointer.
client_->TransferActiveWheelFlingAnimation(fling_parameters_);
fling_may_be_active_on_main_thread_ = true;
CancelCurrentFling();
break;
}
return false;
}
static gfx::Vector2dF ToClientScrollIncrement(const WebFloatSize& increment) {
return gfx::Vector2dF(-increment.width, -increment.height);
}
void InputHandlerProxy::scrollBy(const WebFloatSize& increment) {
WebFloatSize clipped_increment;
if (!fling_overscrolled_horizontally_)
clipped_increment.width = increment.width;
if (!fling_overscrolled_vertically_)
clipped_increment.height = increment.height;
if (clipped_increment == WebFloatSize())
return;
TRACE_EVENT2("renderer",
"InputHandlerProxy::scrollBy",
"x",
clipped_increment.width,
"y",
clipped_increment.height);
bool did_scroll = false;
switch (fling_parameters_.sourceDevice) {
case WebGestureEvent::Touchpad:
did_scroll = TouchpadFlingScroll(clipped_increment);
break;
case WebGestureEvent::Touchscreen:
clipped_increment = ToClientScrollIncrement(clipped_increment);
did_scroll = input_handler_->ScrollBy(fling_parameters_.point,
clipped_increment);
break;
}
if (did_scroll) {
fling_parameters_.cumulativeScroll.width += clipped_increment.width;
fling_parameters_.cumulativeScroll.height += clipped_increment.height;
}
}
void InputHandlerProxy::notifyCurrentFlingVelocity(
const WebFloatSize& velocity) {
TRACE_EVENT2("renderer",
"InputHandlerProxy::notifyCurrentFlingVelocity",
"vx",
velocity.width,
"vy",
velocity.height);
input_handler_->NotifyCurrentFlingVelocity(ToClientScrollIncrement(velocity));
}
} // namespace content
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
2a33776f19fd712835758d387bfa794ae6eae7b9 | 30105cdf24a8ee004eb461b52e73f36372072c84 | /modifikacije/2020 avgust/mod/queue.cpp | 05f7bf48ded2256fdff51801f6b3f82592e1f9ea | [] | no_license | botuljina/ProcessorKernel | 4136a1fd5390353b725b60dc8ee81ce046da65d4 | d48cfe28dfa2633cde08eb3b7a98c96046caa9c4 | refs/heads/master | 2022-12-29T19:35:45.958675 | 2020-10-03T15:55:04 | 2020-10-03T15:55:04 | 256,285,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | #include "queue.h"
#include "Timer.h"
#include <iostream.h>
#include "sPrintf.h"
#include "Thread.h"
queue::queue()
{
#ifndef BCC_BLOCK_IGNORE
lock();
#endif
firstNode = 0;
lastNode = 0;
queueLen = 0;
#ifndef BCC_BLOCK_IGNORE
unlock();
#endif
}
int queue::isEmpty(){
if(firstNode == 0) return 1;
else return 0;
}
void queue::printQueueElements()
{
#ifndef BCC_BLOCK_IGNORE
lock();
#endif
qnode* temp = firstNode;
syncPrintf("VELICINA queue-a je:%d\n************* \n",queueLen);
while(temp!=0)
{
if(temp!=0)syncPrintf("%d id niti.\n",(int)temp->element->myThread->getId());
temp=temp->next;
}
syncPrintf("\n************* \n");
#ifndef BCC_BLOCK_IGNORE
unlock();
#endif
}
void queue::put(PCB* _pcb)
{
#ifndef BCC_BLOCK_IGNORE
lock();
#endif
if(Timer::testingPhase)
{
if(this!= Timer::globalQueueForGettingIds) syncPrintf("Ubacivanje u neki drugi queue,id=%d,addr:%p,\n",_pcb->myThread->getId());
else syncPrintf("Ubacivanje u gloabal queue,id=%d\n",_pcb->myThread->getId());
}
if ( isEmpty( ) == 1 )
{
firstNode = new qnode(_pcb);
lastNode = firstNode;
queueLen++;
}
else
{
qnode *p = new qnode(_pcb);
lastNode->next = p;
lastNode = lastNode->next;
queueLen++;
}
if(Timer::testingPhase)
printQueueElements();
#ifndef BCC_BLOCK_IGNORE
unlock();
#endif
}
PCB* queue::get()
{
#ifndef BCC_BLOCK_IGNORE
lock();
#endif
qnode *temp ;
PCB* element_for_return = 0;
if ( isEmpty( ) == 0 )
{
queueLen--;
element_for_return = firstNode->element;
temp = firstNode;
//pomeram prvi
firstNode = firstNode->next;
delete temp;
}
if(Timer::testingPhase)
{
if(this!= Timer::globalQueueForGettingIds) syncPrintf("POP iz drugog queue-a,id=%d, addr:%p,\n",element_for_return->myThread->getId());
else syncPrintf("POP iz GLOBAL queue-a,id=%d\n",element_for_return->myThread->getId());
printQueueElements();
}
#ifndef BCC_BLOCK_IGNORE
unlock();
#endif
return element_for_return;
}
queue::~queue()
{
#ifndef BCC_BLOCK_IGNORE
lock();
#endif
while (isEmpty()==0)
get();
firstNode = 0;
lastNode = 0;
#ifndef BCC_BLOCK_IGNORE
unlock();
#endif
}
int queue::getQueueSize()
{
return queueLen;
}
Thread* queue::getThreadByIdSearchQueue(ID id)
{
qnode *temp = firstNode;
while(temp!=0)
{
if(temp->element->myThread->getId() == id)
{
return temp->element->myThread;
}
temp=temp->next;
}
return 0;
}
void queue::my_swap(qnode *node_1, qnode *node_2)
{
PCB* temp = node_1->element;
node_1->element = node_2 -> element;
node_2 -> element = temp;
}
void queue::sort()
{
int swapped;
qnode *lPtr; // left pointer will always point to the start of the list
qnode *rPrt = NULL; // right pointer will always point to the end of the list
do
{
swapped = 0;
lPtr = firstNode;
while(lPtr->next != rPrt)
{
//u ovoj ovde liniji samo ispravljam da li cu opadajuce ili rastuce
if (lPtr->element->myThread->getId() < lPtr->next->element->myThread->getId())
{
my_swap(lPtr, lPtr->next);
swapped = 1;
}
lPtr = lPtr->next;
}
//as the largest element is at the end of the list, assign that to rPtr as there is no need to
//check already sorted list
rPrt = lPtr;
}while(swapped);
}
//Funkcija: vadi sa odredjene pozicije PCB i uklanja element iz reda
PCB* queue::get_by_id(ID id)
{
qnode *cur = firstNode, *prev = 0, *old = 0;
while (cur) {
if (cur->element->myThread->getId() != id) {
prev = cur;
cur = cur->next;
} else {
old = cur;
cur = cur->next;
if (!prev)
firstNode = cur;
else
prev->next = cur;
if(old == lastNode)
lastNode = prev;
delete old;
queueLen--;
break;
}
}
}
| [
"lsimovic140@gmail.com"
] | lsimovic140@gmail.com |
92a3dff65a5c52dbd68ba8fdd4afe7e7faaab07a | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/public/mojom/frame/navigation_initiator.mojom-shared.cc | 9f4748f65a7b20a5d2402d04e1f6be3b049fa6ac | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,679 | cc | // Copyright 2016 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.
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4065)
#endif
#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-shared.h"
#include <utility>
#include "base/logging.h"
#include "base/stl_util.h" // for base::size()
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_context.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/bindings/lib/validation_util.h"
#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-params-data.h"
namespace blink {
namespace mojom {
std::ostream& operator<<(std::ostream& os, WebContentSecurityPolicyType value) {
switch(value) {
case WebContentSecurityPolicyType::WebContentSecurityPolicyTypeReport:
return os << "WebContentSecurityPolicyType::WebContentSecurityPolicyTypeReport";
case WebContentSecurityPolicyType::WebContentSecurityPolicyTypeEnforce:
return os << "WebContentSecurityPolicyType::WebContentSecurityPolicyTypeEnforce";
default:
return os << "Unknown WebContentSecurityPolicyType value: " << static_cast<int32_t>(value);
}
}
namespace internal {
// static
bool SourceLocation_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const SourceLocation_Data* object = static_cast<const SourceLocation_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 24 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->url, 1, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams url_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->url, validation_context,
&url_validate_params)) {
return false;
}
return true;
}
SourceLocation_Data::SourceLocation_Data()
: header_({sizeof(*this), 0}) {}
// static
bool CSPViolationParams_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const CSPViolationParams_Data* object = static_cast<const CSPViolationParams_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 72 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->directive, 1, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams directive_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->directive, validation_context,
&directive_validate_params)) {
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->effective_directive, 2, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams effective_directive_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->effective_directive, validation_context,
&effective_directive_validate_params)) {
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->console_message, 3, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams console_message_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->console_message, validation_context,
&console_message_validate_params)) {
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->blocked_url, 4, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams blocked_url_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->blocked_url, validation_context,
&blocked_url_validate_params)) {
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->report_endpoints, 5, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams report_endpoints_validate_params(
0, false, new mojo::internal::ContainerValidateParams(0, false, nullptr));
if (!mojo::internal::ValidateContainer(object->report_endpoints, validation_context,
&report_endpoints_validate_params)) {
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->header, 7, validation_context)) {
return false;
}
const mojo::internal::ContainerValidateParams header_validate_params(
0, false, nullptr);
if (!mojo::internal::ValidateContainer(object->header, validation_context,
&header_validate_params)) {
return false;
}
if (!::blink::mojom::internal::WebContentSecurityPolicyType_Data
::Validate(object->disposition, validation_context))
return false;
if (!mojo::internal::ValidatePointerNonNullable(
object->source_location, 10, validation_context)) {
return false;
}
if (!mojo::internal::ValidateStruct(object->source_location, validation_context))
return false;
return true;
}
CSPViolationParams_Data::CSPViolationParams_Data()
: header_({sizeof(*this), 0}) {}
// static
bool NavigationInitiator_SendViolationReport_Params_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const NavigationInitiator_SendViolationReport_Params_Data* object = static_cast<const NavigationInitiator_SendViolationReport_Params_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 16 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidatePointerNonNullable(
object->violation_params, 1, validation_context)) {
return false;
}
if (!mojo::internal::ValidateStruct(object->violation_params, validation_context))
return false;
return true;
}
NavigationInitiator_SendViolationReport_Params_Data::NavigationInitiator_SendViolationReport_Params_Data()
: header_({sizeof(*this), 0}) {}
} // namespace internal
} // namespace mojom
} // namespace blink
#if defined(_MSC_VER)
#pragma warning(pop)
#endif | [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
adeff6bf8c16e9d1b83dbafc621b030bf0b61b8a | c50c96c7618122a2566322afa75c44eb25e67296 | /sudokuboard.cc | c1ee87112cdc3644c962a659a9ec778a389b7a15 | [] | no_license | easiruwa/Sudoku | 6be0c2cc14859b2e9b8d5c766e033382e89633de | 7fd071f66478250ead9c00fa29fb3c1c603f8de8 | refs/heads/master | 2021-01-13T13:18:09.400178 | 2016-11-02T16:33:29 | 2016-11-02T16:33:29 | 72,659,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,235 | cc | /************************************************************************
File: sudokuboard.cc
Author: Eseosa Asiruwa
Date: 2/21/16
Assignment: Lab 3
Implemenation of the sudokuboard class.
************************************************************************/
#include <iostream>
#include "sudokuboard.h"
/*** Constructor ***/
sudokuboard::sudokuboard()
// Initializes board with blank spaces
{
for (size_t i = 0; i < 9; i++)
sboard[i] = "_________";
}
void sudokuboard::print()
// Print the board
{
for (size_t i = 0; i < 9; i++){
cout << sboard[i] << endl;
}
}
void sudokuboard::place(size_t r, size_t c, int n)
// Place numeral n at posiion (r,c)
{
sboard[r][c] = n + '0';
}
void sudokuboard::placeline(size_t p, string input)
// Places characters in board, line by line
{
sboard[p] = input;
}
bool sudokuboard::canplace(char num, size_t r, size_t c) const
// Checks empty spot to see if you can place given number. Returns a bool
// depending on if the number shows up in the same r, c, or 3x3
{
if (get(r,c) == '_'){
for (int j = 0; j < 9; j++){ // check rows
if (get(j,c) == num)
return false;
}
for (int k = 0; k < 9; k++){ // check cols
if (get(r,k) == num)
return false;
}
for (int y = 0; y < 3; y++){ // check 3x3
for (int x = 0; x < 3; x++){
if (get((r / 3) * 3 + y , (c / 3) * 3 + x) == num){
return false;
}
}
}
return true;
}
return false;
}
char sudokuboard::get(size_t r, size_t c) const
// Return char at position r,c
{
return sboard[r][c];
}
void sudokuboard::remove(size_t r, size_t c)
// Replace char at postion r,c with an empty space
{
sboard[r][c] = '_';
}
bool sudokuboard::solved()
// Check to see if there are any empty spaces on the board
{
for (int r = 0; r < 9; r++){
for (int c = 0; c < 9; c++){
if (sboard[r][c] == '_')
return false;
}
}
return true;
} | [
"easiruwa@hamilton.edu"
] | easiruwa@hamilton.edu |
8ab12cfbb0447560230698d0f7a93bd730e7b4f3 | 22c300690f403c57297fb3d7a1e7a9bf820b85cf | /src/controls/QskScrollView.cpp | a61be872408339eb622c80cc1a8343b23338c446 | [
"BSD-3-Clause"
] | permissive | SammyEnigma/qskinny | 8cf88ae5a7be791f0745b4aba5e5338d94879f99 | db056e783754b7971d737a88ac86a7be97eea6d2 | refs/heads/master | 2023-08-24T23:16:53.923549 | 2023-04-11T12:56:39 | 2023-04-11T13:54:24 | 509,579,338 | 0 | 0 | BSD-3-Clause | 2023-09-14T06:48:12 | 2022-07-01T20:19:54 | C++ | UTF-8 | C++ | false | false | 8,069 | cpp | /******************************************************************************
* QSkinny - Copyright (C) 2016 Uwe Rathmann
* SPDX-License-Identifier: BSD-3-Clause
*****************************************************************************/
#include "QskScrollView.h"
#include "QskAnimationHint.h"
#include "QskBoxBorderMetrics.h"
#include "QskEvent.h"
QSK_SUBCONTROL( QskScrollView, Panel )
QSK_SUBCONTROL( QskScrollView, Viewport )
QSK_SUBCONTROL( QskScrollView, HorizontalScrollBar )
QSK_SUBCONTROL( QskScrollView, HorizontalScrollHandle )
QSK_SUBCONTROL( QskScrollView, VerticalScrollBar )
QSK_SUBCONTROL( QskScrollView, VerticalScrollHandle )
QSK_SYSTEM_STATE( QskScrollView, VerticalHandlePressed, QskAspect::FirstSystemState << 1 )
QSK_SYSTEM_STATE( QskScrollView, HorizontalHandlePressed, QskAspect::FirstSystemState << 2 )
class QskScrollView::PrivateData
{
public:
PrivateData()
: horizontalScrollBarPolicy( Qt::ScrollBarAsNeeded )
, verticalScrollBarPolicy( Qt::ScrollBarAsNeeded )
, isScrolling( 0 )
{
}
Qt::ScrollBarPolicy horizontalScrollBarPolicy;
Qt::ScrollBarPolicy verticalScrollBarPolicy;
qreal scrollPressPos;
int isScrolling;
};
QskScrollView::QskScrollView( QQuickItem* parent )
: Inherited( parent )
, m_data( new PrivateData() )
{
}
QskScrollView::~QskScrollView()
{
}
QskAnimationHint QskScrollView::flickHint() const
{
return effectiveAnimation( QskAspect::Metric,
QskScrollView::Viewport, QskAspect::NoState );
}
void QskScrollView::setVerticalScrollBarPolicy( Qt::ScrollBarPolicy policy )
{
if ( policy != m_data->verticalScrollBarPolicy )
{
m_data->verticalScrollBarPolicy = policy;
update();
Q_EMIT verticalScrollBarPolicyChanged();
}
}
Qt::ScrollBarPolicy QskScrollView::verticalScrollBarPolicy() const
{
return m_data->verticalScrollBarPolicy;
}
void QskScrollView::setHorizontalScrollBarPolicy( Qt::ScrollBarPolicy policy )
{
if ( policy != m_data->horizontalScrollBarPolicy )
{
m_data->horizontalScrollBarPolicy = policy;
update();
Q_EMIT horizontalScrollBarPolicyChanged();
}
}
Qt::ScrollBarPolicy QskScrollView::horizontalScrollBarPolicy() const
{
return m_data->horizontalScrollBarPolicy;
}
bool QskScrollView::isScrolling( Qt::Orientation orientation ) const
{
return m_data->isScrolling == orientation;
}
QRectF QskScrollView::viewContentsRect() const
{
// This code should be done in the skinlet. TODO ...
const qreal bw = boxBorderMetricsHint( Viewport ).widthAt( Qt::TopEdge );
const QRectF r = subControlRect( Viewport );
return r.adjusted( bw, bw, -bw, -bw );
}
void QskScrollView::mousePressEvent( QMouseEvent* event )
{
const auto mousePos = qskMousePosition( event );
if ( subControlRect( VerticalScrollBar ).contains( mousePos ) )
{
const QRectF handleRect = subControlRect( VerticalScrollHandle );
if ( handleRect.contains( mousePos ) )
{
m_data->isScrolling = Qt::Vertical;
m_data->scrollPressPos = mousePos.y();
setSkinStateFlag( VerticalHandlePressed, true );
}
else
{
const QRectF vRect = viewContentsRect();
qreal y = scrollPos().y();
if ( mousePos.y() < handleRect.top() )
y -= vRect.height();
else
y += vRect.height();
setScrollPos( QPointF( scrollPos().x(), y ) );
}
return;
}
if ( subControlRect( HorizontalScrollBar ).contains( mousePos ) )
{
const QRectF handleRect = subControlRect( HorizontalScrollHandle );
if ( handleRect.contains( mousePos ) )
{
m_data->isScrolling = Qt::Horizontal;
m_data->scrollPressPos = mousePos.x();
setSkinStateFlag( HorizontalHandlePressed, true );
}
else
{
const QRectF vRect = viewContentsRect();
qreal x = scrollPos().x();
if ( mousePos.x() < handleRect.left() )
x -= vRect.width();
else
x += vRect.width();
setScrollPos( QPointF( x, scrollPos().y() ) );
}
return;
}
Inherited::mousePressEvent( event );
}
void QskScrollView::mouseMoveEvent( QMouseEvent* event )
{
if ( !m_data->isScrolling )
{
Inherited::mouseMoveEvent( event );
return;
}
const auto mousePos = qskMousePosition( event );
QPointF pos = scrollPos();
if ( m_data->isScrolling == Qt::Horizontal )
{
const qreal dx = mousePos.x() - m_data->scrollPressPos;
const qreal w = subControlRect( HorizontalScrollBar ).width();
pos.rx() += dx / w * scrollableSize().width();
m_data->scrollPressPos = mousePos.x();
}
else if ( m_data->isScrolling == Qt::Vertical )
{
const qreal dy = mousePos.y() - m_data->scrollPressPos;
const qreal h = subControlRect( VerticalScrollBar ).height();
pos.ry() += dy / h * scrollableSize().height();
m_data->scrollPressPos = mousePos.y();
}
if ( pos != scrollPos() )
setScrollPos( pos );
}
void QskScrollView::mouseReleaseEvent( QMouseEvent* event )
{
if ( !m_data->isScrolling )
{
Inherited::mouseReleaseEvent( event );
return;
}
m_data->isScrolling = 0;
m_data->scrollPressPos = 0;
setSkinStateFlag( HorizontalHandlePressed, false );
setSkinStateFlag( VerticalHandlePressed, false );
}
#ifndef QT_NO_WHEELEVENT
QPointF QskScrollView::scrollOffset( const QWheelEvent* event ) const
{
QPointF offset;
const auto pos = qskWheelPosition( event );
const auto viewRect = viewContentsRect();
if ( subControlRect( VerticalScrollBar ).contains( pos ) )
{
const auto steps = qskWheelSteps( event );
offset.setY( steps );
}
else if ( subControlRect( HorizontalScrollBar ).contains( pos ) )
{
const auto steps = qskWheelSteps( event );
offset.setX( steps );
}
else if ( viewRect.contains( pos ) )
{
offset = event->pixelDelta();
if ( offset.isNull() )
offset = event->angleDelta() / QWheelEvent::DefaultDeltasPerStep;
}
if ( !offset.isNull() )
{
const auto vs = viewRect.size() / 3.0;
offset.rx() *= vs.width();
offset.ry() *= vs.height();
}
return offset;
}
#endif
Qt::Orientations QskScrollView::scrollableOrientations() const
{
// layoutRect ???
const QRectF vr = contentsRect();
auto policyVertical = m_data->verticalScrollBarPolicy;
auto policyHorizontal = m_data->horizontalScrollBarPolicy;
if ( policyVertical == Qt::ScrollBarAsNeeded )
{
qreal height = vr.height();
if ( policyHorizontal == Qt::ScrollBarAlwaysOn )
height -= metric( HorizontalScrollBar | QskAspect::Size );
if ( scrollableSize().height() > height )
policyVertical = Qt::ScrollBarAlwaysOn;
}
if ( policyHorizontal == Qt::ScrollBarAsNeeded )
{
qreal width = vr.width();
if ( policyVertical == Qt::ScrollBarAlwaysOn )
width -= metric( VerticalScrollBar | QskAspect::Size );
if ( scrollableSize().width() > width )
{
policyHorizontal = Qt::ScrollBarAlwaysOn;
// we have to check the vertical once more
if ( ( policyVertical == Qt::ScrollBarAsNeeded ) &&
( scrollableSize().height() >
vr.height() - metric( HorizontalScrollBar | QskAspect::Size ) ) )
{
policyVertical = Qt::ScrollBarAlwaysOn;
}
}
}
Qt::Orientations orientations;
if ( policyHorizontal == Qt::ScrollBarAlwaysOn )
orientations |= Qt::Horizontal;
if ( policyVertical == Qt::ScrollBarAlwaysOn )
orientations |= Qt::Vertical;
return orientations;
}
#include "moc_QskScrollView.cpp"
| [
"Uwe.Rathmann@tigertal.de"
] | Uwe.Rathmann@tigertal.de |
5574c0b80e543a0068f7df92819476fb164dbc3e | 4b62cd73e5c255f2b1b0512421c510c011be2ec6 | /2019/roundB/Building_Palindromes.cpp | b7657c315a31b58975bd667cf74c8984d13123b7 | [] | no_license | dishankgoel/KickStart-Solutions | a48cce9421b3427c344eeabe51db5d0a4e9060aa | d51dd6265d44becd8eaa6c04e7db7d15bc35ab21 | refs/heads/master | 2023-07-30T07:25:19.830062 | 2021-09-11T18:57:18 | 2021-09-11T18:57:18 | 356,865,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cpp | #include<bits/stdc++.h>
#define ll long long
using namespace std;
ll test_case() {
ll n, q; cin>>n>>q;
string blocks; cin>>blocks;
vector<vector<int>> dp(n, vector<int>(26, 0));
for(int i = 0; i < n; i++) {
if(i == 0) {
dp[0][blocks[0] - 'A'] = 1;
} else {
dp[i] = dp[i - 1];
dp[i][blocks[i] - 'A'] = dp[i][blocks[i] - 'A'] + 1;
}
}
ll ans = 0;
for(int i = 0; i < q; i++) {
ll l, r; cin>>l>>r;
l--; r--;
ll num_odd = 0;
for(int j = 0; j < 26; j++) {
int freq;
if(l == 0) {
freq = dp[r][j];
} else {
freq = dp[r][j] - dp[l - 1][j];
}
if(freq%2 == 1) {
num_odd++;
}
}
if(num_odd <= 1) {
ans++;
}
}
return ans;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
for(int case_no = 0; case_no < t; case_no++) {
ll ans = test_case();
cout<<"Case #"<<case_no+1<<": "<<ans<<"\n";
}
}
| [
"dishankgoel1729@gmail.com"
] | dishankgoel1729@gmail.com |
07bcfb268e18813ae167b515e654eeff721bcc2d | 966a7bf92b7afb988c917d20483cd50b0d083cd7 | /main.cpp | 39cf35cfb3fd278cae25ba4cf6f7907cf3416ee9 | [] | no_license | anhpham197/Chim_bay_SDL2 | d456d5bbaa5c7ec22b86162e8acedf8b88c71c5f | 794317d1193021bcaba960b8adc377fdb712c2ed | refs/heads/master | 2022-07-03T14:39:05.308452 | 2020-05-13T17:24:34 | 2020-05-13T17:24:34 | 257,076,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,966 | cpp | #include "BaseObject.h"
#include "CommonFunction.h"
#include "character.h"
#include "GameMap.h"
#include "ImpTimer.h"
#include "TextObject.h"
#include "Enemy.h"
#include "Explosion.h"
#include <SDL.h>
#include <Windows.h>
BaseObject g_background;
TTF_Font* font_time; // tao doi tuong font
bool InitData()
{
bool success = true;
int ret = SDL_Init(SDL_INIT_VIDEO); // thiết lập môi trường ban đầu cho SDL
if (ret < 0) return false;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); // thiết lập chế độ tỉ lệ với chất lượng
g_window = SDL_CreateWindow("CHIM_BAY - MSV:19021219", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN); // tạo cửa sổ hiển thị
if (g_window == NULL) success = false;
else
{
g_screen = SDL_CreateRenderer(g_window,-1,SDL_RENDERER_ACCELERATED);
if (g_screen == NULL) success = false;
else
{
SDL_SetRenderDrawColor(g_screen, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR);
int imgflags = IMG_INIT_PNG;
if (!(IMG_Init(imgflags) && imgflags))
success = false;
}
}
//AUDIO
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1)
{
printf("%s", Mix_GetError());
}
g_sound = Mix_LoadMUS("sound/audio.mp3");
if (g_sound == NULL)
{
printf("%s", Mix_GetError());
}
// TEXT
if (TTF_Init() == -1)
{
success = false;
}
font_time = TTF_OpenFont("Font//dlxfont_.ttf", 30);
if (font_time == NULL)
{
printf ("&s",TTF_GetError());
}
return success;
}
bool LoadBackground()
{
bool ret = g_background.LoadImg("Images//background3.jpg", g_screen);
if (ret == false)
return false;
return true;
}
void close()
{
g_background.Free();
SDL_DestroyRenderer(g_screen);
g_screen = NULL;
SDL_DestroyWindow(g_window);
g_window = NULL;
IMG_Quit();
SDL_Quit();
}
int main(int argc, char* argv[])
{
ImpTimer fps_time;
if (InitData() == false)
return -1;
if (LoadBackground() == false)
return -1;
// INITIALIZE GAME_MAP
GameMap tube;
tube.LoadMap("tube/map.txt");
tube.LoadTiles(g_screen);
// INITIALIZE MAIN CHARACTER
character p_player;
p_player.LoadImg("Images//bird.png", g_screen);
// INITIALIZE ENEMY
Enemy p_enemy;
p_enemy.LoadImg("Images//enemy.png", g_screen);
p_enemy.set_x_pos(1664);
p_enemy.set_y_pos(0);
// INITIALIZE TEXTOBJECT
TextObject time_game; // game_time
time_game.SetColor(TextObject::WHITE_TEXT);
TextObject num_of_defeat; // số lần bắn trúng đạn và enemy
num_of_defeat.SetColor(TextObject::WHITE_TEXT);
// SET UP SURVIVAL INDEX
int num_of_death = 0;
// INITIALIZE ITEM FOR ENEMY
character_item* p_item = new character_item();
p_enemy.InitItem(p_item, g_screen);
// INITIALIZE EXPLOSION
Explosion exp;
bool tRet = exp.LoadImg("Images//explosion.png", g_screen);
if (!tRet) return -1;
exp.set_clip();
bool is_quit = false;
// INITIALIZE MENU
int ret_menu = SDLCommonFunction::ShowMenu(g_screen, font_time);
if (ret_menu == 1)
{
is_quit = true;
}
while (!is_quit)
{
if (!Mix_PlayingMusic())
Mix_PlayMusic(g_sound, 0); // thay 0 = so am => so lan phat lai nhac la vo tan
fps_time.start();
while (SDL_PollEvent(&g_event) != 0)
{
if (g_event.type == SDL_QUIT)
is_quit = true;
p_player.HandleInputAction(g_event, g_screen);
}
SDL_SetRenderDrawColor(g_screen, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR, RENDER_DRAW_COLOR);
SDL_RenderClear(g_screen);
g_background.Render(g_screen, NULL);
Map map_data = tube.getMap();
p_player.HandleItem(g_screen);
p_player.SetMapXY(map_data.start_x, map_data.start_y); // thiết lập lại bản đồ theo di chuyển của nvat
int ret = p_player.DoPlayer(map_data);
p_player.Show(g_screen);
tube.SetMap(map_data);
tube.DrawMap(g_screen);
p_enemy.SetMapXY(map_data.start_x, map_data.start_y);
p_enemy.DoPlayer(map_data);
p_enemy.MakeItem(g_screen, SCREEN_WIDTH, SCREEN_HEIGHT);
p_enemy.Show(g_screen);
// GET RECT OF EXPLOSION
int frame_exp_width = exp.get_frame_width();
int frame_exp_height = exp.get_frame_heigh();
// CHECK COLLISION BETWEEN BULLET OF ENEMY AND MAIN CHARACTER
SDL_Rect pRect; // player rect
pRect.x = p_player.GetRect().x;
pRect.y = p_player.GetRect().y;
pRect.w = p_player.GetRect().w;
pRect.h = p_player.GetRect().h;
bool bCol1 = false;
std::vector <character_item*> tBulletList = p_enemy.get_item_list();
for (int j = 0; j < tBulletList.size(); j++) {
character_item* pt_bullet = tBulletList[j];
if (pt_bullet) {
bCol1 = SDLCommonFunction::CheckCollison(pt_bullet->GetRect(), pRect);
if (bCol1) {
// EXPLOSION BETWEEN BULLET OF ENEMY AND MAIN CHARACTER
for (int ex = 0; ex < NUM_OF_FRAMES; ex++)
{
int x_pos = p_item->GetRect().x - frame_exp_width * 0.5;
int y_pos = p_item->GetRect().y - frame_exp_height * 0.5;
exp.set_frame(ex);
exp.SetRect(x_pos, y_pos);
exp.Show(g_screen);
SDL_RenderPresent(g_screen);
}
p_enemy.RemoveBullet(j);
break;
}
}
}
SDL_Rect tRect; // threat rect
tRect.x = p_enemy.GetRect().x;
tRect.y = p_enemy.GetRect().y;
tRect.w = p_enemy.GetRect().w;
tRect.h = p_enemy.GetRect().h;
bool bCol2 = SDLCommonFunction::CheckCollison(pRect, tRect); // collision between player and threat
if (bCol1 || bCol2) {
// EXPLOSION BETWEEN ENEMY AND MAIN CHARACTER
for (int ex = 0; ex < NUM_OF_FRAMES; ex++)
{
int x_pos = p_player.GetRect().x + p_player.GetRect().w - frame_exp_width * 0.5;
int y_pos = p_player.GetRect().y + p_player.GetRect().h- frame_exp_height * 0.5;
exp.set_frame(ex);
exp.SetRect(x_pos, y_pos);
exp.Show(g_screen);
SDL_RenderPresent(g_screen);
}
Mix_Chunk* beep_sound = Mix_LoadWAV("sound/game_over.wav");
if (beep_sound != NULL)
Mix_PlayChannel(-1, beep_sound, 0);
MessageBox(NULL, L"Oops! You've been hit ! ! !", L"Info", MB_ICONERROR | MB_OK);
is_quit = true;
}
// CHECK COLLISION BETWEEN BULLET OF MAIN CHARACTER AND ENEMY
std::vector<character_item*> bullet_arr = p_player.get_item_list();
for (int i = 0; i < bullet_arr.size(); i++)
{
character_item* p_bullet = bullet_arr[i];
if (p_bullet != NULL) {
SDL_Rect tRect;
tRect.x = p_enemy.GetRect().x;
tRect.y = p_enemy.GetRect().y;
tRect.w = p_enemy.GetRect().w;
tRect.h = p_enemy.GetRect().h;
SDL_Rect bRect = p_bullet->GetRect();
bool bCol = SDLCommonFunction::CheckCollison(bRect, tRect);
if (bCol) {
//EXPLOSION BETWEEN BULLET OF MAIN CHARACTER AND ENEMY
for (int ex = 0; ex < NUM_OF_FRAMES; ex++)
{
int x_pos = p_enemy.GetRect().x - frame_exp_width * 0.5;
int y_pos = p_enemy.GetRect().y - frame_exp_height * 0.5;
exp.set_frame(ex);
exp.SetRect(x_pos, y_pos);
exp.Show(g_screen);
SDL_RenderPresent(g_screen);
}
num_of_death++;
if (num_of_death < 3) {
p_enemy.SetRect(1664, 0);
}
else {
for (int j = 0; j < tBulletList.size(); j++) {
p_enemy.RemoveBullet(j);
}
p_player.RemoveBullet(i);
p_enemy.Free();
}
}
}
}
// SHOW GAME STATUS
if (ret == 1)
{
Mix_Chunk* beep_sound = Mix_LoadWAV("sound/game_over.wav");
if (beep_sound != NULL)
Mix_PlayChannel(-1, beep_sound, 0);
MessageBox(NULL, L"GAME OVER !", L"Info", MB_ICONERROR | MB_OK);
is_quit = true;
}
else if (ret == -1 && num_of_death >= 3)
{
Mix_Chunk* beep_sound = Mix_LoadWAV("sound/win_game.wav");
if (beep_sound != NULL)
Mix_PlayChannel(-1, beep_sound, 0);
MessageBox(NULL, L"YOU'VE WIN THE GAME !", L"Info", MB_ICONASTERISK | MB_OK);
is_quit = true;
}
// SHOW GAME TIME
std::string str_time = "Time left : ";
Uint32 time_val = SDL_GetTicks() / 1000; // doi ve giay
Uint32 val_time = 500 - time_val; // dem nguoc;
if (val_time <= 0)
{
Mix_Chunk* beep_sound = Mix_LoadWAV("sound/game_over.wav");
if (beep_sound != NULL)
Mix_PlayChannel(-1, beep_sound, 0);
MessageBox(NULL, L"GAMEOVER !", L"Info", MB_ICONERROR | MB_OK);
is_quit = true;
}
else
{
std::string str_val = std::to_string(val_time);
str_time += str_val;
time_game.SetText(str_time);
time_game.LoadFromRenderText(font_time, g_screen);
time_game.RenderText(g_screen, 10, 20);
}
std::string num_of_Death = std::to_string(num_of_death);
std::string survival("DEFEATED : ");
survival += num_of_Death;
num_of_defeat.SetText(survival);
num_of_defeat.LoadFromRenderText(font_time, g_screen);
num_of_defeat.RenderText(g_screen, 800, 20);
SDL_RenderPresent(g_screen);
// FPS
int real_imp_time = fps_time.get_ticks(); // thời gian thực sự đã trôi qua
int time_of_one_frame = 1000 / frame_per_second; // đơn vị : ms
if (real_imp_time < time_of_one_frame) // nếu thời gian chạy thực bé hơn (nhanh hơn so với cài đặt) -> phải tạo độ trễ
{
int delay_time = time_of_one_frame - real_imp_time;
SDL_Delay(delay_time); // nếu là dương thì delay_time tự truyền vào, nếu là âm thì delay_time tự convert về 0
// delay_time càng lớn <=> frame_per_second (FPS) càng nhỏ => ctrinh càng chậm
// tăng FPS để ctrinh chạy nhanh, MAX_FPS = 1000 / real_imp_time;
// phải giảm real_time <=> máy có cấu hình lớn : thời gian thực hiện lệnh ít
}
}
p_player.Free();
close();
SDL_Quit();
return 0;
}
| [
"19021219@vnu.edu.vn"
] | 19021219@vnu.edu.vn |
12ee2a96480c917b164e73ddbb93b59fc0f59f1b | fab03e072dd5a48eb22b5b4eba58960ee1f2b7d1 | /src/irc.cpp | 71427caf57178aee70794a67e5d2690bec6a139e | [
"MIT"
] | permissive | erfan007p/litecoinstake-source | 8f3c825748b3648c7f35104a75fb7a445fc926a9 | ad1ed4df8b4754e3ae819e357413a88bd3fd8967 | refs/heads/master | 2021-05-16T04:52:06.996080 | 2017-10-08T23:52:14 | 2017-10-08T23:52:14 | 106,218,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,998 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
while (true)
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
while (true)
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
MilliSleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
while (true)
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("litecoinstake-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRIu64"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
MilliSleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #litecoinstakeTEST\r");
Send(hSocket, "WHO #litecoinstakeTEST\r");
} else {
// randomly join #litecoinstake00-#litecoinstake05
int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
//int channel_number = 0;
Send(hSocket, strprintf("JOIN #litecoinstake%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #litecoinstake%02d\r", channel_number).c_str());
}
int64_t nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
| [
"erfan007p@gmail.com"
] | erfan007p@gmail.com |
64b0960ad5cea0ad7b9876ae634a3c2daf7b9ceb | 2c62385f15b1f8e6072138d5175d7a70dd236b98 | /blazetest/src/mathtest/hybridmatrix/ClassTest.cpp | 175fee35beef88f5ce6ea7f8976784cfa6d7ef40 | [
"BSD-3-Clause"
] | permissive | lyxm/blaze | 665e4c6f6e1a717973d2d98e148c720030843266 | 10dbaa368790316b5e044cfe9b92f5534f60a2dc | refs/heads/master | 2021-01-12T20:31:45.197297 | 2015-10-15T21:39:17 | 2015-10-15T21:39:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235,735 | cpp | //=================================================================================================
/*!
// \file src/mathtest/hybridmatrix/ClassTest.cpp
// \brief Source file for the HybridMatrix class test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// 3. Neither the names of the Blaze development group 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 HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blaze/util/Complex.h>
#include <blaze/util/Random.h>
#include <blaze/util/UniqueArray.h>
#include <blazetest/mathtest/hybridmatrix/ClassTest.h>
#include <blazetest/mathtest/RandomMaximum.h>
#include <blazetest/mathtest/RandomMinimum.h>
namespace blazetest {
namespace mathtest {
namespace hybridmatrix {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the HybridMatrix class test.
//
// \exception std::runtime_error Operation error detected.
*/
ClassTest::ClassTest()
{
testAlignment< char >( "char" );
testAlignment< signed char >( "signed char" );
testAlignment< unsigned char >( "unsigned char" );
testAlignment< wchar_t >( "wchar_t" );
testAlignment< short >( "short" );
testAlignment< unsigned short >( "unsigned short" );
testAlignment< int >( "int" );
testAlignment< unsigned int >( "unsigned int" );
testAlignment< long >( "long" );
testAlignment< unsigned long >( "unsigned long" );
testAlignment< float >( "float" );
testAlignment< double >( "double" );
testAlignment< complex<char> >( "complex<char>" );
testAlignment< complex<signed char> >( "complex<signed char>" );
testAlignment< complex<unsigned char> >( "complex<unsigned char>" );
testAlignment< complex<wchar_t> >( "complex<wchar_t>" );
testAlignment< complex<short> >( "complex<short>" );
testAlignment< complex<unsigned short> >( "complex<unsigned short>" );
testAlignment< complex<int> >( "complex<int>" );
testAlignment< complex<unsigned int> >( "complex<unsigned int>" );
testAlignment< complex<float> >( "complex<float>" );
testAlignment< complex<double> >( "complex<double>" );
testConstructors();
testAssignment();
testAddAssign();
testSubAssign();
testMultAssign();
testScaling();
testFunctionCall();
testIterator();
testNonZeros();
testReset();
testClear();
testResize();
testExtend();
testTranspose();
testSwap();
testIsDefault();
}
//*************************************************************************************************
//=================================================================================================
//
// TEST FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Test of the HybridMatrix constructors.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all constructors of the HybridMatrix class template.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testConstructors()
{
//=====================================================================================
// Row-major default constructor
//=====================================================================================
// Default constructor
{
test_ = "Row-major HybridMatrix default constructor";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
//=====================================================================================
// Row-major size constructor
//=====================================================================================
{
test_ = "Row-major HybridMatrix size constructor (0x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 0UL, 0UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix size constructor (0x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 0UL, 4UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix size constructor (3x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 3UL, 0UL );
checkRows ( mat, 3UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix size constructor (3x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 3UL, 4UL );
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
}
//=====================================================================================
// Row-major homogeneous initialization
//=====================================================================================
{
test_ = "Row-major HybridMatrix homogeneous initialization constructor (0x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 0UL, 0UL, 2 );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix homogeneous initialization constructor (0x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 0UL, 4UL, 2 );
checkRows ( mat, 0UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix homogeneous initialization constructor (3x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 3UL, 0UL, 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Row-major HybridMatrix homogeneous initialization constructor (3x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 3UL, 4UL, 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
checkNonZeros( mat, 12UL );
checkNonZeros( mat, 0UL, 4UL );
checkNonZeros( mat, 1UL, 4UL );
checkNonZeros( mat, 2UL, 4UL );
if( mat(0,0) != 2 || mat(0,1) != 2 || mat(0,2) != 2 || mat(0,3) != 2 ||
mat(1,0) != 2 || mat(1,1) != 2 || mat(1,2) != 2 || mat(1,3) != 2 ||
mat(2,0) != 2 || mat(2,1) != 2 || mat(2,2) != 2 || mat(2,3) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 2 2 2 )\n( 2 2 2 2 )\n( 2 2 2 2 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major array initialization
//=====================================================================================
{
test_ = "Row-major HybridMatrix dynamic array initialization constructor";
blaze::UniqueArray<int> array( new int[6] );
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL, array.get() );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major HybridMatrix static array initialization constructor";
const int array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( array );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major copy constructor
//=====================================================================================
{
test_ = "Row-major HybridMatrix copy constructor (0x0)";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 0UL, 0UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( mat1 );
checkRows ( mat2, 0UL );
checkColumns ( mat2, 0UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Row-major HybridMatrix copy constructor (0x3)";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 0UL, 3UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( mat1 );
checkRows ( mat2, 0UL );
checkColumns ( mat2, 3UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Row-major HybridMatrix copy constructor (2x0)";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 0UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( mat1 );
checkRows ( mat2, 2UL );
checkColumns ( mat2, 0UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Row-major HybridMatrix copy constructor (2x3)";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( mat1 );
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 3UL );
checkNonZeros( mat2, 1UL, 3UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major default constructor
//=====================================================================================
{
test_ = "Column-major HybridMatrix default constructor";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
//=====================================================================================
// Column-major size constructor
//=====================================================================================
{
test_ = "Column-major HybridMatrix size constructor (0x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 0UL, 0UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix size constructor (0x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 0UL, 4UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix size constructor (3x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 3UL, 0UL );
checkRows ( mat, 3UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix size constructor (3x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 3UL, 4UL );
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
}
//=====================================================================================
// Column-major homogeneous initialization
//=====================================================================================
{
test_ = "Column-major HybridMatrix homogeneous initialization constructor (0x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 0UL, 0UL, 2 );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix homogeneous initialization constructor (0x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 0UL, 4UL, 2 );
checkRows ( mat, 0UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix homogeneous initialization constructor (3x0)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 3UL, 0UL, 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
{
test_ = "Column-major HybridMatrix homogeneous initialization constructor (3x4)";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 3UL, 4UL, 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
checkNonZeros( mat, 12UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
checkNonZeros( mat, 2UL, 3UL );
checkNonZeros( mat, 3UL, 3UL );
if( mat(0,0) != 2 || mat(0,1) != 2 || mat(0,2) != 2 || mat(0,3) != 2 ||
mat(1,0) != 2 || mat(1,1) != 2 || mat(1,2) != 2 || mat(1,3) != 2 ||
mat(2,0) != 2 || mat(2,1) != 2 || mat(2,2) != 2 || mat(2,3) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 2 2 2 )\n( 2 2 2 2 )\n( 2 2 2 2 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major array initialization
//=====================================================================================
{
test_ = "Column-major HybridMatrix dynamic array initialization constructor";
blaze::UniqueArray<int> array( new int[6] );
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL, array.get() );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 3 || mat(0,2) != 5 ||
mat(1,0) != 2 || mat(1,1) != 4 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 3 5 )\n( 2 4 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major HybridMatrix static array initialization constructor";
const int array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( array );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major copy constructor
//=====================================================================================
{
test_ = "Column-major HybridMatrix copy constructor (0x0)";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 0UL, 0UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( mat1 );
checkRows ( mat2, 0UL );
checkColumns ( mat2, 0UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Column-major HybridMatrix copy constructor (0x3)";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 0UL, 3UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( mat1 );
checkRows ( mat2, 0UL );
checkColumns ( mat2, 3UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Column-major HybridMatrix copy constructor (2x0)";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 0UL );
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( mat1 );
checkRows ( mat2, 2UL );
checkColumns ( mat2, 0UL );
checkNonZeros( mat2, 0UL );
}
{
test_ = "Column-major HybridMatrix copy constructor (2x3)";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( mat1 );
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Construction failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all assignment operators of the HybridMatrix class template.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testAssignment()
{
//=====================================================================================
// Row-major homogeneous assignment
//=====================================================================================
{
test_ = "Row-major HybridMatrix homogeneous assignment";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat( 3UL, 4UL );
mat = 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
checkNonZeros( mat, 12UL );
checkNonZeros( mat, 0UL, 4UL );
checkNonZeros( mat, 1UL, 4UL );
checkNonZeros( mat, 2UL, 4UL );
if( mat(0,0) != 2 || mat(0,1) != 2 || mat(0,2) != 2 || mat(0,3) != 2 ||
mat(1,0) != 2 || mat(1,1) != 2 || mat(1,2) != 2 || mat(1,3) != 2 ||
mat(2,0) != 2 || mat(2,1) != 2 || mat(2,2) != 2 || mat(2,3) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 2 2 2 )\n( 2 2 2 2 )\n( 2 2 2 2 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major array assignment
//=====================================================================================
{
test_ = "Row-major HybridMatrix array assignment";
const int array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat;
mat = array;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major copy assignment
//=====================================================================================
{
test_ = "Row-major HybridMatrix copy assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 3UL );
checkNonZeros( mat2, 1UL, 3UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major HybridMatrix copy assignment stress test";
typedef blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major dense matrix assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix dense matrix assignment";
blaze::DynamicMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 3UL );
checkNonZeros( mat2, 1UL, 3UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix assignment stress test";
typedef blaze::DynamicMatrix<int,blaze::rowMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 3UL );
checkNonZeros( mat2, 1UL, 3UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix assignment stress test";
typedef blaze::DynamicMatrix<int,blaze::columnMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix sparse matrix assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 0 ||
mat2(1,0) != 3 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix assignment stress test";
typedef blaze::CompressedMatrix<int,blaze::rowMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 0 ||
mat2(1,0) != 3 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix assignment stress test";
typedef blaze::CompressedMatrix<int,blaze::columnMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::rowMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major homogeneous assignment
//=====================================================================================
{
test_ = "Column-major HybridMatrix homogeneous assigment";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat( 3UL, 4UL );
mat = 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 4UL );
checkCapacity( mat, 12UL );
checkNonZeros( mat, 12UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
checkNonZeros( mat, 2UL, 3UL );
checkNonZeros( mat, 3UL, 3UL );
if( mat(0,0) != 2 || mat(0,1) != 2 || mat(0,2) != 2 || mat(0,3) != 2 ||
mat(1,0) != 2 || mat(1,1) != 2 || mat(1,2) != 2 || mat(1,3) != 2 ||
mat(2,0) != 2 || mat(2,1) != 2 || mat(2,2) != 2 || mat(2,3) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 2 2 2 )\n( 2 2 2 2 )\n( 2 2 2 2 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major array assignment
//=====================================================================================
{
test_ = "Column-major HybridMatrix array initialization constructor";
const int array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat;
mat = array;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major copy assignment
//=====================================================================================
{
test_ = "Column-major HybridMatrix copy assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major HybridMatrix copy assignment stress test";
typedef blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major dense matrix assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix dense matrix assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix assignment stress test";
typedef blaze::DynamicMatrix<int,blaze::rowMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix assignment";
blaze::DynamicMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(0,2) = 3;
mat1(1,0) = 4;
mat1(1,1) = 5;
mat1(1,2) = 6;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 6UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 3 ||
mat2(1,0) != 4 || mat2(1,1) != 5 || mat2(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix assignment stress test";
typedef blaze::DynamicMatrix<int,blaze::columnMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix sparse matrix assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 1UL );
checkNonZeros( mat2, 2UL, 1UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 0 ||
mat2(1,0) != 3 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix assignment stress test";
typedef blaze::CompressedMatrix<int,blaze::rowMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2;
mat2 = mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 1UL );
checkNonZeros( mat2, 2UL, 1UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 || mat2(0,2) != 0 ||
mat2(1,0) != 3 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix assignment stress test";
typedef blaze::CompressedMatrix<int,blaze::columnMajor> RandomMatrixType;
blaze::HybridMatrix<int,10UL,10UL,blaze::columnMajor> mat1;
const int min( randmin );
const int max( randmax );
for( size_t i=0UL; i<100UL; ++i )
{
const size_t rows ( blaze::rand<size_t>( 0UL, 10UL ) );
const size_t columns( blaze::rand<size_t>( 0UL, 10UL ) );
const RandomMatrixType mat2( blaze::rand<RandomMatrixType>( rows, columns, min, max ) );
mat1 = mat2;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL );
randomize( mat2 );
mat2 = mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix addition assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the addition assignment operators of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testAddAssign()
{
//=====================================================================================
// Row-major dense matrix addition assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix dense matrix addition assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix addition assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix addition assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix sparse matrix addition assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix addition assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix addition assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix dense matrix addition assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix addition assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix addition assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix sparse matrix addition assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix addition assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix addition assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix addition assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix addition assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 += mat1;
if( mat1 != mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix subtraction assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the subtraction assignment operators of the HybridMatrix
// class template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testSubAssign()
{
//=====================================================================================
// Row-major dense matrix subtraction assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix dense matrix subtraction assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix subtraction assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix dense matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix subtraction assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix sparse matrix subtraction assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix subtraction assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = -3;
mat1(1,2) = 4;
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 += mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major HybridMatrix sparse matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix subtraction assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix dense matrix subtraction assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix subtraction assignment";
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat1( 2UL, 3UL, 0 );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix dense matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix dense matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix subtraction assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix sparse matrix subtraction assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix subtraction assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 2UL, 3UL, 4UL );
mat1(0,0) = -1;
mat1(0,1) = -2;
mat1(1,0) = 3;
mat1(1,2) = -4;
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL, 0 );
mat2(0,1) = -2;
mat2(0,2) = 6;
mat2(1,0) = 5;
mat2 -= mat1;
checkRows ( mat2, 2UL );
checkColumns ( mat2, 3UL );
checkCapacity( mat2, 6UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 0UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 0 || mat2(0,2) != 6 ||
mat2(1,0) != 2 || mat2(1,1) != 0 || mat2(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 0 6 )\n( 2 0 4 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix subtraction assignment (lower)";
blaze::LowerMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix subtraction assignment (upper)";
blaze::UpperMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major HybridMatrix sparse matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major HybridMatrix sparse matrix subtraction assignment (diagonal)";
blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > mat1( 3UL );
randomize( mat1 );
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2 -= mat1;
if( mat1 != -mat2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n" << mat2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix multiplication assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the multiplication assignment operators of the HybridMatrix
// class template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testMultAssign()
{
//=====================================================================================
// Row-major dense matrix multiplication assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix dense matrix multiplication assignment";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat1( 3UL, 4UL, 0 );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix multiplication assignment";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat1( 3UL, 4UL, 0 );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix multiplication assignment
//=====================================================================================
{
test_ = "Row-major/row-major HybridMatrix sparse matrix multiplication assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 3UL, 4UL, 5UL );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix multiplication assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 3UL, 4UL, 5UL );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 2UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix multiplication assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix dense matrix multiplication assignment";
blaze::HybridMatrix<int,3UL,4UL,blaze::rowMajor> mat1( 3UL, 4UL, 0 );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 1UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 0UL );
checkNonZeros( mat2, 3UL, 3UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix dense matrix multiplication assignment";
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat1( 3UL, 4UL, 0 );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 1UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 0UL );
checkNonZeros( mat2, 3UL, 3UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix multiplication assignment
//=====================================================================================
{
test_ = "Column-major/row-major HybridMatrix sparse matrix multiplication assignment";
blaze::CompressedMatrix<int,blaze::rowMajor> mat1( 3UL, 4UL, 5UL );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 1UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 0UL );
checkNonZeros( mat2, 3UL, 3UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major HybridMatrix sparse matrix multiplication assignment";
blaze::CompressedMatrix<int,blaze::columnMajor> mat1( 3UL, 4UL, 5UL );
mat1(0,1) = 2;
mat1(1,0) = 1;
mat1(1,1) = 3;
mat1(1,3) = 4;
mat1(2,3) = 5;
blaze::HybridMatrix<int,3UL,4UL,blaze::columnMajor> mat2( 3UL, 3UL, 0 );
mat2(0,0) = 1;
mat2(0,2) = 2;
mat2(1,1) = 3;
mat2(2,0) = 4;
mat2(2,2) = 5;
mat2 *= mat1;
checkRows ( mat2, 3UL );
checkColumns ( mat2, 4UL );
checkNonZeros( mat2, 7UL );
checkNonZeros( mat2, 0UL, 1UL );
checkNonZeros( mat2, 1UL, 3UL );
checkNonZeros( mat2, 2UL, 0UL );
checkNonZeros( mat2, 3UL, 3UL );
if( mat2(0,0) != 0 || mat2(0,1) != 2 || mat2(0,2) != 0 || mat2(0,3) != 10 ||
mat2(1,0) != 3 || mat2(1,1) != 9 || mat2(1,2) != 0 || mat2(1,3) != 12 ||
mat2(2,0) != 0 || mat2(2,1) != 8 || mat2(2,2) != 0 || mat2(2,3) != 25 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 0 2 0 10 )\n( 3 9 0 12 )\n( 0 8 0 25 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of all HybridMatrix (self-)scaling operations.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all available ways to scale an instance of the HybridMatrix
// class template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testScaling()
{
//=====================================================================================
// Row-major self-scaling (M*=s)
//=====================================================================================
{
test_ = "Row-major self-scaling (M*=s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat *= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major self-scaling (M=M*s)
//=====================================================================================
{
test_ = "Row-major self-scaling (M=M*s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat = mat * 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major self-scaling (M=s*M)
//=====================================================================================
{
test_ = "Row-major self-scaling (M=s*M)";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat = 2 * mat;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major self-scaling (M/=s)
//=====================================================================================
{
test_ = "Row-major self-scaling (M/=s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 2;
mat(2,0) = -4;
mat(2,2) = 6;
mat /= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 1 ||
mat(2,0) != -2 || mat(2,1) != 0 || mat(2,2) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 1 )\n( -2 0 3 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major self-scaling (M=M/s)
//=====================================================================================
{
test_ = "Row-major self-scaling (M=M/s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 2;
mat(2,0) = -4;
mat(2,2) = 6;
mat = mat / 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 1 ||
mat(2,0) != -2 || mat(2,1) != 0 || mat(2,2) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 1 )\n( -2 0 3 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major HybridMatrix::scale()
//=====================================================================================
{
test_ = "Row-major HybridMatrix::scale() (int)";
// Initialization check
blaze::HybridMatrix<int,3UL,2UL,blaze::rowMajor> mat( 3UL, 2UL );
mat(0,0) = 1;
mat(0,1) = 2;
mat(1,0) = 3;
mat(1,1) = 4;
mat(2,0) = 5;
mat(2,1) = 6;
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 ||
mat(1,0) != 3 || mat(1,1) != 4 ||
mat(2,0) != 5 || mat(2,1) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 )\n( 3 4 )\n( 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Integral scaling of the matrix
mat.scale( 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 2 || mat(0,1) != 4 ||
mat(1,0) != 6 || mat(1,1) != 8 ||
mat(2,0) != 10 || mat(2,1) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 4 )\n( 6 8 )\n( 10 12 )\n";
throw std::runtime_error( oss.str() );
}
// Floating point scaling of the matrix
mat.scale( 0.5 );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 ||
mat(1,0) != 3 || mat(1,1) != 4 ||
mat(2,0) != 5 || mat(2,1) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 )\n( 3 4 )\n( 5 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major HybridMatrix::scale() (complex)";
using blaze::complex;
blaze::HybridMatrix<complex<float>,2UL,2UL,blaze::rowMajor> mat( 2UL, 2UL );
mat(0,0) = complex<float>( 1.0F, 0.0F );
mat(0,1) = complex<float>( 2.0F, 0.0F );
mat(1,0) = complex<float>( 3.0F, 0.0F );
mat(1,1) = complex<float>( 4.0F, 0.0F );
mat.scale( complex<float>( 3.0F, 0.0F ) );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 4UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
if( mat(0,0) != complex<float>( 3.0F, 0.0F ) || mat(0,1) != complex<float>( 6.0F, 0.0F ) ||
mat(1,0) != complex<float>( 9.0F, 0.0F ) || mat(1,1) != complex<float>( 12.0F, 0.0F ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( ( 3,0) ( 6,0)\n( 9,0) (12,0) )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major self-scaling (M*=s)
//=====================================================================================
{
test_ = "Column-major self-scaling (M*=s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat *= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major self-scaling (M=M*s)
//=====================================================================================
{
test_ = "Column-major self-scaling (M=M*s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat = mat * 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major self-scaling (M=s*M)
//=====================================================================================
{
test_ = "Column-major self-scaling (M=s*M)";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 1;
mat(2,0) = -2;
mat(2,2) = 3;
mat = 2 * mat;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 2 ||
mat(2,0) != -4 || mat(2,1) != 0 || mat(2,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 2 )\n( -4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major self-scaling (M/=s)
//=====================================================================================
{
test_ = "Column-major self-scaling (M/=s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 2;
mat(2,0) = -4;
mat(2,2) = 6;
mat /= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 1 ||
mat(2,0) != -2 || mat(2,1) != 0 || mat(2,2) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 1 )\n( -2 0 3 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major self-scaling (M=M/s)
//=====================================================================================
{
test_ = "Column-major self-scaling (M=M/s)";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat( 3UL, 3UL, 0 );
mat(1,2) = 2;
mat(2,0) = -4;
mat(2,2) = 6;
mat = mat / 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 1 ||
mat(2,0) != -2 || mat(2,1) != 0 || mat(2,2) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed self-scaling operation\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 1 )\n( -2 0 3 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major HybridMatrix::scale()
//=====================================================================================
{
test_ = "Column-major HybridMatrix::scale() (int)";
// Initialization check
blaze::HybridMatrix<int,3UL,2UL,blaze::columnMajor> mat( 3UL, 2UL );
mat(0,0) = 1;
mat(0,1) = 4;
mat(1,0) = 2;
mat(1,1) = 5;
mat(2,0) = 3;
mat(2,1) = 6;
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 4 ||
mat(1,0) != 2 || mat(1,1) != 5 ||
mat(2,0) != 3 || mat(2,1) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 4 )\n( 2 5 )\n( 3 6 )\n";
throw std::runtime_error( oss.str() );
}
// Integral scaling of the matrix
mat.scale( 2 );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 2 || mat(0,1) != 8 ||
mat(1,0) != 4 || mat(1,1) != 10 ||
mat(2,0) != 6 || mat(2,1) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 2 8 )\n( 4 10 )\n( 6 12 )\n";
throw std::runtime_error( oss.str() );
}
// Floating point scaling of the matrix
mat.scale( 0.5 );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 4 ||
mat(1,0) != 2 || mat(1,1) != 5 ||
mat(2,0) != 3 || mat(2,1) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 4 )\n( 2 5 )\n( 3 6 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major HybridMatrix::scale() (complex)";
using blaze::complex;
blaze::HybridMatrix<complex<float>,2UL,2UL,blaze::columnMajor> mat( 2UL, 2UL );
mat(0,0) = complex<float>( 1.0F, 0.0F );
mat(0,1) = complex<float>( 2.0F, 0.0F );
mat(1,0) = complex<float>( 3.0F, 0.0F );
mat(1,1) = complex<float>( 4.0F, 0.0F );
mat.scale( complex<float>( 3.0F, 0.0F ) );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 4UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
if( mat(0,0) != complex<float>( 3.0F, 0.0F ) || mat(0,1) != complex<float>( 6.0F, 0.0F ) ||
mat(1,0) != complex<float>( 9.0F, 0.0F ) || mat(1,1) != complex<float>( 12.0F, 0.0F ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scale operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( ( 3,0) ( 6,0)\n( 9,0) (12,0) )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix function call operator.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of adding and accessing elements via the function call operator
// of the HybridMatrix class template. In case an error is detected, a \a std::runtime_error
// exception is thrown.
*/
void ClassTest::testFunctionCall()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::operator()";
// Assignment to the element (2,1)
blaze::HybridMatrix<int,3UL,5UL,blaze::rowMajor> mat( 3UL, 5UL, 0 );
mat(2,1) = 1;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 1UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 0 )\n( 0 0 0 0 0 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (1,4)
mat(1,4) = 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 2UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(1,4) != 2 || mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 0 )\n( 0 0 0 0 2 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (0,3)
mat(0,3) = 3;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(0,3) != 3 || mat(1,4) != 2 || mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (2,2)
mat(2,2) = 4;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,3) != 3 || mat(1,4) != 2 || mat(2,1) != 1 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 1 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Addition assignment to the element (2,1)
mat(2,1) += mat(0,3);
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,3) != 3 || mat(1,4) != 2 || mat(2,1) != 4 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Subtraction assignment to the element (1,0)
mat(1,0) -= mat(1,4);
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,3) != 3 || mat(1,0) != -2 || mat(1,4) != 2 || mat(2,1) != 4 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( -2 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Multiplication assignment to the element (0,3)
mat(0,3) *= -3;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,3) != -9 || mat(1,0) != -2 || mat(1,4) != 2 || mat(2,1) != 4 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 -3 0 )\n( -2 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Division assignment to the element (2,1)
mat(2,1) /= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,3) != -9 || mat(1,0) != -2 || mat(1,4) != 2 || mat(2,1) != 2 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 -3 0 )\n( -2 0 0 0 2 )\n( 0 2 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::operator()";
// Assignment to the element (2,1)
blaze::HybridMatrix<int,3UL,5UL,blaze::columnMajor> mat( 3UL, 5UL, 0 );
mat(2,1) = 1;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 1UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 0UL );
checkNonZeros( mat, 3UL, 0UL );
checkNonZeros( mat, 4UL, 0UL );
if( mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 0 )\n( 0 0 0 0 0 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (1,4)
mat(1,4) = 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 2UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 0UL );
checkNonZeros( mat, 3UL, 0UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(1,4) != 2 || mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 0 )\n( 0 0 0 0 2 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (0,3)
mat(0,3) = 3;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 0UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(0,3) != 3 || mat(1,4) != 2 || mat(2,1) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 1 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Assignment to the element (2,2)
mat(2,2) = 4;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(0,3) != 3 || mat(1,4) != 2 || mat(2,1) != 1 || mat(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 1 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Addition assignment to the element (2,1)
mat(2,1) += mat(0,3);
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(2,1) != 4 || mat(2,2) != 4 || mat(0,3) != 3 || mat(1,4) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( 0 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Subtraction assignment to the element (1,0)
mat(1,0) -= mat(1,4);
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(1,0) != -2 || mat(2,1) != 4 || mat(2,2) != 4 || mat(0,3) != 3 || mat(1,4) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 3 0 )\n( -2 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Multiplication assignment to the element (0,3)
mat(0,3) *= -3;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(1,0) != -2 || mat(2,1) != 4 || mat(2,2) != 4 || mat(0,3) != -9 || mat(1,4) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 -9 0 )\n( -2 0 0 0 2 )\n( 0 4 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Division assignment to the element (2,1)
mat(2,1) /= 2;
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 1UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 1UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 1UL );
if( mat(1,0) != -2 || mat(2,1) != 2 || mat(2,2) != 4 || mat(0,3) != -9 || mat(1,4) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 -9 0 )\n( -2 0 0 0 2 )\n( 0 2 4 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the HybridMatrix iterator implementation.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the iterator implementation of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testIterator()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
typedef blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> MatrixType;
typedef MatrixType::Iterator Iterator;
typedef MatrixType::ConstIterator ConstIterator;
MatrixType mat( 3UL, 3UL, 0 );
mat(0,1) = 1;
mat(1,0) = -2;
mat(1,2) = -3;
mat(2,1) = 4;
mat(2,2) = 5;
// Testing the Iterator default constructor
{
test_ = "Row-major Iterator default constructor";
Iterator it = Iterator();
if( it != Iterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing the ConstIterator default constructor
{
test_ = "Row-major ConstIterator default constructor";
ConstIterator it = ConstIterator();
if( it != ConstIterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing conversion from Iterator to ConstIterator
{
test_ = "Row-major Iterator/ConstIterator conversion";
ConstIterator it( begin( mat, 1UL ) );
if( it == end( mat, 1UL ) || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator conversion detected\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 0th row via Iterator
{
test_ = "Row-major Iterator subtraction";
const size_t number( end( mat, 0UL ) - begin( mat, 0UL ) );
if( number != 3UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 3\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st row via ConstIterator
{
test_ = "Row-major ConstIterator subtraction";
const size_t number( cend( mat, 1UL ) - cbegin( mat, 1UL ) );
if( number != 3UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 3\n";
throw std::runtime_error( oss.str() );
}
}
// Testing read-only access via ConstIterator
{
test_ = "Row-major read-only access via ConstIterator";
ConstIterator it ( cbegin( mat, 2UL ) );
ConstIterator end( cend( mat, 2UL ) );
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid initial iterator detected\n";
throw std::runtime_error( oss.str() );
}
++it;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-increment failed\n";
throw std::runtime_error( oss.str() );
}
--it;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it++;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-increment failed\n";
throw std::runtime_error( oss.str() );
}
it--;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it += 2UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator addition assignment failed\n";
throw std::runtime_error( oss.str() );
}
it -= 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator subtraction assignment failed\n";
throw std::runtime_error( oss.str() );
}
it = it + 2UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar addition failed\n";
throw std::runtime_error( oss.str() );
}
it = it - 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar subtraction failed\n";
throw std::runtime_error( oss.str() );
}
it = 3UL + it;
if( it != end ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scalar/iterator addition failed\n";
throw std::runtime_error( oss.str() );
}
}
// Testing assignment via Iterator
{
test_ = "Row-major assignment via Iterator";
int value = 7;
for( Iterator it=begin( mat, 2UL ); it!=end( mat, 2UL ); ++it ) {
*it = value++;
}
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 0 ||
mat(1,0) != -2 || mat(1,1) != 0 || mat(1,2) != -3 ||
mat(2,0) != 7 || mat(2,1) != 8 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 0 )\n( -2 0 -3 )\n( 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing addition assignment via Iterator
{
test_ = "Row-major addition assignment via Iterator";
int value = 4;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it += value++;
}
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 0 ||
mat(1,0) != 2 || mat(1,1) != 5 || mat(1,2) != 3 ||
mat(2,0) != 7 || mat(2,1) != 8 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 0 )\n( 2 5 3 )\n( 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing subtraction assignment via Iterator
{
test_ = "Row-major subtraction assignment via Iterator";
int value = 4;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it -= value++;
}
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 0 ||
mat(1,0) != -2 || mat(1,1) != 0 || mat(1,2) != -3 ||
mat(2,0) != 7 || mat(2,1) != 8 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 0 )\n( -2 0 -3 )\n( 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing multiplication assignment via Iterator
{
test_ = "Row-major multiplication assignment via Iterator";
int value = 2;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it *= value++;
}
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 0 ||
mat(1,0) != -4 || mat(1,1) != 0 || mat(1,2) != -12 ||
mat(2,0) != 7 || mat(2,1) != 8 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 0 )\n( -4 0 -12 )\n( 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing division assignment via Iterator
{
test_ = "Row-major division assignment via Iterator";
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it /= 2;
}
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 0 ||
mat(1,0) != -2 || mat(1,1) != 0 || mat(1,2) != -6 ||
mat(2,0) != 7 || mat(2,1) != 8 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Division assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 0 )\n( -2 0 -6 )\n( 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
typedef blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> MatrixType;
typedef MatrixType::Iterator Iterator;
typedef MatrixType::ConstIterator ConstIterator;
MatrixType mat( 3UL, 3UL, 0 );
mat(1,0) = 1;
mat(0,1) = -2;
mat(2,1) = -3;
mat(1,2) = 4;
mat(2,2) = 5;
// Testing the Iterator default constructor
{
test_ = "Column-major Iterator default constructor";
Iterator it = Iterator();
if( it != Iterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing the ConstIterator default constructor
{
test_ = "Column-major ConstIterator default constructor";
ConstIterator it = ConstIterator();
if( it != ConstIterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing conversion from Iterator to ConstIterator
{
test_ = "Column-major Iterator/ConstIterator conversion";
ConstIterator it( begin( mat, 1UL ) );
if( it == end( mat, 1UL ) || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator conversion detected\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 0th column via Iterator
{
test_ = "Column-major Iterator subtraction";
const size_t number( end( mat, 0UL ) - begin( mat, 0UL ) );
if( number != 3UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 3\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st row via ConstIterator
{
test_ = "Column-major ConstIterator subtraction";
const size_t number( cend( mat, 1UL ) - cbegin( mat, 1UL ) );
if( number != 3UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 3\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 2nd row
{
test_ = "Column-major iterator subtraction";
const size_t number( end( mat, 2UL ) - begin( mat, 2UL ) );
if( number != 3UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 3\n";
throw std::runtime_error( oss.str() );
}
}
// Testing read-only access via ConstIterator
{
test_ = "Column-major read-only access via ConstIterator";
ConstIterator it ( cbegin( mat, 2UL ) );
ConstIterator end( cend( mat, 2UL ) );
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid initial iterator detected\n";
throw std::runtime_error( oss.str() );
}
++it;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-increment failed\n";
throw std::runtime_error( oss.str() );
}
--it;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it++;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-increment failed\n";
throw std::runtime_error( oss.str() );
}
it--;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it += 2UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator addition assignment failed\n";
throw std::runtime_error( oss.str() );
}
it -= 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator subtraction assignment failed\n";
throw std::runtime_error( oss.str() );
}
it = it + 2UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar addition failed\n";
throw std::runtime_error( oss.str() );
}
it = it - 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar subtraction failed\n";
throw std::runtime_error( oss.str() );
}
it = 3UL + it;
if( it != end ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scalar/iterator addition failed\n";
throw std::runtime_error( oss.str() );
}
}
// Testing assignment via Iterator
{
test_ = "Column-major assignment via Iterator";
int value = 7;
for( Iterator it=begin( mat, 2UL ); it!=end( mat, 2UL ); ++it ) {
*it = value++;
}
if( mat(0,0) != 0 || mat(0,1) != -2 || mat(0,2) != 7 ||
mat(1,0) != 1 || mat(1,1) != 0 || mat(1,2) != 8 ||
mat(2,0) != 0 || mat(2,1) != -3 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 -2 7 )\n( 1 0 8 )\n( 0 -3 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing addition assignment via Iterator
{
test_ = "Column-major addition assignment via Iterator";
int value = 4;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it += value++;
}
if( mat(0,0) != 0 || mat(0,1) != 2 || mat(0,2) != 7 ||
mat(1,0) != 1 || mat(1,1) != 5 || mat(1,2) != 8 ||
mat(2,0) != 0 || mat(2,1) != 3 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 2 7 )\n( 1 5 8 )\n( 0 3 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing subtraction assignment via Iterator
{
test_ = "Column-major subtraction assignment via Iterator";
int value = 4;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it -= value++;
}
if( mat(0,0) != 0 || mat(0,1) != -2 || mat(0,2) != 7 ||
mat(1,0) != 1 || mat(1,1) != 0 || mat(1,2) != 8 ||
mat(2,0) != 0 || mat(2,1) != -3 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 -2 7 )\n( 1 0 8 )\n( 0 -3 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing multiplication assignment via Iterator
{
test_ = "Column-major multiplication assignment via Iterator";
int value = 2;
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it *= value++;
}
if( mat(0,0) != 0 || mat(0,1) != -4 || mat(0,2) != 7 ||
mat(1,0) != 1 || mat(1,1) != 0 || mat(1,2) != 8 ||
mat(2,0) != 0 || mat(2,1) != -12 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 -2 7 )\n( 1 0 8 )\n( 0 -6 9 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing division assignment via Iterator
{
test_ = "Column-major division assignment via Iterator";
for( Iterator it=begin( mat, 1UL ); it!=end( mat, 1UL ); ++it ) {
*it /= 2;
}
if( mat(0,0) != 0 || mat(0,1) != -2 || mat(0,2) != 7 ||
mat(1,0) != 1 || mat(1,1) != 0 || mat(1,2) != 8 ||
mat(2,0) != 0 || mat(2,1) != -6 || mat(2,2) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Division assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 -2 7 )\n( 1 0 8 )\n( 0 -6 9 )\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c nonZeros() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c nonZeros() member function of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testNonZeros()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::nonZeros()";
{
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL, 0 );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 0UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 0UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL, 0 );
mat(0,1) = 1;
mat(0,2) = 2;
mat(1,1) = 3;
mat(1,2) = 0;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 1UL );
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 2 ||
mat(1,0) != 0 || mat(1,1) != 3 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 2 )\n( 0 3 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::nonZeros()";
{
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL, 0 );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 0UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 0UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL, 0 );
mat(0,1) = 1;
mat(0,2) = 2;
mat(1,1) = 3;
mat(1,2) = 0;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(0,0) != 0 || mat(0,1) != 1 || mat(0,2) != 2 ||
mat(1,0) != 0 || mat(1,1) != 3 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 1 2 )\n( 0 3 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c reset() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c reset() member function of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testReset()
{
using blaze::reset;
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::reset()";
// Initialization check
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL );
mat(0,0) = 1;
mat(0,1) = 2;
mat(0,2) = 3;
mat(1,0) = 4;
mat(1,1) = 5;
mat(1,2) = 6;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting a single element
reset( mat(0,2) );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 0 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 0 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting row 1
reset( mat, 1UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 2UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 0UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting the entire matrix
reset( mat );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 0UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 0UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::reset()";
// Initialization check
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL );
mat(0,0) = 1;
mat(0,1) = 2;
mat(0,2) = 3;
mat(1,0) = 4;
mat(1,1) = 5;
mat(1,2) = 6;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting a single element
reset( mat(0,2) );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 0 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 0 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting column 1
reset( mat, 1UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 3UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 4 || mat(1,1) != 0 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 0 )\n( 4 0 6 )\n";
throw std::runtime_error( oss.str() );
}
// Resetting the entire matrix
reset( mat );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 0UL );
checkNonZeros( mat, 0UL, 0UL );
checkNonZeros( mat, 1UL, 0UL );
checkNonZeros( mat, 2UL, 0UL );
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 ||
mat(1,0) != 0 || mat(1,1) != 0 || mat(1,2) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c clear() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c clear() member function of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testClear()
{
using blaze::clear;
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::clear()";
// Initialization check
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL );
mat(0,0) = 1;
mat(0,1) = 2;
mat(0,2) = 3;
mat(1,0) = 4;
mat(1,1) = 5;
mat(1,2) = 6;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Clearing a single element
clear( mat(0,2) );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 0 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 0 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Clearing the matrix
clear( mat );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::clear()";
// Initialization check
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL );
mat(0,0) = 1;
mat(0,1) = 2;
mat(0,2) = 3;
mat(1,0) = 4;
mat(1,1) = 5;
mat(1,2) = 6;
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 6UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 3 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 3 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Clearing a single element
clear( mat(0,2) );
checkRows ( mat, 2UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 6UL );
checkNonZeros( mat, 5UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 1UL );
if( mat(0,0) != 1 || mat(0,1) != 2 || mat(0,2) != 0 ||
mat(1,0) != 4 || mat(1,1) != 5 || mat(1,2) != 6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 0 )\n( 4 5 6 )\n";
throw std::runtime_error( oss.str() );
}
// Clearing the matrix
clear( mat );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c resize() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c resize() member function of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testResize()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::resize()";
// Initialization check
blaze::HybridMatrix<int,5UL,3UL,blaze::rowMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Resizing to 0x3
mat.resize( 0UL, 3UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 0UL );
// Resizing to 5x0
mat.resize( 5UL, 0UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Resizing to 2x1
mat.resize( 2UL, 1UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 1UL );
checkCapacity( mat, 2UL );
// Resizing to 3x2 and preserving the elements
mat(0,0) = 1;
mat(1,0) = 2;
mat.resize( 3UL, 2UL, true );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
if( mat(0,0) != 1 || mat(1,0) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Resizing the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 x )\n( 2 x )\n( x x )\n";
throw std::runtime_error( oss.str() );
}
// Resizing to 2x2 and preserving the elements
mat(0,1) = 3;
mat(1,1) = 4;
mat.resize( 2UL, 2UL, true );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 4UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 3 || mat(1,0) != 2 || mat(1,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Resizing the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 3 )\n( 2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Resizing to 1x1
mat.resize( 1UL, 1UL );
checkRows ( mat, 1UL );
checkColumns ( mat, 1UL );
checkCapacity( mat, 1UL );
// Resizing to 0x0
mat.resize( 0UL, 0UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::resize()";
// Initialization check
blaze::HybridMatrix<int,5UL,3UL,blaze::columnMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Resizing to 0x3
mat.resize( 0UL, 3UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 3UL );
checkNonZeros( mat, 0UL );
// Resizing to 5x0
mat.resize( 5UL, 0UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Resizing to 2x1
mat.resize( 2UL, 1UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 1UL );
checkCapacity( mat, 2UL );
// Resizing to 3x2 and preserving the elements
mat(0,0) = 1;
mat(1,0) = 2;
mat.resize( 3UL, 2UL, true );
checkRows ( mat, 3UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 6UL );
if( mat(0,0) != 1 || mat(1,0) != 2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Resizing the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 x )\n( 2 x )\n( x x )\n";
throw std::runtime_error( oss.str() );
}
// Resizing to 2x2 and preserving the elements
mat(0,1) = 3;
mat(1,1) = 4;
mat.resize( 2UL, 2UL, true );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 4UL );
checkNonZeros( mat, 4UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 3 || mat(1,0) != 2 || mat(1,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Resizing the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 3 )\n( 2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Resizing to 1x1
mat.resize( 1UL, 1UL );
checkRows ( mat, 1UL );
checkColumns ( mat, 1UL );
checkCapacity( mat, 1UL );
// Resizing to 0x0
mat.resize( 0UL, 0UL );
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c extend() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c extend() member function of the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testExtend()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix::extend()";
// Initialization check
blaze::HybridMatrix<int,7UL,13UL,blaze::rowMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Increasing the size of the matrix
mat.extend( 2UL, 2UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 3UL );
// Further increasing the size of the matrix and preserving the elements
mat(0,0) = 1;
mat(0,1) = 2;
mat(1,0) = 3;
mat(1,1) = 4;
mat.extend( 1UL, 1UL, true );
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 9UL );
if( mat(0,0) != 1 || mat(0,1) != 2 ||
mat(1,0) != 3 || mat(1,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Extending the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 x )\n( 3 4 x )\n( x x x )\n";
throw std::runtime_error( oss.str() );
}
// Further increasing the size of the matrix
mat.extend( 4UL, 10UL, false );
checkRows ( mat, 7UL );
checkColumns ( mat, 13UL );
checkCapacity( mat, 91UL );
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix::extend()";
// Initialization check
blaze::HybridMatrix<int,7UL,13UL,blaze::columnMajor> mat;
checkRows ( mat, 0UL );
checkColumns ( mat, 0UL );
checkNonZeros( mat, 0UL );
// Increasing the size of the matrix
mat.extend( 2UL, 2UL );
checkRows ( mat, 2UL );
checkColumns ( mat, 2UL );
checkCapacity( mat, 3UL );
// Further increasing the size of the matrix and preserving the elements
mat(0,0) = 1;
mat(0,1) = 2;
mat(1,0) = 3;
mat(1,1) = 4;
mat.extend( 1UL, 1UL, true );
checkRows ( mat, 3UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 9UL );
if( mat(0,0) != 1 || mat(0,1) != 2 ||
mat(1,0) != 3 || mat(1,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Extending the matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 2 x )\n( 3 4 x )\n( x x x )\n";
throw std::runtime_error( oss.str() );
}
// Further increasing the size of the matrix
mat.extend( 4UL, 10UL, false );
checkRows ( mat, 7UL );
checkColumns ( mat, 13UL );
checkCapacity( mat, 91UL );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c transpose() member function of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c transpose() member function of the HybridMatrix
// class template. Additionally, it performs a test of self-transpose via the \c trans()
// function. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testTranspose()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major self-transpose via HybridMatrix::transpose()";
// Self-transpose of a 3x5 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::rowMajor> mat( 3UL, 5UL, 0 );
mat(0,0) = 1;
mat(0,2) = 2;
mat(0,4) = 3;
mat(1,1) = 4;
mat(1,3) = 5;
mat(2,0) = 6;
mat(2,2) = 7;
mat(2,4) = 8;
mat.transpose();
checkRows ( mat, 5UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 6 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 ||
mat(2,0) != 2 || mat(2,1) != 0 || mat(2,2) != 7 ||
mat(3,0) != 0 || mat(3,1) != 5 || mat(3,2) != 0 ||
mat(4,0) != 3 || mat(4,1) != 0 || mat(4,2) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 6 )\n( 0 4 0 )\n( 2 0 7 )\n( 0 5 0 )\n( 3 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
// Self-transpose of a 5x3 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::rowMajor> mat( 5UL, 3UL, 0 );
mat(0,0) = 1;
mat(0,2) = 6;
mat(1,1) = 4;
mat(2,0) = 2;
mat(2,2) = 7;
mat(3,1) = 5;
mat(4,0) = 3;
mat(4,2) = 8;
mat.transpose();
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 2 || mat(0,3) != 0 || mat(0,4) != 3 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 || mat(1,3) != 5 || mat(1,4) != 0 ||
mat(2,0) != 6 || mat(2,1) != 0 || mat(2,2) != 7 || mat(2,3) != 0 || mat(2,4) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 2 0 3 )\n( 0 4 0 5 0 )\n( 6 0 7 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Row-major self-transpose via trans()";
// Self-transpose of a 3x5 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::rowMajor> mat( 3UL, 5UL, 0 );
mat(0,0) = 1;
mat(0,2) = 2;
mat(0,4) = 3;
mat(1,1) = 4;
mat(1,3) = 5;
mat(2,0) = 6;
mat(2,2) = 7;
mat(2,4) = 8;
mat = trans( mat );
checkRows ( mat, 5UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 6 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 ||
mat(2,0) != 2 || mat(2,1) != 0 || mat(2,2) != 7 ||
mat(3,0) != 0 || mat(3,1) != 5 || mat(3,2) != 0 ||
mat(4,0) != 3 || mat(4,1) != 0 || mat(4,2) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 6 )\n( 0 4 0 )\n( 2 0 7 )\n( 0 5 0 )\n( 3 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
// Self-transpose of a 5x3 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::rowMajor> mat( 5UL, 3UL, 0 );
mat(0,0) = 1;
mat(0,2) = 6;
mat(1,1) = 4;
mat(2,0) = 2;
mat(2,2) = 7;
mat(3,1) = 5;
mat(4,0) = 3;
mat(4,2) = 8;
mat = trans( mat );
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 2 || mat(0,3) != 0 || mat(0,4) != 3 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 || mat(1,3) != 5 || mat(1,4) != 0 ||
mat(2,0) != 6 || mat(2,1) != 0 || mat(2,2) != 7 || mat(2,3) != 0 || mat(2,4) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 2 0 3 )\n( 0 4 0 5 0 )\n( 6 0 7 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major self-transpose via HybridMatrix::transpose()";
// Self-transpose of a 3x5 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::columnMajor> mat( 3UL, 5UL, 0 );
mat(0,0) = 1;
mat(0,2) = 2;
mat(0,4) = 3;
mat(1,1) = 4;
mat(1,3) = 5;
mat(2,0) = 6;
mat(2,2) = 7;
mat(2,4) = 8;
mat.transpose();
checkRows ( mat, 5UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 6 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 ||
mat(2,0) != 2 || mat(2,1) != 0 || mat(2,2) != 7 ||
mat(3,0) != 0 || mat(3,1) != 5 || mat(3,2) != 0 ||
mat(4,0) != 3 || mat(4,1) != 0 || mat(4,2) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 6 )\n( 0 4 0 )\n( 2 0 7 )\n( 0 5 0 )\n( 3 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
// Self-transpose of a 5x3 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::columnMajor> mat( 5UL, 3UL, 0 );
mat(0,0) = 1;
mat(0,2) = 6;
mat(1,1) = 4;
mat(2,0) = 2;
mat(2,2) = 7;
mat(3,1) = 5;
mat(4,0) = 3;
mat(4,2) = 8;
mat.transpose();
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 2 || mat(0,3) != 0 || mat(0,4) != 3 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 || mat(1,3) != 5 || mat(1,4) != 0 ||
mat(2,0) != 6 || mat(2,1) != 0 || mat(2,2) != 7 || mat(2,3) != 0 || mat(2,4) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 2 0 3 )\n( 0 4 0 5 0 )\n( 6 0 7 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
}
{
test_ = "Column-major self-transpose via trans()";
// Self-transpose of a 3x5 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::columnMajor> mat( 3UL, 5UL, 0 );
mat(0,0) = 1;
mat(0,2) = 2;
mat(0,4) = 3;
mat(1,1) = 4;
mat(1,3) = 5;
mat(2,0) = 6;
mat(2,2) = 7;
mat(2,4) = 8;
mat = trans( mat );
checkRows ( mat, 5UL );
checkColumns ( mat, 3UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 3UL );
checkNonZeros( mat, 1UL, 2UL );
checkNonZeros( mat, 2UL, 3UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 6 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 ||
mat(2,0) != 2 || mat(2,1) != 0 || mat(2,2) != 7 ||
mat(3,0) != 0 || mat(3,1) != 5 || mat(3,2) != 0 ||
mat(4,0) != 3 || mat(4,1) != 0 || mat(4,2) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 6 )\n( 0 4 0 )\n( 2 0 7 )\n( 0 5 0 )\n( 3 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
// Self-transpose of a 5x3 matrix
{
blaze::HybridMatrix<int,5UL,5UL,blaze::columnMajor> mat( 5UL, 3UL, 0 );
mat(0,0) = 1;
mat(0,2) = 6;
mat(1,1) = 4;
mat(2,0) = 2;
mat(2,2) = 7;
mat(3,1) = 5;
mat(4,0) = 3;
mat(4,2) = 8;
mat = trans( mat );
checkRows ( mat, 3UL );
checkColumns ( mat, 5UL );
checkCapacity( mat, 15UL );
checkNonZeros( mat, 8UL );
checkNonZeros( mat, 0UL, 2UL );
checkNonZeros( mat, 1UL, 1UL );
checkNonZeros( mat, 2UL, 2UL );
checkNonZeros( mat, 3UL, 1UL );
checkNonZeros( mat, 4UL, 2UL );
if( mat(0,0) != 1 || mat(0,1) != 0 || mat(0,2) != 2 || mat(0,3) != 0 || mat(0,4) != 3 ||
mat(1,0) != 0 || mat(1,1) != 4 || mat(1,2) != 0 || mat(1,3) != 5 || mat(1,4) != 0 ||
mat(2,0) != 6 || mat(2,1) != 0 || mat(2,2) != 7 || mat(2,3) != 0 || mat(2,4) != 8 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 1 0 2 0 3 )\n( 0 4 0 5 0 )\n( 6 0 7 0 8 )\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c swap() functionality of the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c swap() function of the HybridMatrix class template.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testSwap()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major HybridMatrix swap";
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat1( 3UL, 2UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 0;
mat1(1,1) = 3;
mat1(2,0) = 4;
mat1(2,1) = 0;
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat2( 2UL, 3UL );
mat2(0,0) = 6;
mat2(0,1) = 5;
mat2(0,2) = 4;
mat2(1,0) = 3;
mat2(1,1) = 2;
mat2(1,2) = 1;
swap( mat1, mat2 );
checkRows ( mat1, 2UL );
checkColumns ( mat1, 3UL );
checkCapacity( mat1, 6UL );
checkNonZeros( mat1, 6UL );
checkNonZeros( mat1, 0UL, 3UL );
checkNonZeros( mat1, 1UL, 3UL );
if( mat1(0,0) != 6 || mat1(0,1) != 5 || mat1(0,2) != 4 ||
mat1(1,0) != 3 || mat1(1,1) != 2 || mat1(1,2) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Swapping the first matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n( 6 5 4 )\n( 3 2 1 )\n";
throw std::runtime_error( oss.str() );
}
checkRows ( mat2, 3UL );
checkColumns ( mat2, 2UL );
checkCapacity( mat2, 4UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 1UL );
checkNonZeros( mat2, 2UL, 1UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 ||
mat2(1,0) != 0 || mat2(1,1) != 3 ||
mat2(2,0) != 4 || mat2(2,1) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Swapping the second matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 )\n( 0 3 )\n( 4 0 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major HybridMatrix swap";
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat1( 3UL, 2UL );
mat1(0,0) = 1;
mat1(0,1) = 2;
mat1(1,0) = 0;
mat1(1,1) = 3;
mat1(2,0) = 4;
mat1(2,1) = 0;
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat2( 2UL, 3UL );
mat2(0,0) = 6;
mat2(0,1) = 5;
mat2(0,2) = 4;
mat2(1,0) = 3;
mat2(1,1) = 2;
mat2(1,2) = 1;
swap( mat1, mat2 );
checkRows ( mat1, 2UL );
checkColumns ( mat1, 3UL );
checkCapacity( mat1, 6UL );
checkNonZeros( mat1, 6UL );
checkNonZeros( mat1, 0UL, 2UL );
checkNonZeros( mat1, 1UL, 2UL );
checkNonZeros( mat1, 2UL, 2UL );
if( mat1(0,0) != 6 || mat1(0,1) != 5 || mat1(0,2) != 4 ||
mat1(1,0) != 3 || mat1(1,1) != 2 || mat1(1,2) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Swapping the first matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat1 << "\n"
<< " Expected result:\n( 6 5 4 )\n( 3 2 1 )\n";
throw std::runtime_error( oss.str() );
}
checkRows ( mat2, 3UL );
checkColumns ( mat2, 2UL );
checkCapacity( mat2, 4UL );
checkNonZeros( mat2, 4UL );
checkNonZeros( mat2, 0UL, 2UL );
checkNonZeros( mat2, 1UL, 2UL );
if( mat2(0,0) != 1 || mat2(0,1) != 2 ||
mat2(1,0) != 0 || mat2(1,1) != 3 ||
mat2(2,0) != 4 || mat2(2,1) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Swapping the second matrix failed\n"
<< " Details:\n"
<< " Result:\n" << mat2 << "\n"
<< " Expected result:\n( 1 2 )\n( 0 3 )\n( 4 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c isDefault() function with the HybridMatrix class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c isDefault() function with the HybridMatrix class
// template. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void ClassTest::testIsDefault()
{
using blaze::isDefault;
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major isDefault() function";
// isDefault with 0x0 matrix
{
blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> mat;
if( isDefault( mat ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with default matrix
{
blaze::HybridMatrix<int,2UL,3UL,blaze::rowMajor> mat( 2UL, 3UL, 0 );
if( isDefault( mat(0,1) ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix element: " << mat(0,1) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( mat ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with non-default matrix
{
blaze::HybridMatrix<int,3UL,2UL,blaze::rowMajor> mat( 3UL, 2UL, 0 );
mat(0,1) = 1;
if( isDefault( mat(0,1) ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix element: " << mat(0,1) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( mat ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major isDefault() function";
// isDefault with 0x0 matrix
{
blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> mat;
if( isDefault( mat ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with default matrix
{
blaze::HybridMatrix<int,2UL,3UL,blaze::columnMajor> mat( 2UL, 3UL, 0 );
if( isDefault( mat(0,1) ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix element: " << mat(0,1) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( mat ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with non-default matrix
{
blaze::HybridMatrix<int,3UL,2UL,blaze::columnMajor> mat( 3UL, 2UL, 0 );
mat(1,0) = 1;
if( isDefault( mat(1,0) ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix element: " << mat(1,0) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( mat ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
} // namespace hybridmatrix
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running HybridMatrix class test..." << std::endl;
try
{
RUN_HYBRIDMATRIX_CLASS_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during HybridMatrix class test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
c72546fa09fc13fa5e70eb7afdc73c46f638f37d | eb827d7993b146cf507b57a45e420fffdf641eef | /camps/lksh_winter2020/day4/src/gen.cpp | 6dc0a5e989f5d58dff95773318a1ef513f8ad282 | [] | no_license | khbminus/code2020 | dfdbcae71d61d03d4457aad47ff7d4136e6fcc1e | a0d2230b0905df79ba78cb98353f4ba03f16e8b0 | refs/heads/master | 2023-07-16T16:08:20.629283 | 2021-08-29T20:35:14 | 2021-08-29T20:35:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
int MAXN = 10;
int MAXC = 100;
int n = rnd() % MAXN + 1;
cout << n << '\n';
for (int i = 0; i < n; i++)
cout << rnd() % MAXC + 1 << " \n"[i + 1 == n];
} | [
"serega.haritontsev@gmail.com"
] | serega.haritontsev@gmail.com |
9f94354c7165ea26f21b8c1035a7db0eb819cc35 | 3b72c7a278e150117b075b8b79f57fe0c7035325 | /main.cpp | a9d814c322e8af98fced19d03992b132a18723cd | [] | no_license | matejanus/cpp_tetris | a332a63cd59fbaeda7067051fcd666f43f3d1f96 | fb89edd5eb0c7b5bcc4e57599f5d0b1ee382f1ff | refs/heads/master | 2020-12-14T15:27:35.119990 | 2020-01-20T21:51:23 | 2020-01-20T21:51:23 | 234,787,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,087 | cpp | #include <iostream>
#include "includes/tetermino.hpp"
#include <array>
#include <curses.h>
#include <chrono>
#include <thread>
#include <vector>
#include <memory>
#include <random>
#include <stdio.h>
using namespace std::chrono_literals;
// std::array<std::string, 7> tetromino;
const std::array<std::string, 7> tetromino = {"..X."
"..X."
"..X."
"..X.",
"..X."
".XX."
".X.."
"....",
".X.."
".XX."
"..X."
"....",
"...."
".XX."
".XX."
"....",
"..X."
".XX."
"..X."
"....",
"...."
".XX."
"..X."
"..X.",
"...."
"..XX"
"..X."
"..X."};
const int nFieldHeight = {18};
const int nFieldWidth = {12};
const int nScreenWidth = {80};
const int nScreenHeight = {20};
int rotate(int px, int py, int r)
{
switch (r % 4)
{
case 0:
return py * 4 + px; //0deg
case 1:
return 12 + py - (px * 4); //90deg
case 2:
return 15 - (py * 4) - px; //180deg
case 3:
return 3 - py + (px * 4); //270deg
}
return 0;
}
bool doesPieceFit(int nTetromino, int nRotaion, int nPosX, int nPosY, const std::array<unsigned char, (nFieldWidth * nFieldHeight)> &gameField)
{
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
{
int piece = rotate(x, y, nRotaion);
int field = (nPosY + y) * nFieldWidth + (nPosX + x);
if (nPosX + x >= 0 && nPosX + x < nFieldWidth)
{
if (nPosY + y >= 0 && nPosY + y < nFieldHeight)
{
if (tetromino[nTetromino][piece] == 'X' && gameField[field] != 0)
return false;
}
}
}
return true;
}
int main()
{
std::array<unsigned char, (nFieldWidth * nFieldHeight)>
pField = {0};
auto t = Tetermino();
auto d = t.getData();
for (int x = 0; x < nFieldWidth; x++)
{
for (int y = 0; y < nFieldHeight; y++)
{
pField[y * nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;
}
}
std::array<char, (nScreenWidth * nScreenHeight)> screen = {0};
for (int i = 0; i < nScreenWidth * nScreenHeight; i++)
{
screen[i] = L' ';
}
initscr();
WINDOW *win = newwin(nScreenHeight, nScreenWidth, 0, 0);
wrefresh(win);
wmove(win, 0, 0);
curs_set(0);
keypad(win, TRUE);
cbreak();
noecho();
nodelay(win, TRUE);
bool gameOver = {false};
int nCurrentRotation = {0};
int nCurrentX = {nFieldWidth / 2};
int nCurrentY = {0};
bool bRotateHold = {false};
int nSpeed = {20};
int nSpeedCounter = {0};
bool bForceDown = {0};
int nPieceCount = {0};
int nScore = {0};
std::vector<int> vLines;
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> gen(0, 6);
int nCurrentPiece = gen(rng);
while (!gameOver)
{
// Game timitng
std::this_thread::sleep_for(50ms);
nSpeedCounter++;
bForceDown = (nSpeedCounter == nSpeed);
// input
bool bKey[4] = {false};
// auto ch = wgetch(win);
switch (wgetch(win))
{
case KEY_RIGHT:
bKey[0] = true;
break;
case KEY_LEFT:
bKey[1] = true;
break;
case KEY_DOWN:
bKey[2] = true;
break;
case 122:
bKey[3] = true;
break;
default:
break;
}
// game logic
nCurrentX += (bKey[0] && doesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX + 1, nCurrentY, pField)) ? 1 : 0;
nCurrentX -= (bKey[1] && doesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX - 1, nCurrentY, pField)) ? 1 : 0;
nCurrentY += (bKey[2] && doesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1, pField)) ? 1 : 0;
if (bKey[3])
{
nCurrentRotation += (!bRotateHold && doesPieceFit(nCurrentPiece, nCurrentRotation + 1, nCurrentX, nCurrentY, pField)) ? 1 : 0;
bRotateHold = true;
}
else
{
bRotateHold = false;
}
if (bForceDown)
{
if (doesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1, pField))
{
nCurrentY++;
}
else
{
//lock te current piece
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
if (tetromino[nCurrentPiece][rotate(px, py, nCurrentRotation)] != '.')
{
pField[(nCurrentY + py) * nFieldWidth + (nCurrentX + px)] = nCurrentPiece + 1;
}
nPieceCount++;
if (nPieceCount % 10 == 0)
if (nSpeed >= 10)
nSpeed--;
//check for horizontal lines
for (int py = 0; py < 4; py++)
if (nCurrentY + py < nFieldHeight - 1)
{
bool bLine = true;
for (int px = 1; px < nFieldWidth - 1; px++)
bLine &= (pField[(nCurrentY + py) * nFieldWidth + px]) != 0;
if (bLine)
{
for (int px = 1; px < nFieldWidth - 1; px++)
pField[(nCurrentY + py) * nFieldWidth + px] = 8;
vLines.push_back(nCurrentY + py);
}
}
nScore += 25;
if (!vLines.empty())
{
nScore += (1 << vLines.size()) * 100;
}
//choose next piece
nCurrentX = nFieldWidth / 2;
nCurrentY = 0;
nCurrentRotation = 0;
nCurrentPiece = gen(rng);
//if piece does nof fit
gameOver = !doesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY, pField);
}
nSpeedCounter = 0;
}
// render output
//draw field
for (int x = 0; x < nFieldWidth; x++)
for (int y = 0; y < nFieldHeight; y++)
screen[(y + 2) * nScreenWidth + (x + 2)] = " ABCDEFG=#"[pField[y * nFieldWidth + x]];
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
if (tetromino[nCurrentPiece][rotate(px, py, nCurrentRotation)] == 'X')
{
screen[(nCurrentY + py + 2) * nScreenWidth + (nCurrentX + px + 2)] = nCurrentPiece + 65;
}
snprintf(&screen[(nScreenHeight - 1) * nScreenWidth + nFieldWidth + 6], 16, "SCORE: %8d", nScore); // TODO: find another way of appending to screen
if (!vLines.empty())
{
wprintw(win, screen.data());
wmove(win, 0, 0);
wrefresh(win);
std::this_thread::sleep_for(400ms);
for (auto &v : vLines)
{
for (int px = 1; px < nFieldWidth - 1; px++)
{
for (int py = v; py > 0; py--)
{
pField[py * nFieldWidth + px] = pField[(py - 1) * nFieldWidth + px];
}
pField[px] = 0;
}
}
vLines.clear();
}
// display frame
wprintw(win, screen.data());
wmove(win, 0, 0);
wrefresh(win);
}
std::cout << "Game over! Score: " << nScore << std::endl;
getchar();
delwin(win);
endwin();
return 0;
} | [
"mate.janus@gmail.com"
] | mate.janus@gmail.com |
9f78a7a7832c97c27d7501f0b7bb6b12c651343d | 53c537c1064d7856d7d638753238eadb1479c13f | /install/include/cwru_action/cwru_baxter_cart_moveActionGoal.h | bd87f95f18ae31aa604d7d6723aebd7b54d34dc5 | [] | no_license | dsb86/MobileRobotics | de8600b23a54cb3626a3a56f06a1fe766950a66e | 986771e1bcfba9bc601ed6324dc544ae28e40b54 | refs/heads/master | 2021-01-10T12:21:39.010769 | 2016-01-27T04:46:43 | 2016-01-27T04:46:43 | 50,472,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,422 | h | // Generated by gencpp from file cwru_action/cwru_baxter_cart_moveActionGoal.msg
// DO NOT EDIT!
#ifndef CWRU_ACTION_MESSAGE_CWRU_BAXTER_CART_MOVEACTIONGOAL_H
#define CWRU_ACTION_MESSAGE_CWRU_BAXTER_CART_MOVEACTIONGOAL_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
#include <actionlib_msgs/GoalID.h>
#include <cwru_action/cwru_baxter_cart_moveGoal.h>
namespace cwru_action
{
template <class ContainerAllocator>
struct cwru_baxter_cart_moveActionGoal_
{
typedef cwru_baxter_cart_moveActionGoal_<ContainerAllocator> Type;
cwru_baxter_cart_moveActionGoal_()
: header()
, goal_id()
, goal() {
}
cwru_baxter_cart_moveActionGoal_(const ContainerAllocator& _alloc)
: header(_alloc)
, goal_id(_alloc)
, goal(_alloc) {
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef ::actionlib_msgs::GoalID_<ContainerAllocator> _goal_id_type;
_goal_id_type goal_id;
typedef ::cwru_action::cwru_baxter_cart_moveGoal_<ContainerAllocator> _goal_type;
_goal_type goal;
typedef boost::shared_ptr< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> const> ConstPtr;
}; // struct cwru_baxter_cart_moveActionGoal_
typedef ::cwru_action::cwru_baxter_cart_moveActionGoal_<std::allocator<void> > cwru_baxter_cart_moveActionGoal;
typedef boost::shared_ptr< ::cwru_action::cwru_baxter_cart_moveActionGoal > cwru_baxter_cart_moveActionGoalPtr;
typedef boost::shared_ptr< ::cwru_action::cwru_baxter_cart_moveActionGoal const> cwru_baxter_cart_moveActionGoalConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace cwru_action
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'roscpp': ['/opt/ros/indigo/share/roscpp/cmake/../msg'], 'actionlib': ['/opt/ros/indigo/share/actionlib/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/indigo/share/trajectory_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'cwru_action': ['/home/dsb86/ros_ws/devel/share/cwru_action/msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "0dd8083c14e4b775a204ee3c6bf9d4ed";
}
static const char* value(const ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x0dd8083c14e4b775ULL;
static const uint64_t static_value2 = 0xa204ee3c6bf9d4edULL;
};
template<class ContainerAllocator>
struct DataType< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "cwru_action/cwru_baxter_cart_moveActionGoal";
}
static const char* value(const ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
Header header\n\
actionlib_msgs/GoalID goal_id\n\
cwru_baxter_cart_moveGoal goal\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: actionlib_msgs/GoalID\n\
# The stamp should store the time at which this goal was requested.\n\
# It is used by an action server when it tries to preempt all\n\
# goals that were requested before a certain time\n\
time stamp\n\
\n\
# The id provides a way to associate feedback and\n\
# result message with specific goal requests. The id\n\
# specified must be unique.\n\
string id\n\
\n\
\n\
================================================================================\n\
MSG: cwru_action/cwru_baxter_cart_moveGoal\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
#This action message is specialized for Baxter\n\
#minimally, it may contain just a command code\n\
#more generally, it may contain desired left and right tool-frame poses, as well\n\
# as gripper poses (gripper opening--interpreted for specific grippers, e.g. Yale hand)\n\
# and an arrival time for the move\n\
# It is assumed that a move starts from the previous commanded pose, or from the current joint state\n\
\n\
#return codes provide status info, e.g. if a proposed move is reachable\n\
\n\
#define message constants:\n\
uint8 ARM_TEST_MODE =0\n\
\n\
#queries\n\
uint8 ARM_IS_SERVER_BUSY_QUERY = 1\n\
\n\
uint8 ARM_QUERY_IS_PATH_VALID = 2\n\
uint8 RT_ARM_GET_Q_DATA = 3\n\
uint8 LEFT_ARM_GET_Q_DATA = 4\n\
uint8 RT_ARM_GET_TOOL_POSE = 5\n\
uint8 LEFT_ARM_GET_TOOL_POSE = 5\n\
\n\
#requests for motion plans; need to extend this to left arm and both arms\n\
uint8 RT_ARM_PLAN_PATH_CURRENT_TO_GOAL_POSE=20 #plan paths from current arm pose\n\
uint8 RT_ARM_PLAN_PATH_CURRENT_TO_PRE_POSE=21\n\
\n\
uint8 RT_ARM_PLAN_JSPACE_PATH_CURRENT_TO_PRE_POSE=22\n\
uint8 RT_ARM_PLAN_JSPACE_PATH_CURRENT_TO_QGOAL=23\n\
\n\
#cartesian path from specified joint-space start and end;\n\
# orientation interpolation is a bit odd\n\
uint8 RT_ARM_PLAN_PATH_QSTART_TO_QGOAL = 25\n\
uint8 RT_ARM_PLAN_PATH_QSTART_TO_ADES = 24 #specify start and end, j-space start, affine desired end\n\
\n\
#uint8 RT_ARM_PLAN_PATH_ASTART_TO_QGOAL = 26 #specified affine start, joint-space goal\n\
uint8 RT_ARM_PLAN_PATH_CURRENT_TO_GOAL_DP_XYZ = 27 #rectilinear translation w/ fixed orientation\n\
\n\
# request to preview plan:\n\
uint8 RT_ARM_DISPLAY_TRAJECTORY = 50\n\
\n\
#MOVE commands!\n\
uint8 RT_ARM_EXECUTE_PLANNED_PATH = 100\n\
\n\
#uint8 RT_ARM_DESCEND_20CM=101\n\
#uint8 RT_ARM_DEPART_20CM=102\n\
\n\
\n\
#goal:\n\
int32 command_code\n\
geometry_msgs/PoseStamped des_pose_gripper_right\n\
geometry_msgs/PoseStamped des_pose_gripper_left\n\
float64 gripper_opening_right\n\
float64 gripper_opening_left\n\
float64[] arm_dp_right #to command a 3-D vector displacement relative to current pose, fixed orientation\n\
float64[] arm_dp_left\n\
float64[] q_goal_right\n\
float64[] q_goal_left\n\
float64 move_time\n\
\n\
================================================================================\n\
MSG: geometry_msgs/PoseStamped\n\
# A Pose with reference coordinate frame and timestamp\n\
Header header\n\
Pose pose\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Pose\n\
# A representation of pose in free space, composed of postion and orientation. \n\
Point position\n\
Quaternion orientation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Point\n\
# This contains the position of a point in free space\n\
float64 x\n\
float64 y\n\
float64 z\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Quaternion\n\
# This represents an orientation in free space in quaternion form.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
float64 w\n\
";
}
static const char* value(const ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.goal_id);
stream.next(m.goal);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
}; // struct cwru_baxter_cart_moveActionGoal_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::cwru_action::cwru_baxter_cart_moveActionGoal_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "goal_id: ";
s << std::endl;
Printer< ::actionlib_msgs::GoalID_<ContainerAllocator> >::stream(s, indent + " ", v.goal_id);
s << indent << "goal: ";
s << std::endl;
Printer< ::cwru_action::cwru_baxter_cart_moveGoal_<ContainerAllocator> >::stream(s, indent + " ", v.goal);
}
};
} // namespace message_operations
} // namespace ros
#endif // CWRU_ACTION_MESSAGE_CWRU_BAXTER_CART_MOVEACTIONGOAL_H
| [
"dsb86@case.edu"
] | dsb86@case.edu |
f78f14640114face0fbef0b8b36c2e815e9635ec | 07c7953dbbf05a46cd260c96a515276915c1e493 | /C++实现数据结构查找和排序/main.cpp | 110070ab08bfd2760232ffe277944191cc38eeaa | [] | no_license | MasterLeen/cpp- | 9e421f40bcaf407f793c18a4408b9edb8dc7ddd4 | 22a8f6c1688903c36c3eda533fe57b9ece22ccc9 | refs/heads/master | 2020-03-24T20:58:32.164225 | 2019-10-07T05:47:19 | 2019-10-07T05:47:19 | 143,006,802 | 1 | 0 | null | 2019-10-07T05:47:20 | 2018-07-31T11:44:37 | C++ | GB18030 | C++ | false | false | 6,870 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <string.h>
#include <algorithm>
#include <sstream>//stringstream must include the header
using namespace std;
void SeqFind(const int& tmp);
void BinarySearch(const int& tmp);
void LinerExploration(int & num,char *cp);
void SearchStu(const int &num);
int Hash(char* cp);
void BubbleSort(vector<int> m_vec);
void SelectSort(vector<int> m_vec);
void InsertSort(vector<int> m_vec);
void QuickSort(vector<int> m_vec);
void QSort(vector<int>& m_vec,int low,int high);
void MergeSort(vector<int> m_vec);
void Print(const int & tmp);
void MergePass(vector<int> &m_vec, int head1, int head2, int tail2);
vector<int> m_vec;
map<int,char*> hash_map;
int main()
{
/*m_vec = {3,10,13,17,40,43,50,70};
SeqFind(43);
SeqFind(5);
BinarySearch(43);
BinarySearch(5);*/
//只输入两个姓名测试
/*char** cp = new char* [30];
cp[0] = "李华";
cp[1] = "周军";
for(int i = 0;i < 2;i++){
int location = Hash(cp[i]);
LinerExploration(location,cp[i]);
}
SearchStu(1);
SearchStu(27);
for(int i = 0;i < 30;i++)
delete [] cp[i];
delete cp;*/
//5种排序算法
cout<<"please input out of order digital series:"<<endl;
/*int tmp;
do{
cin>>tmp;
m_vec.push_back(tmp);
}while(cin.get() != '\n');*/
/*string ss;
getline(cin,ss,'\n');//使用string流读取一行
stringstream s;
s<<ss;
int tmp;
while(s>>tmp)
m_vec.push_back(tmp);
BubbleSort(m_vec);
SelectSort(m_vec);
InsertSort(m_vec);
QuickSort(m_vec);
MergeSort(m_vec);*/
//利用归并排序合并两个顺序表
/*m_vec = {1,5,10,44,66,2,4,7,11,55};
int head2 = 0,len = m_vec.size();
for(int i = 0;i < len - 1;i++)
{
if(m_vec[i] > m_vec[i + 1])
{
head2 = i + 1;
break;
}
}
head2 = head2 == 0?m_vec.size() - 1:head2;
MergePass(m_vec,0,head2,len - 1);
for_each(m_vec.begin(),m_vec.end(),Print);*/
return 0;
}
void SeqFind(const int &tmp)
{
//vector<int>::iterator iter = m_vec.begin();
int i = 0;
for(;i < m_vec.size();i++) {
if(m_vec[i] == tmp)
{
cout<<"found it! it's location in m_vec :"<<i<<endl;
return;
}
}
if(i == m_vec.size())
cout<<"can not find it!"<<endl;
}
void BinarySearch(const int &tmp)
{
int low = 0,high = m_vec.size() - 1,middle;
while(low <= high)
{
middle = (low + high)/2;
if(m_vec[middle] == tmp){
cout<<"found it! it's location in m_vec :"<<middle<<endl;
return;
}
else if(m_vec[middle] > tmp){
high = middle - 1;
}
else
low = middle + 1;
}
cout<<"can not find it!"<<endl;
}
int Hash(char* cp)
{
int sum = 0;
int len = strlen(cp);
for(int i = 0;i < len;i++){
sum += (int)*cp;
cp++;
}
return abs(sum%30);
}
void LinerExploration(int & num,char* cp)
{
while (hash_map.find(num) != hash_map.end()) num++;
hash_map.insert(pair<int,char*>(num,cp));
}
void SearchStu(const int &num)
{
map<int,char*>::iterator iter = hash_map.find(num);
if(iter == hash_map.end())
cout<<"false! can not find the stu!"<<endl;
else
cout<<"num = "<<iter->first<<" the stu name is :"<<iter->second<<endl;
}
void BubbleSort(vector<int> m_vec)
{
for(int i = 0;i < m_vec.size();i++)
{
for(int j = 0;j < m_vec.size() - i - 1;j++)
{
if(m_vec[j] > m_vec[j + 1]){
swap(m_vec[j],m_vec[j + 1]);
}
}
}
cout<<"the result of bubble sort algorithm is :"<<endl;
for_each(m_vec.begin(),m_vec.end(),Print);//for_each需包含<algorithm>头文件
cout<<endl;
}
void SelectSort(vector<int> m_vec)
{
for(int i = 0;i < m_vec.size();i++)
{
int min = i;
for(int j = i + 1;j < m_vec.size();j++){
if(m_vec[j] < m_vec[min])
min = j;
}
if(min != i)
swap(m_vec[i],m_vec[min]);
}
cout<<"the result of select sort algorithm is :"<<endl;
for_each(m_vec.begin(),m_vec.end(),&Print);
cout<<endl;
}
void InsertSort(vector<int> m_vec)
{
for(int i = 1;i < m_vec.size();i++)
{
if(m_vec[i] < m_vec[i - 1]){
int temp = m_vec[i];
int j = i - 1;
for(;j >= 0 && m_vec[j] > temp;j--)
m_vec[j + 1] = m_vec[j];
m_vec[j + 1] = temp;
}
}
cout<<"the result of insertion sort algorithm is :"<<endl;
for_each(m_vec.begin(),m_vec.end(),&Print);
cout<<endl;
}
void QuickSort(vector<int> m_vec)
{
QSort(m_vec,0,m_vec.size() - 1);
cout<<"the result of quick sort algorithm is :"<<endl;
for_each(m_vec.begin(),m_vec.end(),&Print);
cout<<endl;
}
//快排的思路是选取一个枢轴(比较值),将序列分成大于和小于枢轴的两部分再通过递归,直到序列不可分,因此每次递归都会确定枢轴的正确放置位置
void QSort(vector<int> &m_vec, int low, int high)
{
int pivort;
if(low < high)
{
{
int temp = m_vec[low];
int low1 = low;
int high1 = high;
while (low1 < high1) {
while(low1 < high1 && m_vec[high1] >= temp) high1--;
swap(m_vec[low1],m_vec[high1]);
while(low1 < high1 && m_vec[low1] <= temp) low1++;
swap(m_vec[low1],m_vec[high1]);
}
pivort = low1;
QSort(m_vec,low,pivort - 1);
QSort(m_vec,pivort + 1,high);
}
}
else
return;
}
void MergePass(vector<int>& m_vec,int head1,int head2,int tail2)
{
int tail1 = head2 - 1,start = head1;
vector<int> tmp;
tmp.reserve(tail2 - head1 + 1);
while (head1 <= tail1 && head2 <= tail2) {
if(m_vec[head1] <= m_vec[head2])
tmp.push_back(m_vec[head1++]);
else
tmp.push_back(m_vec[head2++]);
}
while(head1 <= tail1)
tmp.push_back(m_vec[head1++]);
while(head2 <= tail2)
tmp.push_back(m_vec[head2++]);
for(int i = 0;i < tmp.size();i++){
m_vec[start + i] = tmp[i];
}
tmp.clear();
}
//用迭代法实现归并排序
void MergeSort(vector<int> m_vec)
{
//步长每次都倍增
int len = m_vec.size();
for(int step = 1;step <= len;step <<= 1){
int offset = step << 1;
for(int index = 0;index < len;index += offset)
MergePass(m_vec,index,min(index + step,len -1),min(index + offset - 1,len - 1));
}
cout<<"the result of merge sort algorithm is :"<<endl;
for_each(m_vec.begin(),m_vec.end(),&Print);
cout<<endl;
}
void Print(const int & tmp)
{
cout<<tmp<<" ";
}
| [
"1763946255@qq.com"
] | 1763946255@qq.com |
eb5219ac375fcf1a41a0b153db1b6f5be7f8925b | 401bfbcc3cdd53b0f646ce61e1c3ecc81fff9a50 | /src/cpp/record/Region.h | 733c818d2e5b9507c318621a5b9753c01d068b19 | [] | no_license | TU-Berlin-DIMA/tpch-gen | 807d41c6b40c0d265b31a7a95c0d0f97094ed1b9 | 736d88323e12871025aa3a3f4966b995d683c7d9 | refs/heads/master | 2016-09-05T17:39:23.546219 | 2014-09-10T13:14:21 | 2014-09-10T13:14:21 | 13,740,341 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h | #ifndef REGION_H_
#define REGION_H_
#include "record/base/BaseRegion.h"
namespace TPCHGen {
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// record type
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
class Region: public BaseRegion
{
public:
Region(const RegionMeta& meta)
: BaseRegion(meta)
{
}
};
} // namespace TPCHGen
namespace Myriad {
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// record serialize method specialization
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
template<>
inline void AbstractOutputCollector<TPCHGen::Region>::serialize(std::ostream& out, const TPCHGen::Region& record)
{
AbstractOutputCollector<TPCHGen::BaseRegion>::serialize(out, record);
}
} // namespace Myriad
#endif /* REGION_H_ */
| [
"alexander.s.alexandrov@gmail.com"
] | alexander.s.alexandrov@gmail.com |
0b4d76ad7c57c7ce3ad081dba47b17d093c9d76d | 8e63e4fd669ced86bf07b20be364da5a06bce70d | /SPOJ/BYTESE2 - The Great Ball.cpp | 573575c43f2ef46363f334fdb9e5c33b779d214d | [] | no_license | AliOsm/CompetitiveProgramming | 00a1e75a2635532651fcdfb0e478c009adf84032 | af25b7f806e9c22a2176bfd05a1406ce5f1492c3 | refs/heads/master | 2023-03-07T01:17:25.555911 | 2023-02-10T09:09:17 | 2023-02-10T09:09:17 | 70,904,119 | 125 | 58 | null | 2021-02-27T13:13:18 | 2016-10-14T11:29:55 | C++ | UTF-8 | C++ | false | false | 1,372 | cpp | #include <stdio.h>
#include <set>
#include <algorithm>
#include <memory.h>
using namespace std;
int const N = 1000;
int n, seg[4 * N], lazy[4 * N];
pair<int, int> a[N];
set<int> st;
int s, e;
void pro(int idx, int l, int r) {
seg[idx] += lazy[idx];
if(l != r)
lazy[idx << 1] += lazy[idx],
lazy[(idx << 1) + 1] += lazy[idx];
lazy[idx] = 0;
}
int update(int idx, int l, int r) {
if(lazy[idx] != 0)
pro(idx, l, r);
if(s > r || e < l)
return 0;
if(l >= s && r <= e) {
++lazy[idx];
pro(idx, l, r);
return seg[idx];
}
int m = (l + r) >> 1;
update(idx << 1, l, m);
update((idx << 1) + 1, m + 1, r);
return seg[idx] = max(seg[idx << 1], seg[(idx << 1) + 1]);
}
int main() {
int t, res;
scanf("%d", &t);
while(t-- != 0) {
st.clear();
memset(seg, 0, sizeof seg);
memset(lazy, 0, sizeof lazy);
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d %d", &a[i].first, &a[i].second);
st.insert(a[i].first);
st.insert(a[i].second);
}
int cnt = 1;
for(set<int>::iterator it = st.begin(); it != st.end(); ++it, ++cnt)
for(int i = 0; i < n; ++i) {
if(a[i].first == (*it))
a[i].first = cnt;
if(a[i].second == (*it))
a[i].second = cnt;
}
res = 0;
for(int i = 0; i < n; ++i) {
s = a[i].first, e = a[i].second;
res = max(res, update(1, 1, N));
}
printf("%d\n", res);
}
return 0;
}
| [
"aliosm1997@gmail.com"
] | aliosm1997@gmail.com |
0ff77464b00abb9eeb83c0fd73e0804499b81841 | eee0588d6c92b1bc093716ac84969a47a8159e38 | /Cluiche/DiaGraphicWithUITest/SimThreadStruct.h | 0715e67ac15aed0c9b88a8e41b1e3ef8f990a874 | [] | no_license | LenihanConor/Cluiche | bf919ef721d901ba2a23646e70444803e0fe5781 | 1b65c5861a2354a81fbf1ed63fb0e7620b635d0d | refs/heads/master | 2023-06-28T19:45:52.811023 | 2023-06-20T18:20:58 | 2023-06-20T18:20:58 | 37,433,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | h | #pragma once
#include <DiaCore/Timer/TimeThreadLimiter.h>
#include <DiaCore/Time/TimeServer.h>
#include <DiaCore/Frame/FrameStream.h>
#include <DiaInput/EventData.h>
#include <DiaGraphics/Frame/FrameData.h>
#include <DiaUI/IUISystem.h>
struct SimThreadStruct
{
public:
SimThreadStruct(bool& running,
Dia::UI::IUISystem& uiSystem,
Dia::Core::FrameStream<Dia::Input::EventData>& inputToSimFrameStream,
Dia::Core::FrameStream<Dia::Graphics::FrameData>& SimToRenderFrameStream);
void operator()();
void Run();
private:
// Shared resources
bool& mRunning;
Dia::UI::IUISystem& mUISystem;
Dia::Core::FrameStream<Dia::Input::EventData>& mInputToSimFrameStream;
Dia::Core::FrameStream<Dia::Graphics::FrameData>& mSimToRenderFrameStream;
// Local resources
Dia::Core::TimeServer mTimeServer;
Dia::Core::TimeThreadLimiter mThreadLimiter;
};
| [
"lenihan.conor@gmail.com"
] | lenihan.conor@gmail.com |
db89dc51f0129523e6f957678435931d62145b89 | 7b103608fd1715d15077763ed82b4f78e7aa3dab | /Introductory Problems/03_Repetitions.cpp | 8528401f418fe32ccf41907f7a448a31ed9102d9 | [] | no_license | ameya-shahu/CSES-Problem-Set | b9f352950d6febb921587acc0556599f13eb6b60 | 2be2bc4d9e48bf91bfd543996f1c579de9ff9cb4 | refs/heads/master | 2022-09-18T08:32:33.413929 | 2020-06-01T16:22:34 | 2020-06-01T16:22:34 | 268,145,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | #include<bits/stdc++.h>
#define REP(i,n) for (int i = 1; i <= n; i++)
#define RREP(i,a,b) for (int i = a;i<b;i++)
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define INF 1000000000
#define endl '\n'
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
using namespace std;
int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
string input;
cin>>input;
int count = 0;
int Max = -INF;
char pre = 'i';
RREP(i,0,input.size()){
if(input[i]!=pre){
Max = max(Max,count);
count = 0;
}
pre = input[i];
count++;
}
cout<<max(Max,count);
return 0;
} | [
"ameyashahu@gmail.com"
] | ameyashahu@gmail.com |
69f928294b8db87e4c9c139740e2bb032a4bc4cb | 082f6678d50622d95e5253edb3564f52b6e81481 | /include/vsmc/gcd/dispatch_source.hpp | 471c75237aad6452f7bd38794ca23d7ae17f68e9 | [
"BSD-2-Clause"
] | permissive | Soledad89/vSMC | e78dc93dba7789190745636a1e913db579fb0816 | b00886f8d0cee0687fea8fee05f37fb2a5bab1d8 | refs/heads/master | 2021-01-24T21:18:56.700290 | 2015-05-28T08:42:54 | 2015-05-28T08:42:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,697 | hpp | //============================================================================
// vSMC/include/vsmc/gcd/dispatch_source.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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 HOLDER 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 VSMC_GCD_DISPATCH_SOURCE_HPP
#define VSMC_GCD_DISPATCH_SOURCE_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/gcd/dispatch_object.hpp>
#include <vsmc/gcd/dispatch_queue.hpp>
namespace vsmc {
/// \brief Types of DispatchSource
/// \ingroup Dispatch
enum DispatchSourceType {
DispatchDataAdd, ///< DISPATCH_SOURCE_TYPE_DATA_ADD
DispatchDataOr, ///< DISPATCH_SOURCE_TYPE_DATA_OR
DispatchMachRecv, ///< DISPATCH_SOURCE_TYPE_MACH_RECV
DispatchMachSend, ///< DISPATCH_SOURCE_TYPE_MACH_SEND
DispatchProc, ///< DISPATCH_SOURCE_TYPE_PROC
DispatchRead, ///< DISPATCH_SOURCE_TYPE_READ
DispatchSignal, ///< DISPATCH_SOURCE_TYPE_SIGNAL
DispatchTimer, ///< DISPATCH_SOURCE_TYPE_TIMER
DispatchVnode, ///< DISPATCH_SOURCE_TYPE_VNODE
DispatchWrite ///< DISPATCH_SOURCE_TYPE_WRITE
}; // enum DispatchSourceType
template <DispatchSourceType> class DispatchSource;
/// \brief Base class of DispatchSource
/// \ingroup Dispatch
///
/// \bug A DispachSource object is manually retained when created. It is
/// supposed to be retained by `dispatch_source_create` according to the
/// documents. But this seems not to be the case in the current implementation
/// (Mac OS X 10.9). The worst case is that a source object is retained one
/// more time than it is released. A simple test example is,
/// ~~~{.cpp}
/// ::dispatch_source_t source = ::dispatch_source_create( /* arguments */ );
/// ::dispatch_release(source); // generate error
/// ~~~
template <DispatchSourceType Type>
class DispatchSourceBase : public DispatchObject< ::dispatch_source_t>
{
public :
void resume () const {::dispatch_resume(this->object());}
void suspend () const {::dispatch_suspend(this->object());}
void cancel () const {::dispatch_source_cancel(this->object());}
long testcancel () const
{return ::dispatch_source_testcancel(this->object());}
unsigned long get_data () const
{return ::dispatch_source_get_data(this->object());}
uintptr_t get_handle () const
{return ::dispatch_source_get_handle(this->object());}
unsigned long get_mask () const
{return ::dispatch_source_get_mask(this->object());}
void set_cancel_handler_f (::dispatch_function_t cancel_handler) const
{::dispatch_source_set_cancel_handler_f(this->object(), cancel_handler);}
void set_event_handler_f (::dispatch_function_t event_handler) const
{::dispatch_source_set_event_handler_f(this->object(), event_handler);}
#if VSMC_HAS_GCD_LION
void set_registration_handler_f (::dispatch_function_t
registration_handler) const
{
::dispatch_source_set_registration_handler_f(
this->object(), registration_handler);
}
#endif // VSMC_HAS_GCD_LION
#ifdef __BLOCKS__
void set_cancel_handler (::dispatch_block_t cancel_handler) const
{::dispatch_source_set_cancel_handler(this->object(), cancel_handler);}
void set_event_handler (::dispatch_block_t event_handler) const
{::dispatch_source_set_event_handler(this->object(), event_handler);}
#if VSMC_HAS_GCD_LION
void set_registration_handler (::dispatch_block_t
registration_handler) const
{
::dispatch_source_set_registration_handler(
this->object(), registration_handler);
}
#endif // VSMC_HAS_GCD_LION
#endif // __BLOCKS__
private :
template <DispatchSourceType> struct source_type {};
protected :
DispatchSourceBase (uintptr_t handle, unsigned long mask,
::dispatch_queue_t queue) :
DispatchObject< ::dispatch_source_t>(::dispatch_source_create(
source_type_t(source_type<Type>()),
handle, mask, queue), false) {}
private :
static ::dispatch_source_type_t source_type_t (
source_type<DispatchDataAdd>)
{return DISPATCH_SOURCE_TYPE_DATA_ADD;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchDataOr>)
{return DISPATCH_SOURCE_TYPE_DATA_OR;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchMachRecv>)
{return DISPATCH_SOURCE_TYPE_MACH_RECV;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchMachSend>)
{return DISPATCH_SOURCE_TYPE_MACH_SEND;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchProc>)
{return DISPATCH_SOURCE_TYPE_PROC;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchRead>)
{return DISPATCH_SOURCE_TYPE_READ;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchSignal>)
{return DISPATCH_SOURCE_TYPE_SIGNAL;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchTimer>)
{return DISPATCH_SOURCE_TYPE_TIMER;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchVnode>)
{return DISPATCH_SOURCE_TYPE_VNODE;}
static ::dispatch_source_type_t source_type_t (
source_type<DispatchWrite>)
{return DISPATCH_SOURCE_TYPE_WRITE;}
}; // class DispatchSourceBase
/// \brief A dispatch source
/// \ingroup Dispatch
template <DispatchSourceType Type>
class DispatchSource : public DispatchSourceBase<Type>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<Type>(handle, mask, queue.object()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
::dispatch_queue_t queue) :
DispatchSourceBase<Type>(handle, mask, queue) {}
}; // class DispatchSource
/// \brief Data (ADD) dispatch source
/// \ingroup Dispatch
template <>
class DispatchSource<DispatchDataAdd> :
public DispatchSourceBase<DispatchDataAdd>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DispatchDataAdd>(handle, mask, queue.object()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
::dispatch_queue_t queue) :
DispatchSourceBase<DispatchDataAdd>(handle, mask, queue) {}
void merge_data (unsigned long value) const
{::dispatch_source_merge_data(this->object(), value);}
}; // class DispatchSource
/// \brief Data (OR) dispatch source
/// \ingroup Dispatch
template <>
class DispatchSource<DispatchDataOr> :
public DispatchSourceBase<DispatchDataOr>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DispatchDataOr>(handle, mask, queue.object()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
::dispatch_queue_t queue) :
DispatchSourceBase<DispatchDataOr>(handle, mask, queue) {}
void merge_data (unsigned long value) const
{::dispatch_source_merge_data(this->object(), value);}
}; // class DispatchSource
/// \brief Timer dispatch source
/// \ingroup Dispatch
template <>
class DispatchSource<DispatchTimer> :
public DispatchSourceBase<DispatchTimer>
{
public :
template <DispatchQueueType QType>
DispatchSource (uintptr_t handle, unsigned long mask,
const DispatchQueue<QType> &queue) :
DispatchSourceBase<DispatchTimer>(handle, mask, queue.object()) {}
DispatchSource (uintptr_t handle, unsigned long mask,
::dispatch_queue_t queue) :
DispatchSourceBase<DispatchTimer>(handle, mask, queue) {}
void set_timer (::dispatch_time_t start,
uint64_t interval, uint64_t leeway) const
{::dispatch_source_set_timer(this->object(), start, interval, leeway);}
}; // class DispatchSource
} // namespace vsmc
#endif // VSMC_GCD_DISPATCH_SOURCE_HPP
| [
"zhouyan@me.com"
] | zhouyan@me.com |
fc25b35580685e5875ded9c4455970437a4f1626 | d3d5089fa5c1ba5dea70d1f0de14d4d094b67e68 | /devel_isolated/controller_manager_msgs/include/controller_manager_msgs/ListControllerTypesResponse.h | 21dfb2a0cda9d9036fefabf5af3bdf73c362db27 | [] | no_license | akingse/ros_package_ws | d5408451e2fafd3314d53994b94585f95f2612c7 | 1d1ad9e9aecc90fa9335f29a802dc342a2a96612 | refs/heads/main | 2023-03-04T20:41:57.232496 | 2021-02-08T14:17:26 | 2021-02-08T14:17:26 | 337,102,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,122 | h | // Generated by gencpp from file controller_manager_msgs/ListControllerTypesResponse.msg
// DO NOT EDIT!
#ifndef CONTROLLER_MANAGER_MSGS_MESSAGE_LISTCONTROLLERTYPESRESPONSE_H
#define CONTROLLER_MANAGER_MSGS_MESSAGE_LISTCONTROLLERTYPESRESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace controller_manager_msgs
{
template <class ContainerAllocator>
struct ListControllerTypesResponse_
{
typedef ListControllerTypesResponse_<ContainerAllocator> Type;
ListControllerTypesResponse_()
: types()
, base_classes() {
}
ListControllerTypesResponse_(const ContainerAllocator& _alloc)
: types(_alloc)
, base_classes(_alloc) {
(void)_alloc;
}
typedef std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > , typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::other > _types_type;
_types_type types;
typedef std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > , typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::other > _base_classes_type;
_base_classes_type base_classes;
typedef boost::shared_ptr< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> const> ConstPtr;
}; // struct ListControllerTypesResponse_
typedef ::controller_manager_msgs::ListControllerTypesResponse_<std::allocator<void> > ListControllerTypesResponse;
typedef boost::shared_ptr< ::controller_manager_msgs::ListControllerTypesResponse > ListControllerTypesResponsePtr;
typedef boost::shared_ptr< ::controller_manager_msgs::ListControllerTypesResponse const> ListControllerTypesResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace controller_manager_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'controller_manager_msgs': ['/home/akingse/tempopkg_ws/src/ros_control/controller_manager_msgs/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
{
static const char* value()
{
return "c1d4cd11aefa9f97ba4aeb5b33987f4e";
}
static const char* value(const ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xc1d4cd11aefa9f97ULL;
static const uint64_t static_value2 = 0xba4aeb5b33987f4eULL;
};
template<class ContainerAllocator>
struct DataType< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
{
static const char* value()
{
return "controller_manager_msgs/ListControllerTypesResponse";
}
static const char* value(const ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
{
static const char* value()
{
return "string[] types\n\
string[] base_classes\n\
\n\
";
}
static const char* value(const ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.types);
stream.next(m.base_classes);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ListControllerTypesResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::controller_manager_msgs::ListControllerTypesResponse_<ContainerAllocator>& v)
{
s << indent << "types[]" << std::endl;
for (size_t i = 0; i < v.types.size(); ++i)
{
s << indent << " types[" << i << "]: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.types[i]);
}
s << indent << "base_classes[]" << std::endl;
for (size_t i = 0; i < v.base_classes.size(); ++i)
{
s << indent << " base_classes[" << i << "]: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.base_classes[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // CONTROLLER_MANAGER_MSGS_MESSAGE_LISTCONTROLLERTYPESRESPONSE_H
| [
"akingse@qq.com"
] | akingse@qq.com |
d182a664e531d0a74a989a4e3c19fdee8b40850e | c969008ffeb3e4c6e21cd2cb86dd46b60b81840a | /Code/用0~2个的1,2,4,8,16合出N.cpp | 0aaf823468999d0fe1b07d657fa3366282f13bca | [] | no_license | Crasader/Code_GSL | 6b7ddd27b47133b5a1e5f5eade8ca61275deac00 | dcd5ef0a204b7dc6b8c58939fb52a515b5689be8 | refs/heads/master | 2022-02-13T17:05:07.682256 | 2019-09-09T08:21:17 | 2019-09-09T08:21:17 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,106 | cpp | // ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<math.h>
#include<time.h>
#include<set>
using namespace std;
int nums[63];//num[i]表示2^i的个数,只有0,1,2三个取值
//回溯法
int IsOk(long long n, int *nums, int len)
{
long long sum = 0;
for (int i = 0; i < len; i++)
sum += nums[i] * pow(2, i);
if (sum == n)
return 0;
else if (sum > n)
return -1;
else
return 1;
}
void solve(long long n, int index, int *nums, int len, int &count)
{
if (index >= len)
return;
for (int i = 0; i <= 2; i++)
{
nums[index] = i;
if (IsOk(n, nums, len) == 0)
count++;
else if (IsOk(n, nums, len) == 1)
solve(n, index + 1, nums, len, count);
}
nums[index] = 0;//回溯法,要撤回上一步的假设
}
long long DP(long long n)//使用动态规划方法
{
int len = log(n) / log(2) + 1;
long long **dp = new long long*[n + 1];
for (long long i = 0; i <= n; i++)
{
dp[i] = new long long[len];
}
//long long dp[5][3] = { 0 };
for (int i = 0; i < len; i++)
for (long long j = 0; j <= n; j++)
dp[j][i] = 0;
//dp[n][i]表示使用1,1,2,2,4,4,...,2^i可以组合出n的方案数
for (int i = 0; i < len; i++)
dp[0][i] = 1;
if (n == 1 || n == 2)
return n;
dp[1][0] = 1;
dp[2][0] = 1;
for (int i = 3; i <= n; i++)
dp[i][0] = 0;
//dp[n][i]=
// cout << "len=" << len << endl;
for (int i = 1; i < len; i++)
{
for (long long j = 1; j <= n; j++)
{
for (int m = 0; m <= 2; m++)
if (j - pow(2, i)*m >= 0)
{
dp[j][i] = dp[j][i] + dp[(long long)(j - pow(2, i)*m)][i - 1];
//cout <<"j="<< j << " " << "i=" << i << " " << "m=" << m<<" "<< dp[j][i]<<endl;
}
}
}
return dp[n][len - 1];
}
int solve3(long long n)
{
long long stop = n / 2;
long long res = 0;
set<int> myset;
/*
将硬币分为两份:1,2,4,8,16,.....和1,2,4,8,16....
组成两个数值为a,b的两个数字,他们的和是a+b=n;
a在每一份中只可能有一种组合方式(二进制的思想)
*/
for (int i = 1; i <= stop; i++)
{
res = i ^ (n - i);
myset.insert(res);
}
//对于1,2,4,8结果再加1.
int len = log(n) / log(2) + 1;
if (pow(2, len - 1) == n)
return myset.size() + 1;
return myset.size();
}
int main()
{
for (int i = 0; i < 63; i++)
nums[i] = 0;
long long n;
clock_t start, finish;
while (true)
{
cin >> n;
if (n < 1)
{
return 0;
}
int len = log(n) / log(2) + 1;
int count = 0;
start = clock();
solve(n, 0, nums, len, count);
cout << count << endl;
finish = clock();
cout << "回溯法耗费时间为" << (double)(finish - start) / CLOCKS_PER_SEC << "秒" << endl;
//
//
start = clock();
long long res = DP(n);
cout << res << endl;
finish = clock();
cout << "动态规划方法耗费时间为" << (double)(finish - start) / CLOCKS_PER_SEC << "秒" << endl;
start = clock();
res = solve3(n);
cout << res << endl;
finish = clock();
cout << "第三种方法耗费时间为" << (double)(finish - start) / CLOCKS_PER_SEC << "秒" << endl;
}
return 0;
} | [
"153274152@qq.com"
] | 153274152@qq.com |
5d2e0ab7b8f7ef361cbbea0578ac48d7b10c1497 | d558f13a3e9c15e51e8aeff3cdbcbbd99df7166f | /C++/powcarettranslator/caretPow.cpp | 94689a941a661d62916716fc9898735fa9433e30 | [] | no_license | mehstruslehpy/Documents | 3b52dc2b9506746b88eccb2afa2d591f4572b7a5 | b40fa6d6944d6bf21ce99de6fbfd9b19f98bd763 | refs/heads/master | 2020-04-15T14:03:11.555203 | 2019-01-01T04:03:27 | 2019-01-01T04:03:27 | 58,814,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,273 | cpp | #include <iostream>
#include <strings.h>
#include <regex>
#include <boost/algorithm/string/replace.hpp>
#define NOT_FOUND string::npos ///the find method returns this if not found
using namespace std;
int caretPow(string inLine, int offsets[])
{
//string inLine; //input string
regex singleCaret (".*(\^).*"); //we use this to look for a caret in our input expression
//int offsets[8] = {-1, -1, -1, -1, -1, -1, -1, -1}; //an array of 8 integers corresponding to the offsets for parens and symbols below
int count = 0; //used to tally parens zero means we have finished matching open = +1 close = -1 or open =-1 close = +1
int pos = 0; //tracks indexes into our string
int lhoParen = -1; //left hand side open paren
int lhcParen = -1; //left hand side close paren
int rhoParen = -1; //right hand side open paren
int rhcParen = -1; //right hand side close paren
//in the case of symbol^symbol or some combination
int lhsSymbols = -1; //the left hand side symbol
int lhsSymbole = -1; //the left hand side symbol
int rhsSymbols = -1; //the right hand side symbol
int rhsSymbole = -1; //the right hand side symbol
//getline(cin, inLine); //get a line this can be eliminated later to process by line input files
if (regex_match(inLine, singleCaret))
{
//cout << "MATCH!" << endl;
pos = inLine.find("^");
pos = pos - 1;
//consume lhs white space til we reach a open paren
while (inLine.at(pos) == ' ' && inLine.at(pos) != ')' && pos != 0)
{
pos = pos - 1;
}
//if this is still a white space then the user entered something invalid and we should exit
if (inLine.at(pos) == ' ')
{
cout << "ERROR: INVAID EXPRESSION ON LEFT HAND SIDE OF EXPONENT" << endl;
return 1;
}
//match parentheses on lhs of caret
do
{
if (inLine.at(pos) == ')')
{
count = count + 1;
//cout << "PLUS ONE" << endl;
pos = pos - 1;
lhcParen = pos + 1;
}
else if (inLine.at(pos) == '(')
{
count = count - 1;
//cout << "MINUS ONE" << endl;
pos = pos - 1;
lhoParen = pos + 1;
}
else
{
//cout << "NEXT ELEMENT" << endl;
pos = pos - 1;
}
} while (count != 0 && pos >= 0);
//cout << "DONE COUNTING! left hand side of first caret" << endl;
count = 0;
pos = inLine.find("^");
pos = pos + 1;
//consume rhs white space til we reach an open paren
while (inLine.at(pos) == ' ' && inLine.at(pos) != '(' && (inLine.length() - 1) != pos)
{
pos = pos + 1;
}
//if this is still a white space then the user entered something invalid and we should exit
if (inLine.at(pos) == ' ')
{
cout << "ERROR: INVAID EXPRESSION ON RIGHT HAND SIDE OF EXPONENT" << endl;
return 0; //we should probably just skip over this line but returning now might be good
}
//match parens on right hand side of caret
do
{
if (inLine.at(pos) == '(')
{
count = count + 1;
//cout << "PLUS ONE" << endl;
pos = pos + 1;
rhoParen = pos - 1;
}
else if (inLine.at(pos) == ')')
{
count = count - 1;
//cout << "MINUS ONE" << endl;
pos = pos + 1;
rhcParen = pos - 1;
}
else
{
//cout << "NEXT ELEMENT" << endl;
pos = pos + 1;
}
} while (count != 0 && pos <= inLine.length());
//evaluate the symbol on the left hand side if we know it is not a parenthesized expression
pos = inLine.find("^");
pos = pos - 1;
if (lhcParen == -1)
{
//kill off any white space..
while (inLine.at(pos) == ' ')
pos = pos - 1;
//set the end of the symbol to position if isalnum is true
if (isalnum(inLine.at(pos)))
lhsSymbole = pos;
while (pos != -1 && inLine.at(pos) != ' ' && pos >= 0 && isalnum(inLine.at(pos)))
{
//set the start to whatever the new position is
pos = pos - 1;
lhsSymbols = pos + 1;
if (pos <= 0) //I'm an idiot, this breaks out when we hit the end of the array
{
lhsSymbols = pos;
break;
}
}
//if we get here and:
//start is neg 1 but end is not
//we need to consume some whitespace..
if (lhsSymbols == -1 && lhsSymbole != -1 )
lhsSymbols = lhsSymbole;
}
}
//evaluate the symbol on the right hand side if we know it is not a parenthesized expression
pos = inLine.find("^");
pos = pos + 1;
if (rhoParen == -1)
{
//kill off any white space..
while (inLine.at(pos) == ' ' && pos != inLine.length())
pos = pos + 1;
//set the end of the symbol to position if isalnum is true
if (isalnum(inLine.at(pos)))
rhsSymbols = pos;
while (pos != -1 && inLine.at(pos) != ' ' && pos <= inLine.length() && isalnum(inLine.at(pos)))
{
//cout << "DEBUG" << endl;
//set the start to whatever the new position is
pos = pos + 1;
rhsSymbole = pos - 1;
if (pos >= inLine.length()) //I'm an idiot, this breaks out when we hit the end of the array
{
rhsSymbole = pos - 1;
break;
}
}
//if we get here and:
//start is neg 1 but end is not
//we need to consume some whitespace..
if (rhsSymbols == -1 && rhsSymbole != -1 )
{
rhsSymbols = rhsSymbole;
}
}
//cout << "lhoParen: " << lhoParen << endl;
//cout << "lhcParen: " << lhcParen << endl;
//cout << "rhoParen: " << rhoParen << endl;
//cout << "rhcParen: " << rhcParen << endl << endl;
//cout << "lhsSymbols: " << lhsSymbols << endl;
//cout << "lhsSymbole: " << lhsSymbole << endl;
//cout << "rhsSymbols: " << rhsSymbols << endl;
//cout << "rhsSymbole: " << rhsSymbole << endl;
//setup our return values
offsets[0] = lhoParen;
offsets[1] = lhcParen;
offsets[2] = rhoParen;
offsets[3] = rhcParen;
offsets[4] = lhsSymbols;
offsets[5] = lhsSymbole;
offsets[6] = rhsSymbols;
offsets[7] = rhsSymbole;
return 0;
}
string stringGenerator(string strtStr, int offsets[])
{
//these will be offsets in the original string to be replaced..
int lhOffsetStrt; //left hand side offsetStart
int rhOffsetStop; //right hand side offsetStop
string lhSubstr; //left hand substring
string rhSubstr; //right hand substring
string exprString; //the full caret expression
string temp = ""; //hopefully this works..
temp = strtStr; //hopefully this works..
exprString = "pow("; //we want it to start with this
//grab the left hand side substring
if (offsets[0] != -1 && offsets[1] != -1) //check if it's a parenthesized expression
{
lhOffsetStrt = offsets[0];
//return substring starting at offsets[0] and as long as the difference between the two..
lhSubstr = strtStr.substr(offsets[0] + 1, (offsets[1] - offsets[0] - 1));
//cout << "LHS PAREN EXPR!" << endl;
}
else if (offsets[4] != -1 && offsets[5] != -1) //check if it's a symbol
{
lhOffsetStrt = offsets[4];
lhSubstr = strtStr.substr(offsets[4], (offsets[5] - offsets[4] + 1));
//cout << "LHS SYMBOL EXPR!" << endl;
}
else //if it's neither then something is wrong..
{
cout << "IMPROPER LEX/PARSE LHS OF INPUT" << endl;
}
//cout << "LEFT HAND SUBSTRING: " << lhSubstr << endl;
//grab the right hand side substring
if (offsets[2] != -1 && offsets[3] != -1) //check if it's a parenthesized expression
{
rhOffsetStop = offsets[3];
rhSubstr = strtStr.substr(offsets[2] + 1, (offsets[3] - offsets[2] - 1));
//cout << "RHS PAREN EXPR!" << endl;
}
else if (offsets[6] != -1 && offsets[7] != -1) //check if it's a symbol
{
rhOffsetStop = offsets[7];
rhSubstr = strtStr.substr(offsets[6], (offsets[7] - offsets[6] + 1));
//cout << "RHS SYMBOL EXPR!" << endl;
}
else //if it's neither then something is wrong..
{
cout << "IMPROPER LEX/PARSE RHS OF INPUT" << endl;
}
//cout << "RIGHT HAND SUBSTRING: " << rhSubstr << endl;
exprString = exprString + "(" + lhSubstr + "),(" + rhSubstr + "))";
//cout << "BEFORE REPLACE STRING: " << temp << endl;
//I tried to do this with only std lib but this function was really rough to do
//using the standard string library
boost::replace_first(temp, temp.substr(lhOffsetStrt, (rhOffsetStop - lhOffsetStrt + 1)), exprString);
//cout << "AFTER REPLACE STRING: " << temp << endl;
return temp;
}
| [
"williamvanskike@gmail.com"
] | williamvanskike@gmail.com |
eb8d8915b88c49fd4917043c464b384d040a6954 | 9b2938d4ea17d29569ff5b4d2b0ed66783cddee9 | /d-pong/paddle.h | b603b3631f735e637c4a61ec384f4285fe5701ed | [] | no_license | dmateos/scratch | 87f8b6988630fb75655e2dda2d3e2e2f3df2d5a3 | 5d0092877527039bc70bcbd5e0671e5cb421f037 | refs/heads/master | 2021-01-16T18:29:33.304457 | 2016-01-27T15:04:37 | 2016-01-27T15:04:37 | 273,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121 | h | #ifndef _PADDLE_H_
#define _PADDLE_H_
class Paddle {
public:
Paddle();
~Paddle();
private:
int x, y;
};
#endif
| [
"daniel@mateos.cc"
] | daniel@mateos.cc |
92ab0e93b9978b2de344b853d96cf062ea9a1d26 | ae1c6ad39b94b34b2312e7cc599321616016d767 | /HighlightTextEditor/jni/highlight/cli/cmdlineoptions.h | 3cd5679d872ab06db66c1f5a13814bebb1d49efb | [] | no_license | vbea/AideProjects | cd4481943229fd585841863bd7f66f98543e54d9 | 0d6dfc4bb1e8aea7b60483b0cbc23190f8e0f26d | refs/heads/master | 2023-01-30T09:11:11.278783 | 2023-01-14T10:28:47 | 2023-01-14T10:28:47 | 200,463,935 | 24 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 14,153 | h | /***************************************************************************
cmdlineoptions.h - description
-------------------
begin : Sun Nov 25 2001
copyright : (C) 2001-2010 by Andre Simon
email : andre.simon1@gmx.de
***************************************************************************/
/*
This file is part of Highlight.
Highlight 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.
Highlight 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Highlight. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CMDLINEOPTIONS_H
#define CMDLINEOPTIONS_H
#ifdef _WIN32
#include <windows.h>
#endif
#include <string>
#include <map>
#include <set>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include "stringtools.h"
#include "enums.h"
#if ANDROID
#include <android/log.h>
#ifndef TAG_NAME
#define TAG_NAME "highliter"
#endif
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, TAG_NAME, __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, TAG_NAME, __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, TAG_NAME, __VA_ARGS__))
#define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, TAG_NAME, __VA_ARGS__))
#else
#define LOGI(...)
#define LOGW(...)
#define LOGE(...)
#endif
#define OPT_OUTFORMAT "out-format"
#define OPT_ANCHORS "anchors"
#define OPT_ANCHOR_FN "anchor-filename"
#define OPT_ANCHOR_PFX "anchor-prefix"
#define OPT_BABEL "babel"
#define OPT_BASE_FONT "font"
#define OPT_BASE_FONT_SIZE "font-size"
#define OPT_BATCHREC "batch-recursive"
#define OPT_CLASSNAME "class-name"
#define OPT_DATADIR "data-dir"
#define OPT_DELTABS "replace-tabs"
#define OPT_DOC_TITLE "doc-title"
#define OPT_ENCLOSE_PRE "enclose-pre"
#define OPT_ENCODING "encoding"
#define OPT_FILLZEROES "zeroes"
#define OPT_FORCE_OUTPUT "force"
#define OPT_FORMAT "reformat"
#define OPT_FRAGMENT "fragment"
#define OPT_HELP "help"
#define OPT_IN "input"
#define OPT_INC_STYLE "include-style"
#define OPT_INDEXFILE "print-index"
#define OPT_INLINE_CSS "inline-css"
#define OPT_KW_CASE "kw-case"
#define OPT_LINENO "line-numbers"
#define OPT_LINE_LEN "line-length"
#define OPT_LISTLANGS "list-langs"
#define OPT_LISTTHEMES "list-themes"
#define OPT_LIST_SCRIPTS "list-scripts"
#define OPT_LNR_LEN "line-number-length"
#define OPT_LNR_START "line-number-start"
#define OPT_ORDERED_LIST "ordered-list"
#define OPT_OUT "output"
#define OPT_OUTDIR "outdir"
#define OPT_RTF_PAGE_SIZE "page-size"
#define OPT_RTF_CHAR_STYLES "char-styles"
#define OPT_PRINT_CONFIG "print-config"
#define OPT_PROGRESSBAR "progress"
#define OPT_QUIET "quiet"
#define OPT_REPLACE_QUOTES "replace-quotes"
#define OPT_STYLE "style"
#define OPT_STYLE_IN "style-infile"
#define OPT_STYLE_OUT "style-outfile"
#define OPT_SYNTAX "syntax"
#define OPT_TEST_INPUT "validate-input"
#define OPT_VERBOSE "verbose"
#define OPT_VERSION "version"
#define OPT_WRAP "wrap"
#define OPT_WRAPSIMPLE "wrap-simple"
#define OPT_SVG_WIDTH "width"
#define OPT_SVG_HEIGHT "height"
#define OPT_SKIP_UNKNOWN "skip"
#define OPT_PRETTY_SYMBOLS "pretty-symbols"
#define OPT_EOL_DELIM_CR "delim-cr"
#define OPT_START_NESTED "start-nested"
#define OPT_PRINT_STYLE "print-style"
#define OPT_NO_TRAILING_NL "no-trailing-nl"
#define OPT_PLUGIN "plug-in"
#define OPT_ABS_CFG_PATH "config-file"
#define OPT_PLUGIN_READFILE "plug-in-read"
#define OPT_NO_NUMBER_WL "wrap-no-numbers"
#define OPT_USE_NBSP "nbsp"
// Improve CLI option compatibility with GNU source-highlight
#define OPT_COMPAT_DOC "doc"
#define OPT_COMPAT_NODOC "no-doc"
#define OPT_COMPAT_TAB "tab"
#define OPT_COMPAT_CSS "css"
#define OPT_COMPAT_OUTDIR "output-dir"
#define OPT_COMPAT_FAILSAFE "failsafe"
#define OPT_COMPAT_SRCLANG "src-lang"
#define OPT_COMPAT_LINENUM "line-number"
#define OPT_COMPAT_LINEREF "line-number-ref"
using namespace std;
/// handle command line options
class CmdLineOptions
{
public:
/**Constructor
\param argc Argument count
\param argv Argument strings
*/
void init (const int argc, const char *argv[] ) ;
CmdLineOptions();
CmdLineOptions ( const int argc, const char *argv[] );
~CmdLineOptions();
/** \return Single output file name*/
const string &getSingleOutFilename();
/** \return Single input file name*/
const string &getSingleInFilename() const;
/** \return Output directory*/
const string& getOutDirectory() ;
/** \return Style output file name*/
const string getStyleOutFilename() const;
/** \return Style input file name*/
const string& getStyleInFilename() const;
/** \return Char set*/
const string& getEncoding() const;
/** \return SVG width*/
const string& getSVGWidth() const;
/** \return SVG height*/
const string& getSVGHeight() const;
/** \return Number of spaces to replace a tab*/
int getNumberSpaces() const;
/** \return True if version information should be printed*/
bool printVersion() const;
/** \return True if help information should be printed*/
bool printHelp() const;
/** \return True if debug information should be printed*/
bool printDebugInfo() const;
/** \return True if configuration information should be printed*/
bool printConfigInfo() const;
/** \return True if Style definition should be included in output*/
bool includeStyleDef() const;
/** \return True if line numbers should be printed*/
bool printLineNumbers() const;
/** \return True if CR is eol delimiter */
bool useCRDelimiter() const;
/** \return colour theme name */
string getThemeName() const ;
/** gibt true zurck, falls deutsche Hilfe ausgegeben werden soll */
int helpLanguage() const;
/** \return True if batch mode is active*/
bool enableBatchMode() const;
/** \return True if output shluld be fragmented*/
bool fragmentOutput() const;
/** \return output file suffix */
string getOutFileSuffix() const;
/** \return True if anchors should be attached to line numbers*/
bool attachLineAnchors() const;
/** \return True if list of installed themes should be printed*/
bool showThemes() const;
/** \return True if list of installed language definitions should be printed*/
bool showLangdefs() const;
/** \return True if list of installed language definitions should be printed*/
bool showPlugins() const;
/** \return True if loutput directory is given*/
bool outDirGiven() const;
/** \return True if a new data directory is given*/
bool dataDirGiven() const;
/** \return True if index file should be printed*/
bool printIndexFile() const;
/** \return True if quotes should be replaced by /dq in LaTeX*/
bool replaceQuotes() const;
/** \return True if shorthands of LaTeX Babel package should be disabled*/
bool disableBabelShorthands() const;
/** \return True if input file name should be used as anchor name */
bool useFNamesAsAnchors() const;
/** \return Data directory*/
const string &getDataDir() const;
/** \return True if language syntax is given*/
bool syntaxGiven() const;
/** \return True if quiet mode is active*/
bool quietMode() const;
/** \return True if progress bar should be printed in batch mode */
bool printProgress() const;
/** \return True if line numbers are filled with leading zeroes */
bool fillLineNrZeroes() const;
/** \return programming syntax */
const string &getSyntax() const ;
/** \return Wrapping style*/
highlight::WrapMode getWrappingStyle() const;
/** \return List of input file names*/
const vector <string> & getInputFileNames() const;
/** \return indentation and reformatting scheme*/
string getIndentScheme() const;
/** \return RTF page size */
const string &getPageSize() const;
/** \return Output file format */
highlight::OutputType getOutputType() const;
/** \return True if chosen output format supports referenced style files */
bool formatSupportsExtStyle();
/** \return True if style output path was defined by user*/
bool styleOutPathDefined() const
{
return opt_stylepath_explicit;
}
/** \return True if encoding specification should be omitted in output*/
bool omitEncoding() const;
/** \return True if output should be generated if languege type is unknown*/
bool forceOutput() const;
/** \return True if line numbers should be replaced by ordered list (HTML) */
bool orderedList() const;
/** \return True if spaces should be replaced by (HTML) */
//bool useNonBreakingSpace() const;
/** \return True if a base font has been given */
bool hasBaseFont() const ;
/** \return True if input should be validated */
bool validateInput() const ;
/** \return True if wrapped lines should get unique numbers */
bool numberWrappedLines() const ;
/** \return True if CSS should be outputted within tag elements */
bool inlineCSS() const ;
/** \return True if fragmented html output should be enclosed with pre tags */
bool enclosePreTag() const ;
/** \return True if RTF output should include character styles */
bool includeCharStyles() const ;
/** \return True if LaTeX output should includ fancier symbols */
bool prettySymbols() const;
/** \return True if style should be printed */
bool printOnlyStyle() const;
/** \return The given base font, empty string by default */
const string& getBaseFont() const ;
/** \return Document title */
const string& getDocumentTitle() const ;
/** \return anchor prefix */
const string& getAnchorPrefix() const ;
/** \return class name */
const string& getClassName() const ;
const vector <string> &getPluginPaths() const;
/** \return True if trailing nl should be omitted */
bool disableTrailingNL() const ;
/** \return The given base font size, empty string by default */
const string& getBaseFontSize() const ;
/** \return name of nested syntax which starts the input */
const string& getStartNestedLang() const ;
/** \return absolute theme definition path name */
const string& getAbsThemePath() const ;
/** \return absolute language definition path name */
const string& getAbsLangPath() const ;
/** \return path of input file passed to plugin */
const string& getPluginReadFilePath() const ;
/** \return line number width */
int getNumberWidth();
/** \return line length */
int getLineLength();
/** \return Line number start count */
int getNumberStart();
/** \return Keyword Case (upper, lower, unchanged) */
StringTools::KeywordCase getKeywordCase() const;
bool isSkippedExt ( const string& ext )
{
return ignoredFileTypes.count ( ext );
}
private:
int numberSpaces; // number of spaces which replace a tab
int lineNrWidth; // width of line number (left padding)
int lineLength; // length of line before wrapping
int lineNrStart; // line number start count
highlight::WrapMode wrappingStyle; // line wrapping mode
highlight::OutputType outputType;
StringTools::KeywordCase keywordCase;
// name of single output file
string outFilename,
// output directory
outDirectory,
// programming syntax which will be loaded
syntax,
// name of colour theme
styleName,
// name of external style file
styleOutFilename,
// name of file to be included in external style file
styleInFilename,
// used to define data directories at runtime
dataDir;
// name of indenation scheme
string indentScheme,
pageSize, startNestedLang;
string baseFont, baseFontSize;
string docTitle, className;
string skipArg;
string svg_height, svg_width;
string absThemePath, absLangPath;
bool opt_syntax;
bool opt_include_style;
bool opt_help;
bool opt_version ;
bool opt_verbose;
bool opt_print_config;
bool opt_linenumbers;
bool opt_style;
bool opt_batch_mode;
bool opt_fragment;
bool opt_attach_line_anchors;
bool opt_show_themes;
bool opt_show_langdefs;
bool opt_show_plugins;
bool opt_asformat_output;
bool opt_printindex;
bool opt_quiet;
bool opt_replacequotes;
bool opt_babel;
bool opt_print_progress;
bool opt_fill_zeroes;
bool opt_stylepath_explicit;
bool opt_force_output;
bool opt_ordered_list;
bool opt_fnames_as_anchors;
bool opt_validate;
bool opt_number_wrapped_lines;
bool opt_inline_css;
bool opt_enclose_pre;
bool opt_char_styles;
bool opt_pretty_symbols;
bool opt_delim_CR;
bool opt_print_style;
bool opt_no_trailing_nl;
string anchorPrefix;
string helpLang, encodingName;
string pluginPath, pluginReadFilePath;
/** list of all input file names */
vector <string> inputFileNames;
/** list of plugin file names */
vector <string> userPlugins;
/** list lines which should be marked and supplied with help string */
map <int, string> markLines;
/** list of file types which should be ignored */
set <string> ignoredFileTypes;
/** \return file suffix */
string getFileSuffix ( const string & fileName ) const;
/** \return directory name of path */
string getDirName ( const string & path );
/** get all entries in the directory defined by wildcard */
void readDirectory ( const string & wildcard );
/** \return Boolean value of paramVal */
bool getFlag ( const string& paramVal );
/** \return Valid path name */
string validateDirPath ( const string & path );
};
#endif
| [
"vbea@foxmail.com"
] | vbea@foxmail.com |
494133e0120091ea2b466a480fa9282b16da98dd | 0f2e24348a278522127df89124f3e9fde44fc536 | /lapotop.cpp | 5da62c822949578d8f05b13784b7ac53a888b1dc | [] | no_license | Jstrykow/projectC- | 7a07ca75af10fc2dd34af219020ed8e6390e86d9 | 5d4076a4ddf56e0047be2e3b4f777810f32018c6 | refs/heads/master | 2021-02-09T19:44:33.362619 | 2020-03-02T08:26:28 | 2020-03-02T08:26:28 | 244,319,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | cpp | #include <iostream>
#include "laptop.h"
#include "antywirus.h"
#include <string>
#include <cstdlib>
#include <fstream>
std::string Laptop::getmodel()
{
return model;
}
void Laptop::setmodel(std::string model1)
{
model = model1;
}
std::string Laptop::typ()
{
return "L";
}
void Laptop::zapisz_komputer(std::string n = "test")
{
std::fstream plik;
plik.open(n, std::fstream::out | std::fstream::app);
plik << (*this);
plik.close();
}
Laptop::Laptop()///kostruktor
{
}
Laptop::~Laptop()//dekostruktor
{
}
Laptop::Laptop( int benchmark1 , std::string uzytkownik = "Domyslny", std::string model1 = "O")
:Komputer(benchmark1, uzytkownik)
{
model = model1;
}
void Laptop::pokaz()
{
std::cout << "laptop o ktory prosiles: " << std::endl;
std::cout << "Model: " << model << std::endl;///funckjonalnosc doddana w laptopie
show();///<funkcja odziedziczona z komputer
std::cout << std::endl;
}
std::ostream & operator << (std::ostream& out2, const Laptop &L)
{
out2 << "Model: " << L.model << std::endl;
out2 << "Uzytkownik: " << L.user << std::endl;
out2 << L.processor_komputer;
return out2;
}
void Laptop::set()
{
std::cout << "podaj model: ";
std::cin >> model;
set_komputer();
}
| [
"jakub@strykowski.eu"
] | jakub@strykowski.eu |
afe93c072eaf722a4b07b4debc5367e0a758dfa8 | 534e2e3d8d8bebd2366c0fee60886d84597ee0ef | /CF/CF 949B.cpp | 2a316bb8d0abb2539d54ac1d8e29b3ebd9a1f019 | [] | no_license | coldEr66/online-judge | a8844d3f35755adafd4f43a1f08ce56b6b870601 | e85ec0750d92dd00133c93284085a0f5d8a11d36 | refs/heads/master | 2021-09-07T01:58:10.634492 | 2021-07-28T16:31:13 | 2021-07-28T16:31:13 | 128,494,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,181 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(int i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define RST(i,n) memset(i,n,sizeof i)
#define SZ(a) (int)a.size()
#define ALL(a) a.begin(),a.end()
#define F first
#define S second
#define pb push_back
#define pob pop_back
#define MP make_pair
#define VI vector<int>
#ifdef cold66
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.F<<","<<_p.S<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // cold66
//}
template<class T> inline bool chkmax(T &a, const T &b) { return b > a ? a = b, true : false; }
template<class T> inline bool chkmin(T &a, const T &b) { return b < a ? a = b, true : false; }
template<class T> using MaxHeap = priority_queue<T>;
template<class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;
const ll MAXn=1e5+5;
const ll MOD=1000000007;
const ll INF=(ll)1e18;
int main(){
IOS();
ll n,q;
cin>>n>>q;
while(q--){
ll t;cin>>t;
ll tmp=n-t/2;
while(t%2==0){
t+=tmp;
tmp/=2;
}
cout<<t/2+1<<endl;
}
}
| [
"seal1000402@gmail.com"
] | seal1000402@gmail.com |
465b3613f8637344b2a8715e6ab6a8e7da97fd31 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /third_party/abseil-cpp/absl/strings/internal/str_format/float_conversion.h | 71100e714257defbb6e92579353acce70e909674 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 1,343 | h | // Copyright 2020 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_FLOAT_CONVERSION_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_FLOAT_CONVERSION_H_
#include "absl/strings/internal/str_format/extension.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
bool ConvertFloatImpl(float v, const FormatConversionSpecImpl &conv,
FormatSinkImpl *sink);
bool ConvertFloatImpl(double v, const FormatConversionSpecImpl &conv,
FormatSinkImpl *sink);
bool ConvertFloatImpl(long double v, const FormatConversionSpecImpl &conv,
FormatSinkImpl *sink);
} // namespace str_format_internal
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_STRINGS_INTERNAL_STR_FORMAT_FLOAT_CONVERSION_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ce26026512813125ded1f93bde9cab6b036083f5 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_4480_squid-3.3.14.cpp | 66b690bf0a8059661a9e7cf726a15f370f23b1e3 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | void
DestinationDomainLookup::LookupDone(const char *fqdn, const DnsLookupDetails &details, void *data)
{
ACLFilledChecklist *checklist = Filled((ACLChecklist*)data);
assert (checklist->asyncState() == DestinationDomainLookup::Instance());
checklist->asyncInProgress(false);
checklist->changeState (ACLChecklist::NullState::Instance());
checklist->markDestinationDomainChecked();
checklist->request->recordLookup(details);
checklist->matchNonBlocking();
} | [
"993273596@qq.com"
] | 993273596@qq.com |
f69d926dfaaa7ab744d962c75858c2353f063356 | 722732c3c575070f04d69896e094584b2e1c6b85 | /BulletHellMaker/src/Editor/EMP/EditorMovablePointPanel.cpp | 7442fd55cb929afb308b1c457a8785bd2b593c1d | [] | no_license | Miv99/BulletHellMaker | 6c702bf01bbc3f31f3ef0fe9482b760bebbf1101 | 6ad7fafab763bd2241e5e669c95c53f60fe182b5 | refs/heads/master | 2021-11-29T18:41:40.026183 | 2021-11-14T21:36:47 | 2021-11-14T21:36:47 | 175,186,909 | 3 | 1 | null | 2020-08-20T03:44:00 | 2019-03-12T10:24:32 | C++ | UTF-8 | C++ | false | false | 74,502 | cpp | #include <Editor/EMP/EditorMovablePointPanel.h>
#include <Mutex.h>
#include <Config.h>
#include <GuiConfig.h>
#include <Util/StringUtils.h>
#include <Editor/Util/EditorUtils.h>
#include <Editor/EMPA/EditorMovablePointActionPanel.h>
const std::string EditorMovablePointPanel::PROPERTIES_TAB_NAME = "MP Properties";
const std::string EditorMovablePointPanel::MOVEMENT_TAB_NAME = "MP Movement";
std::string EditorMovablePointPanel::getID(BULLET_ON_COLLISION_ACTION onCollisionAction) {
return std::to_string(static_cast<int>(onCollisionAction));
}
BULLET_ON_COLLISION_ACTION EditorMovablePointPanel::fromID(std::string id) {
return static_cast<BULLET_ON_COLLISION_ACTION>(std::stoi(std::string(id)));
}
std::string EditorMovablePointPanel::getID(std::shared_ptr<EMPSpawnType> spawnType) {
if (dynamic_cast<SpecificGlobalEMPSpawn*>(spawnType.get())) {
return "0";
} else if (dynamic_cast<EntityRelativeEMPSpawn*>(spawnType.get())) {
return "1";
} else if (dynamic_cast<EntityAttachedEMPSpawn*>(spawnType.get())) {
return "2";
}
}
EditorMovablePointPanel::EditorMovablePointPanel(MainEditorWindow& mainEditorWindow, std::shared_ptr<LevelPack> levelPack, SpriteLoader& spriteLoader, Clipboard& clipboard, std::shared_ptr<EditorMovablePoint> emp, int undoStackSize)
: CopyPasteable(EMP_COPY_PASTE_ID), mainEditorWindow(mainEditorWindow), levelPack(levelPack), emp(emp), clipboard(clipboard), undoStack(UndoStack(undoStackSize)) {
std::lock_guard<std::recursive_mutex> lock(tguiMutex);
spawnTypePositionMarkerPlacer = SingleMarkerPlacer::create(*(mainEditorWindow.getWindow()), clipboard);
spawnTypePositionMarkerPlacer->setPosition(0, 0);
spawnTypePositionMarkerPlacer->setSize("100%", "100%");
spawnTypePositionMarkerPlacerFinishEditing = tgui::Button::create();
spawnTypePositionMarkerPlacerFinishEditing->setSize(100, TEXT_BUTTON_HEIGHT);
spawnTypePositionMarkerPlacerFinishEditing->setTextSize(TEXT_SIZE);
spawnTypePositionMarkerPlacerFinishEditing->setText("Finish");
spawnTypePositionMarkerPlacerFinishEditing->onPress.connect([this]() {
finishEditingSpawnTypePosition();
});
tabs = TabsWithPanel::create(mainEditorWindow);
tabs->setPosition(0, 0);
tabs->setSize("100%", "100%");
add(tabs);
{
// Properties
propertiesPanel = tgui::ScrollablePanel::create();
id = tgui::Label::create();
empiAnimatableLabel = tgui::Label::create();
empiAnimatable = AnimatableChooser::create(spriteLoader);
// Invisible if empiAnimatable's value is a sprite
empiLoopAnimation = tgui::CheckBox::create("Loop animation");
// Invisible if loopAnimation is checked or a sprite is selected in empiAnimatable
empiBaseSpriteLabel = tgui::Label::create();
empiBaseSprite = AnimatableChooser::create(spriteLoader, true);
isBullet = tgui::CheckBox::create("Is bullet");
empiHitboxRadiusLabel = tgui::Label::create();
empiHitboxRadius = EditBox::create();
empiDespawnTimeLabel = tgui::Label::create();
// Max value is sum of time taken for every EMPA in empiActions
empiDespawnTime = std::make_shared<SliderWithEditBox>();
empiSpawnTypeLabel = tgui::Label::create();
// Entry ID is from getID()
empiSpawnType = tgui::ComboBox::create();
empiSpawnTypeTimeLabel = tgui::Label::create();
empiSpawnTypeTime = EditBox::create();
empiSpawnTypeXLabel = tgui::Label::create();
empiSpawnTypeX = EditBox::create();
empiSpawnTypeYLabel = tgui::Label::create();
empiSpawnTypeY = EditBox::create();
empiSpawnLocationManualSet = tgui::Button::create();
empiShadowTrailLifespanLabel = tgui::Label::create();
empiShadowTrailLifespan = EditBox::create();
empiShadowTrailIntervalLabel = tgui::Label::create();
empiShadowTrailInterval = EditBox::create();
empiDamageLabel = tgui::Label::create();
empiDamage = EditBox::create();
empiOnCollisionActionLabel = tgui::Label::create();
// Entry ID obtained from getID()
empiOnCollisionAction = tgui::ComboBox::create();
empiPierceResetTimeLabel = tgui::Label::create();
empiPierceResetTime = EditBox::create();
empiSoundSettingsLabel = tgui::Label::create();
empiSoundSettings = SoundSettingsGroup::create(format(RELATIVE_LEVEL_PACK_SOUND_FOLDER_PATH, levelPack->getName().c_str()));
empiBulletModelLabel = tgui::Label::create();
// Entry ID is bullet model ID
empiBulletModel = tgui::ComboBox::create();
empiInheritRadius = tgui::CheckBox::create();
empiInheritDespawnTime = tgui::CheckBox::create();
empiInheritShadowTrailInterval = tgui::CheckBox::create();
empiInheritShadowTrailLifespan = tgui::CheckBox::create();
empiInheritAnimatables = tgui::CheckBox::create();
empiInheritDamage = tgui::CheckBox::create();
empiInheritPierceResetTime = tgui::CheckBox::create();
empiInheritSoundSettings = tgui::CheckBox::create();
empiAnimatableLabel->setToolTip(createToolTip("The default sprite/animation for this movable point."));
empiLoopAnimation->setToolTip(createToolTip("If this is checked, the default animation will loop indefinitely."));
empiBaseSpriteLabel->setToolTip(createToolTip("The fallback sprite after the animation finishes. Only used if the default animation does not loop."));
isBullet->setToolTip(createToolTip("If this is checked, this movable point will be a bullet that is able to damage entities. If the bullet originated from \
a player, it can damage only enemies. If the bullet originated from an enemy, it can damage only players."));
empiHitboxRadiusLabel->setToolTip(createToolTip("The radius of this bullet. Only used if this movable point is a bullet."));
empiDespawnTimeLabel->setToolTip(createToolTip("Number of seconds after being spawned that this movable point despawns. When a movable point despawns, every movable point \
attached to it also despawns, so this effectively despawns all movable points in the movable point attachment tree with this one as the root."));
empiSpawnTypeLabel->setToolTip(createToolTip("Determines how this movable point will be spawned.\n\n\
\"Relative to map origin\" - Spawns at some absolute position\n\n\
\"Detached, relative to parent\" - Spawns relative to this movable point's parent\n\n\
\"Attached, relative to parent\" - Spawns relative to this movable point's parent and moves relative to its parent until this movable point does a detach movement action"));
empiSpawnTypeTimeLabel->setToolTip(createToolTip("Number of seconds after this movable point's parent spawns that this movable point spawns. If \
this movable point is the main movable point of its attack (the root of the attack's movable point tree), this value will be fixed to 0 so this movable point spawns as soon \
as the attack is executed."));
empiSpawnTypeXLabel->setToolTip(createToolTip("The x-position for this movable point's spawn. See \"Spawn type\" for how this position will be interpreted."));
empiSpawnTypeYLabel->setToolTip(createToolTip("The y-position for this movable point's spawn. See \"Spawn type\" for how this position will be interpreted."));
empiSpawnLocationManualSet->setToolTip(createToolTip("Opens a map to help visualize and set this movable point's spawn position."));
empiShadowTrailLifespanLabel->setToolTip(createToolTip("Number of seconds each of this movable point's shadows last. Shadows are purely visual and create a movement trail."));
empiShadowTrailIntervalLabel->setToolTip(createToolTip("Number of seconds between the creation of each shadow. Shadows are purely visual and create a movement trail."));
empiDamageLabel->setToolTip(createToolTip("Damage dealt to an enemy/player on contact with this bullet. Only used if this movable point is a bullet. Value will be rounded to the nearest integer."));
empiOnCollisionActionLabel->setToolTip(createToolTip("Determines how this bullet will act on contact with an enemy/player.\n\n\
\"Destroy self only\" - This bullet becomes invisible and intangible upon hitting an enemy/player but will still continue following its movement actions until it despawns. \
This means any movable points attached to this bullet when it collided with an enemy/player will behave as if nothing happened. \n\n\
\"Destroy self and attached children\" - This bullet, and every movable point attached to it, despawns upon hitting an enemy/player. When a movable point despawns, every movable point \
attached to it also despawns, so this effectively despawns all movable points in the movable point attachment tree with this one as the root. \n\n\
\"Pierce players/enemies\" - This bullet does not do anything special upon hitting an enemy/player, so it is able to hit multiple enemies/players multiple times. \
Each enemy/player can be hit at most every \"Pierce reset time\" seconds by the same bullet. Players also have a custom invulnerability time every time they take damage, \
so this should be considered as well."));
empiPierceResetTimeLabel->setToolTip(createToolTip("Minimum number of seconds after this bullet hits a player/enemy that it can hit the same player/enemy again. \
Players also have a custom invulnerability time every time they take damage, so this should be considered as well."));
empiSoundSettingsLabel->setToolTip(createToolTip("Settings for the sound to be played when this movable point is spawned."));
empiBulletModelLabel->setToolTip(createToolTip("The movable point model that this movable point will use. This is purely for convenience by allowing this movable point to \
use the radius, despawn time, shadow settings, sprites and animations, damage, and/or sound settings of some user-defined model such that whenever the model is updated, this movable \
point will update only the values it wants to inherit to match the model."));
empiInheritRadius->setToolTip(createToolTip("If this is checked, this movable point will use its model's radius."));
empiInheritDespawnTime->setToolTip(createToolTip("If this is checked, this movable point will use its model's despawn time."));
empiInheritShadowTrailInterval->setToolTip(createToolTip("If this is checked, this movable point will use its model's shadow trail interval."));
empiInheritShadowTrailLifespan->setToolTip(createToolTip("If this is checked, this movable point will use its model's shadow trail lifespan."));
empiInheritAnimatables->setToolTip(createToolTip("If this is checked, this movable point will use its model's sprites and animations."));
empiInheritDamage->setToolTip(createToolTip("If this is checked, this movable point will use its model's damage."));
empiInheritPierceResetTime->setToolTip(createToolTip("If this is checked, this movable point will use its model's pierce reset time."));
empiInheritSoundSettings->setToolTip(createToolTip("If this is checked, this movable point will use its model's sound settings."));
propertiesPanel->setHorizontalScrollAmount(SCROLL_AMOUNT);
propertiesPanel->setVerticalScrollAmount(SCROLL_AMOUNT);
empiSpawnType->setChangeItemOnScroll(false);
empiOnCollisionAction->setChangeItemOnScroll(false);
empiBulletModel->setChangeItemOnScroll(false);
id->setTextSize(TEXT_SIZE);
empiAnimatableLabel->setTextSize(TEXT_SIZE);
empiLoopAnimation->setTextSize(TEXT_SIZE);
empiBaseSpriteLabel->setTextSize(TEXT_SIZE);
isBullet->setTextSize(TEXT_SIZE);
empiHitboxRadiusLabel->setTextSize(TEXT_SIZE);
empiHitboxRadius->setTextSize(TEXT_SIZE);
empiDespawnTimeLabel->setTextSize(TEXT_SIZE);
empiDespawnTime->setTextSize(TEXT_SIZE);
empiSpawnTypeLabel->setTextSize(TEXT_SIZE);
empiSpawnType->setTextSize(TEXT_SIZE);
empiSpawnTypeTimeLabel->setTextSize(TEXT_SIZE);
empiSpawnTypeTime->setTextSize(TEXT_SIZE);
empiSpawnTypeXLabel->setTextSize(TEXT_SIZE);
empiSpawnTypeX->setTextSize(TEXT_SIZE);
empiSpawnTypeYLabel->setTextSize(TEXT_SIZE);
empiSpawnTypeY->setTextSize(TEXT_SIZE);
empiSpawnLocationManualSet->setTextSize(TEXT_SIZE);
empiShadowTrailLifespanLabel->setTextSize(TEXT_SIZE);
empiShadowTrailLifespan->setTextSize(TEXT_SIZE);
empiShadowTrailIntervalLabel->setTextSize(TEXT_SIZE);
empiShadowTrailInterval->setTextSize(TEXT_SIZE);
empiDamageLabel->setTextSize(TEXT_SIZE);
empiDamage->setTextSize(TEXT_SIZE);
empiOnCollisionActionLabel->setTextSize(TEXT_SIZE);
empiOnCollisionAction->setTextSize(TEXT_SIZE);
empiPierceResetTimeLabel->setTextSize(TEXT_SIZE);
empiPierceResetTime->setTextSize(TEXT_SIZE);
empiBulletModelLabel->setTextSize(TEXT_SIZE);
empiBulletModel->setTextSize(TEXT_SIZE);
empiInheritRadius->setTextSize(TEXT_SIZE);
empiInheritDespawnTime->setTextSize(TEXT_SIZE);
empiInheritShadowTrailInterval->setTextSize(TEXT_SIZE);
empiInheritShadowTrailLifespan->setTextSize(TEXT_SIZE);
empiInheritAnimatables->setTextSize(TEXT_SIZE);
empiInheritDamage->setTextSize(TEXT_SIZE);
empiInheritPierceResetTime->setTextSize(TEXT_SIZE);
empiInheritSoundSettings->setTextSize(TEXT_SIZE);
empiSoundSettingsLabel->setTextSize(TEXT_SIZE);
id->setText("Movable point ID " + std::to_string(emp->getID()));
empiHitboxRadiusLabel->setText("Hitbox radius");
empiAnimatableLabel->setText("Sprite/Animation");
empiBaseSpriteLabel->setText("Base sprite");
empiDespawnTimeLabel->setText("Time to despawn");
empiSpawnTypeLabel->setText("Spawn type");
empiSpawnTypeTimeLabel->setText("Spawn delay");
empiSpawnTypeXLabel->setText("Spawn X");
empiSpawnTypeYLabel->setText("Spawn Y");
empiSpawnLocationManualSet->setText("Spawn position manual set");
empiShadowTrailLifespanLabel->setText("Shadow trail lifespan");
empiShadowTrailIntervalLabel->setText("Shadow trail spawn interval");
empiDamageLabel->setText("Damage");
empiOnCollisionActionLabel->setText("On-collision action");
empiPierceResetTimeLabel->setText("Seconds between piercing hits");
empiBulletModelLabel->setText("Movable point model");
empiInheritRadius->setText("Inherit radius");
empiInheritDespawnTime->setText("Inherit despawn time");
empiInheritShadowTrailInterval->setText("Inherit shadow trail interval");
empiInheritShadowTrailLifespan->setText("Inherit shadow trail lifespan");
empiInheritAnimatables->setText("Inherit animatables");
empiInheritDamage->setText("Inherit damage");
empiInheritPierceResetTime->setText("Inherit pierce reset time");
empiInheritSoundSettings->setText("Inherit sound settings");
empiSoundSettingsLabel->setText("Spawn sound");
empiSpawnType->addItem("Relative to map origin", "0");
empiSpawnType->addItem("Detached, relative to parent", "1");
empiSpawnType->addItem("Attached, relative to parent", "2");
empiOnCollisionAction->addItem("Destroy self only", getID(BULLET_ON_COLLISION_ACTION::DESTROY_THIS_BULLET_ONLY));
empiOnCollisionAction->addItem("Destroy self and attached children", getID(BULLET_ON_COLLISION_ACTION::DESTROY_THIS_BULLET_AND_ATTACHED_CHILDREN));
empiOnCollisionAction->addItem("Pierce players/enemies", getID(BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY));
empiBulletModel->addItem("None", "-1");
for (auto it = levelPack->getBulletModelIteratorBegin(); it != levelPack->getBulletModelIteratorEnd(); it++) {
empiBulletModel->addItem(it->second->getName(), std::to_string(it->second->getID()));
}
levelPack->getOnChange()->sink().connect<EditorMovablePointPanel, &EditorMovablePointPanel::onLevelPackChange>(this);
emp->loadBulletModel(*levelPack);
empiAnimatable->onValueChange.connect([this](Animatable value) {
if (this->ignoreSignals) {
return;
}
Animatable oldValue = this->emp->getAnimatable();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setAnimatable(value);
this->ignoreSignals = true;
empiAnimatable->setValue(value);
empiLoopAnimation->setVisible(!value.isSprite());
empiBaseSprite->setVisible(!empiLoopAnimation->isChecked() && !value.isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setAnimatable(oldValue);
this->ignoreSignals = true;
empiAnimatable->setValue(oldValue);
empiLoopAnimation->setVisible(!oldValue.isSprite());
empiBaseSprite->setVisible(!empiLoopAnimation->isChecked() && !oldValue.isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
empiLoopAnimation->onChange.connect([this](bool value) {
if (this->ignoreSignals) {
return;
}
bool oldValue = this->emp->getIsBullet();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setLoopAnimation(value);
this->ignoreSignals = true;
empiLoopAnimation->setChecked(value);
empiBaseSprite->setVisible(!value && !empiAnimatable->getValue().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setLoopAnimation(oldValue);
this->ignoreSignals = true;
empiLoopAnimation->setChecked(oldValue);
empiBaseSprite->setVisible(!oldValue && !empiAnimatable->getValue().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
empiBaseSprite->onValueChange.connect([this](Animatable value) {
if (this->ignoreSignals) {
return;
}
Animatable oldValue = this->emp->getAnimatable();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setBaseSprite(value);
this->ignoreSignals = true;
empiBaseSprite->setValue(value);
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setBaseSprite(oldValue);
this->ignoreSignals = true;
empiBaseSprite->setValue(oldValue);
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
isBullet->onChange.connect([this](bool value) {
if (this->ignoreSignals) {
return;
}
bool oldValue = this->emp->getIsBullet();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setIsBullet(value);
this->ignoreSignals = true;
isBullet->setChecked(value);
empiOnCollisionAction->setEnabled(this->emp->getIsBullet());
empiHitboxRadius->setEnabled((!this->emp->getInheritRadius() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiDamage->setEnabled((!this->emp->getInheritDamage() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiPierceResetTimeLabel->setVisible(this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
empiPierceResetTime->setVisible(this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setIsBullet(oldValue);
this->ignoreSignals = true;
isBullet->setChecked(oldValue);
empiOnCollisionAction->setEnabled(this->emp->getIsBullet());
empiHitboxRadius->setEnabled((!this->emp->getInheritRadius() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiDamage->setEnabled((!this->emp->getInheritDamage() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiPierceResetTimeLabel->setVisible(this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
empiPierceResetTime->setVisible(this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
empiHitboxRadius->onValueChange.connect([this](tgui::String value) {
if (this->ignoreSignals) {
return;
}
std::string oldValue = this->emp->getRawHitboxRadius();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setHitboxRadius(static_cast<std::string>(value));
this->ignoreSignals = true;
empiHitboxRadius->setText(static_cast<std::string>(value));
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setHitboxRadius(oldValue);
this->ignoreSignals = true;
empiHitboxRadius->setText(oldValue);
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
empiDespawnTime->onValueChange.connect([this](float value) {
if (this->ignoreSignals) {
return;
}
float oldValue = this->emp->getDespawnTime();
undoStack.execute(UndoableCommand([this, value]() {
this->emp->setDespawnTime(value);
this->ignoreSignals = true;
empiDespawnTime->setValue(value);
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}, [this, oldValue]() {
this->emp->setDespawnTime(oldValue);
this->ignoreSignals = true;
empiDespawnTime->setValue(oldValue);
this->ignoreSignals = false;
onEMPModify.emit(this, this->emp);
}));
});
empiSpawnType->onItemSelect.connect([this](tgui::String item, tgui::String id) {
if (ignoreSignals) {
return;
}
std::shared_ptr<EMPSpawnType> oldSpawnType = this->emp->getSpawnType();
if (id == "0") {
undoStack.execute(UndoableCommand(
[this]() {
this->emp->setSpawnType(std::make_shared<SpecificGlobalEMPSpawn>(static_cast<std::string>(empiSpawnTypeTime->getText()),
static_cast<std::string>(empiSpawnTypeX->getText()), static_cast<std::string>(empiSpawnTypeY->getText())));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
},
[this, oldSpawnType]() {
this->emp->setSpawnType(oldSpawnType);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
}));
} else if (id == "1") {
undoStack.execute(UndoableCommand(
[this]() {
this->emp->setSpawnType(std::make_shared<EntityRelativeEMPSpawn>(static_cast<std::string>(empiSpawnTypeTime->getText()),
static_cast<std::string>(empiSpawnTypeX->getText()), static_cast<std::string>(empiSpawnTypeY->getText())));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
},
[this, oldSpawnType]() {
this->emp->setSpawnType(oldSpawnType);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
}));
} else if (id == "2") {
undoStack.execute(UndoableCommand(
[this]() {
this->emp->setSpawnType(std::make_shared<EntityAttachedEMPSpawn>(static_cast<std::string>(empiSpawnTypeTime->getText()),
static_cast<std::string>(empiSpawnTypeX->getText()), static_cast<std::string>(empiSpawnTypeY->getText())));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
},
[this, oldSpawnType]() {
this->emp->setSpawnType(oldSpawnType);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnType->setSelectedItemById(getID(this->emp->getSpawnType()));
ignoreSignals = false;
}));
} else {
// You forgot a case
assert(false);
}
});
empiSpawnTypeTime->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getSpawnType()->getRawTime();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setSpawnTypeTime(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeTime->setText(this->emp->getSpawnType()->getRawTime());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setSpawnTypeTime(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeTime->setText(this->emp->getSpawnType()->getRawTime());
ignoreSignals = false;
}));
});
empiSpawnTypeX->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getSpawnType()->getRawX();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->getSpawnType()->setX(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeX->setText(this->emp->getSpawnType()->getRawX());
movementEditorPanel->setVisualizerStartPosX(this->emp->getSpawnType()->getRawX());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->getSpawnType()->setX(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeX->setText(this->emp->getSpawnType()->getRawX());
movementEditorPanel->setVisualizerStartPosX(this->emp->getSpawnType()->getRawX());
ignoreSignals = false;
}));
});
empiSpawnTypeY->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getSpawnType()->getRawY();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->getSpawnType()->setY(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeY->setText(this->emp->getSpawnType()->getRawY());
movementEditorPanel->setVisualizerStartPosY(this->emp->getSpawnType()->getRawY());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->getSpawnType()->setY(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSpawnTypeY->setText(this->emp->getSpawnType()->getRawY());
movementEditorPanel->setVisualizerStartPosY(this->emp->getSpawnType()->getRawY());
ignoreSignals = false;
}));
});
empiSpawnLocationManualSet->onPress.connect([this]() {
savedWidgets = propertiesPanel->getWidgets();
horizontalScrollPos = propertiesPanel->getHorizontalScrollbarValue();
verticalScrollPos = propertiesPanel->getVerticalScrollbarValue();
propertiesPanel->removeAllWidgets();
propertiesPanel->setHorizontalScrollbarValue(0);
propertiesPanel->setVerticalScrollbarValue(0);
float x, y;
try {
x = std::stof(this->emp->getSpawnType()->getRawX());
y = std::stof(this->emp->getSpawnType()->getRawY());
} catch (...) {
x = 0;
y = 0;
}
spawnTypePositionMarkerPlacer->clearUndoStack();
spawnTypePositionMarkerPlacer->setMarkers({std::make_pair(sf::Vector2f(x, y), sf::Color::Red)});
spawnTypePositionMarkerPlacer->lookAt(sf::Vector2f(0, 0));
propertiesPanel->add(spawnTypePositionMarkerPlacer);
propertiesPanel->add(spawnTypePositionMarkerPlacerFinishEditing);
spawnTypePositionMarkerPlacer->setFocused(true);
placingSpawnLocation = true;
});
empiShadowTrailLifespan->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getRawShadowTrailLifespan();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setShadowTrailLifespan(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setShadowTrailLifespan(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
ignoreSignals = false;
}));
});
empiShadowTrailInterval->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getRawShadowTrailInterval();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setShadowTrailInterval(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setShadowTrailInterval(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
ignoreSignals = false;
}));
});
empiDamage->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getRawDamage();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setDamage(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiDamage->setText(this->emp->getRawDamage());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setDamage(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiDamage->setText(this->emp->getRawDamage());
ignoreSignals = false;
}));
});
empiOnCollisionAction->onItemSelect.connect([this](tgui::String item, tgui::String id) {
if (ignoreSignals) {
return;
}
BULLET_ON_COLLISION_ACTION action = fromID(static_cast<std::string>(empiOnCollisionAction->getSelectedItemId()));
BULLET_ON_COLLISION_ACTION oldAction = this->emp->getOnCollisionAction();
undoStack.execute(UndoableCommand(
[this, action]() {
this->emp->setOnCollisionAction(action);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiOnCollisionAction->setSelectedItemById(getID(action));
empiPierceResetTimeLabel->setVisible(action == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
empiPierceResetTime->setVisible(action == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
ignoreSignals = false;
},
[this, oldAction]() {
this->emp->setOnCollisionAction(oldAction);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiOnCollisionAction->setSelectedItemById(getID(oldAction));
empiPierceResetTimeLabel->setVisible(oldAction == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
empiPierceResetTime->setVisible(oldAction == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY && this->emp->getIsBullet());
ignoreSignals = false;
}));
});
empiPierceResetTime->onValueChange.connect([this](tgui::String value) {
if (ignoreSignals) {
return;
}
std::string oldValue = this->emp->getRawPierceResetTime();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setPierceResetTime(static_cast<std::string>(value));
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setPierceResetTime(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
ignoreSignals = false;
}));
});
empiSoundSettings->onValueChange.connect([this](SoundSettings value) {
if (ignoreSignals) {
return;
}
SoundSettings oldValue = this->emp->getSoundSettings();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setSoundSettings(value);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSoundSettings->initSettings(this->emp->getSoundSettings());
ignoreSignals = false;
},
[this, oldValue]() {
this->emp->setSoundSettings(oldValue);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiSoundSettings->initSettings(this->emp->getSoundSettings());
ignoreSignals = false;
}));
});
empiBulletModel->onItemSelect.connect([this](tgui::String item, tgui::String id) {
if (ignoreSignals) {
return;
}
int bulletModelID = id.toInt();
if (item == "") bulletModelID = -1;
int oldBulletModelID = this->emp->getBulletModelID();
std::string radius = this->emp->getRawHitboxRadius();
float despawnTime = this->emp->getDespawnTime();
std::string interval = this->emp->getRawShadowTrailInterval();
std::string lifespan = this->emp->getRawShadowTrailLifespan();
Animatable animatable = this->emp->getAnimatable();
Animatable baseSprite = this->emp->getBaseSprite();
bool loopAnimation = this->emp->getLoopAnimation();
std::string damage = this->emp->getRawDamage();
std::string pierceResetTime = this->emp->getRawPierceResetTime();
SoundSettings sound = this->emp->getSoundSettings();
undoStack.execute(UndoableCommand(
[this, bulletModelID, radius, despawnTime, interval, lifespan, animatable, baseSprite, loopAnimation, damage, pierceResetTime, sound]() {
if (bulletModelID == -1) {
this->emp->removeBulletModel();
} else {
this->emp->setBulletModel(this->levelPack->getBulletModel(bulletModelID));
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
if (bulletModelID == -1) {
empiBulletModel->deselectItem();
} else {
empiBulletModel->setSelectedItemById(std::to_string(this->emp->getBulletModelID()));
}
empiHitboxRadius->setText(this->emp->getRawHitboxRadius());
empiDespawnTime->setValue(this->emp->getDespawnTime());
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
empiAnimatable->setValue(this->emp->getAnimatable());
empiLoopAnimation->setChecked(this->emp->getLoopAnimation());
empiBaseSprite->setValue(this->emp->getAnimatable());
empiDamage->setText(this->emp->getRawDamage());
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
empiSoundSettings->initSettings(this->emp->getSoundSettings());
empiLoopAnimation->setVisible(!this->emp->getAnimatable().isSprite());
empiBaseSprite->setVisible(!this->emp->getLoopAnimation() && !this->emp->getAnimatable().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
empiPierceResetTimeLabel->setVisible((this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && this->emp->getIsBullet());
empiPierceResetTime->setVisible((this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && this->emp->getIsBullet());
empiHitboxRadius->setEnabled((!this->emp->getInheritRadius() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiDespawnTime->setEnabled(!this->emp->getInheritDespawnTime() || this->emp->getBulletModelID() < 0);
empiShadowTrailInterval->setEnabled(!this->emp->getInheritShadowTrailInterval() || this->emp->getBulletModelID() < 0);
empiShadowTrailLifespan->setEnabled(!this->emp->getInheritShadowTrailLifespan() || this->emp->getBulletModelID() < 0);
empiAnimatable->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiBaseSprite->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiDamage->setEnabled((!this->emp->getInheritDamage() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiPierceResetTime->setEnabled((!this->emp->getInheritPierceResetTime() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiSoundSettings->setEnabled(!this->emp->getInheritSoundSettings() || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldBulletModelID, radius, despawnTime, interval, lifespan, animatable, baseSprite, loopAnimation, damage, pierceResetTime, sound]() {
this->emp->setHitboxRadius(radius);
this->emp->setDespawnTime(despawnTime);
this->emp->setShadowTrailLifespan(lifespan);
this->emp->setShadowTrailInterval(interval);
this->emp->setAnimatable(animatable);
this->emp->setLoopAnimation(loopAnimation);
this->emp->setBaseSprite(baseSprite);
this->emp->setDamage(damage);
this->emp->setPierceResetTime(pierceResetTime);
this->emp->setSoundSettings(sound);
if (oldBulletModelID == -1) {
this->emp->removeBulletModel();
} else {
this->emp->setBulletModel(this->levelPack->getBulletModel(oldBulletModelID));
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
if (oldBulletModelID == -1) {
empiBulletModel->deselectItem();
} else {
empiBulletModel->setSelectedItemById(std::to_string(this->emp->getBulletModelID()));
}
empiHitboxRadius->setText(this->emp->getRawHitboxRadius());
empiDespawnTime->setValue(this->emp->getDespawnTime());
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
empiAnimatable->setValue(this->emp->getAnimatable());
empiLoopAnimation->setChecked(this->emp->getLoopAnimation());
empiBaseSprite->setValue(this->emp->getAnimatable());
empiDamage->setText(this->emp->getRawDamage());
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
empiSoundSettings->initSettings(this->emp->getSoundSettings());
empiLoopAnimation->setVisible(!this->emp->getAnimatable().isSprite());
empiBaseSprite->setVisible(!this->emp->getLoopAnimation() && !this->emp->getAnimatable().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
empiPierceResetTimeLabel->setVisible((this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && this->emp->getIsBullet());
empiPierceResetTime->setVisible((this->emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && this->emp->getIsBullet());
empiHitboxRadius->setEnabled(!this->emp->getInheritRadius() || this->emp->getBulletModelID() < 0);
empiDespawnTime->setEnabled(!this->emp->getInheritDespawnTime() || this->emp->getBulletModelID() < 0);
empiShadowTrailInterval->setEnabled(!this->emp->getInheritShadowTrailInterval() || this->emp->getBulletModelID() < 0);
empiShadowTrailLifespan->setEnabled(!this->emp->getInheritShadowTrailLifespan() || this->emp->getBulletModelID() < 0);
empiAnimatable->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiBaseSprite->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiDamage->setEnabled((!this->emp->getInheritDamage() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiPierceResetTime->setEnabled((!this->emp->getInheritPierceResetTime() || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
empiSoundSettings->setEnabled(!this->emp->getInheritSoundSettings() || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritRadius->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritRadius();
std::string oldInheritValue = this->emp->getRawHitboxRadius();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritRadius(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritRadius->setChecked(this->emp->getInheritRadius());
empiHitboxRadius->setText(this->emp->getRawHitboxRadius());
empiHitboxRadius->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritRadius(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setHitboxRadius(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritRadius->setChecked(this->emp->getInheritRadius());
empiHitboxRadius->setText(this->emp->getRawHitboxRadius());
empiHitboxRadius->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritDespawnTime->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritDespawnTime();
float oldInheritValue = this->emp->getDespawnTime();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritDespawnTime(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritDespawnTime->setChecked(this->emp->getInheritDespawnTime());
empiDespawnTime->setValue(this->emp->getDespawnTime());
empiDespawnTime->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritDespawnTime(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setDespawnTime(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritDespawnTime->setChecked(this->emp->getInheritDespawnTime());
empiDespawnTime->setValue(this->emp->getDespawnTime());
empiDespawnTime->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritShadowTrailInterval->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritShadowTrailInterval();
std::string oldInheritValue = this->emp->getRawShadowTrailInterval();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritShadowTrailInterval(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritShadowTrailInterval->setChecked(this->emp->getInheritShadowTrailInterval());
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
empiShadowTrailInterval->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritShadowTrailInterval(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setShadowTrailInterval(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritShadowTrailInterval->setChecked(this->emp->getInheritShadowTrailInterval());
empiShadowTrailInterval->setText(this->emp->getRawShadowTrailInterval());
empiShadowTrailInterval->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritShadowTrailLifespan->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritShadowTrailLifespan();
std::string oldInheritValue = this->emp->getRawShadowTrailLifespan();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritShadowTrailLifespan(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritShadowTrailLifespan->setChecked(this->emp->getInheritShadowTrailLifespan());
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
empiShadowTrailLifespan->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritShadowTrailLifespan(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setShadowTrailLifespan(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritShadowTrailLifespan->setChecked(this->emp->getInheritShadowTrailLifespan());
empiShadowTrailLifespan->setText(this->emp->getRawShadowTrailLifespan());
empiShadowTrailLifespan->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritAnimatables->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritAnimatables();
Animatable oldAnimatable = this->emp->getAnimatable();
Animatable oldBaseSprite = this->emp->getBaseSprite();
bool oldLoopAnimation = this->emp->getLoopAnimation();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritAnimatables(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritAnimatables->setChecked(this->emp->getInheritAnimatables());
empiAnimatable->setValue(this->emp->getAnimatable());
empiBaseSprite->setValue(this->emp->getBaseSprite());
empiLoopAnimation->setChecked(this->emp->getLoopAnimation());
empiLoopAnimation->setVisible(!this->emp->getAnimatable().isSprite());
empiBaseSprite->setVisible(!this->emp->getLoopAnimation() && !this->emp->getAnimatable().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
empiAnimatable->setEnabled(!value || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setEnabled(!value || this->emp->getBulletModelID() < 0);
empiBaseSprite->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldAnimatable, oldBaseSprite, oldLoopAnimation]() {
this->emp->setInheritAnimatables(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setAnimatable(oldAnimatable);
this->emp->setBaseSprite(oldBaseSprite);
this->emp->setLoopAnimation(oldLoopAnimation);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritAnimatables->setChecked(this->emp->getInheritAnimatables());
empiAnimatable->setValue(this->emp->getAnimatable());
empiBaseSprite->setValue(this->emp->getBaseSprite());
empiLoopAnimation->setChecked(this->emp->getLoopAnimation());
empiLoopAnimation->setVisible(!this->emp->getAnimatable().isSprite());
empiBaseSprite->setVisible(!this->emp->getLoopAnimation() && !this->emp->getAnimatable().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
empiAnimatable->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
empiBaseSprite->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
empiInheritDamage->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritDamage();
std::string oldInheritValue = this->emp->getRawDamage();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritDamage(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritDamage->setChecked(this->emp->getInheritDamage());
empiDamage->setText(this->emp->getRawDamage());
empiDamage->setEnabled((!value || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritDamage(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setDamage(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritDamage->setChecked(this->emp->getInheritDamage());
empiDamage->setText(this->emp->getRawDamage());
empiDamage->setEnabled((!oldValue || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
ignoreSignals = false;
}));
});
empiInheritPierceResetTime->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritPierceResetTime();
std::string oldInheritValue = this->emp->getRawPierceResetTime();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritPierceResetTime(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritPierceResetTime->setChecked(this->emp->getInheritPierceResetTime());
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
empiPierceResetTime->setEnabled((!value || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritPierceResetTime(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setPierceResetTime(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritPierceResetTime->setChecked(this->emp->getInheritPierceResetTime());
empiPierceResetTime->setText(this->emp->getRawPierceResetTime());
empiPierceResetTime->setEnabled((!oldValue || this->emp->getBulletModelID() < 0) && this->emp->getIsBullet());
ignoreSignals = false;
}));
});
empiInheritSoundSettings->onChange.connect([this](bool value) {
if (ignoreSignals) {
return;
}
bool oldValue = this->emp->getInheritSoundSettings();
SoundSettings oldInheritValue = this->emp->getSoundSettings();
undoStack.execute(UndoableCommand(
[this, value]() {
this->emp->setInheritSoundSettings(value, *this->levelPack);
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritSoundSettings->setChecked(this->emp->getInheritSoundSettings());
empiSoundSettings->initSettings(this->emp->getSoundSettings());
empiSoundSettings->setEnabled(!value || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
},
[this, oldValue, oldInheritValue]() {
this->emp->setInheritSoundSettings(oldValue, *this->levelPack);
if (!oldValue) {
this->emp->setSoundSettings(oldInheritValue);
}
onEMPModify.emit(this, this->emp);
ignoreSignals = true;
empiInheritSoundSettings->setChecked(this->emp->getInheritSoundSettings());
empiSoundSettings->initSettings(this->emp->getSoundSettings());
empiSoundSettings->setEnabled(!oldValue || this->emp->getBulletModelID() < 0);
ignoreSignals = false;
}));
});
updateAllWidgetValues();
id->setPosition(GUI_PADDING_X, GUI_PADDING_Y);
empiAnimatableLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(id) + GUI_PADDING_Y);
empiAnimatable->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiAnimatableLabel) + GUI_LABEL_PADDING_Y);
empiLoopAnimation->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiAnimatable) + GUI_PADDING_Y);
empiBaseSpriteLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiLoopAnimation) + GUI_PADDING_Y * 2);
empiBaseSprite->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiBaseSpriteLabel) + GUI_LABEL_PADDING_Y);
empiBulletModelLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiBaseSprite) + GUI_PADDING_Y * 2);
empiBulletModel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiBulletModelLabel) + GUI_LABEL_PADDING_Y);
empiInheritRadius->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiBulletModel) + GUI_LABEL_PADDING_Y);
empiInheritDespawnTime->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritRadius) + GUI_LABEL_PADDING_Y);
empiInheritShadowTrailLifespan->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritDespawnTime) + GUI_LABEL_PADDING_Y);
empiInheritShadowTrailInterval->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritShadowTrailLifespan) + GUI_LABEL_PADDING_Y);
empiInheritAnimatables->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritShadowTrailInterval) + GUI_LABEL_PADDING_Y);
empiInheritDamage->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritAnimatables) + GUI_LABEL_PADDING_Y);
empiInheritPierceResetTime->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritDamage) + GUI_LABEL_PADDING_Y);
empiInheritSoundSettings->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritPierceResetTime) + GUI_LABEL_PADDING_Y);
isBullet->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiInheritSoundSettings) + GUI_PADDING_Y * 2);
empiHitboxRadiusLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(isBullet) + GUI_PADDING_Y);
empiHitboxRadius->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiHitboxRadiusLabel) + GUI_LABEL_PADDING_Y);
empiDamageLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiHitboxRadius) + GUI_PADDING_Y * 2);
empiDamage->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiDamageLabel) + GUI_LABEL_PADDING_Y);
empiOnCollisionActionLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiDamage) + GUI_PADDING_Y);
empiOnCollisionAction->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiOnCollisionActionLabel) + GUI_LABEL_PADDING_Y);
empiPierceResetTimeLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiOnCollisionAction) + GUI_PADDING_Y);
empiPierceResetTime->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiPierceResetTimeLabel) + GUI_LABEL_PADDING_Y);
empiDespawnTimeLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiPierceResetTime) + GUI_PADDING_Y * 2);
empiDespawnTime->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiDespawnTimeLabel) + GUI_LABEL_PADDING_Y);
empiSpawnTypeLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiDespawnTime) + GUI_PADDING_Y * 2);
empiSpawnType->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeLabel) + GUI_LABEL_PADDING_Y);
empiSpawnTypeTimeLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnType) + GUI_PADDING_Y);
empiSpawnTypeTime->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeTimeLabel) + GUI_LABEL_PADDING_Y);
empiSpawnTypeXLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeTime) + GUI_PADDING_Y);
empiSpawnTypeX->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeXLabel) + GUI_LABEL_PADDING_Y);
empiSpawnTypeYLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeX) + GUI_PADDING_Y);
empiSpawnTypeY->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeYLabel) + GUI_LABEL_PADDING_Y);
empiSpawnLocationManualSet->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnTypeY) + GUI_PADDING_Y);
empiSoundSettingsLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSpawnLocationManualSet) + GUI_PADDING_Y * 2);
empiSoundSettings->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSoundSettingsLabel) + GUI_LABEL_PADDING_Y);
empiShadowTrailLifespanLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiSoundSettings) + GUI_PADDING_Y * 2);
empiShadowTrailLifespan->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiShadowTrailLifespanLabel) + GUI_LABEL_PADDING_Y);
empiShadowTrailIntervalLabel->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiShadowTrailLifespan) + GUI_PADDING_Y);
empiShadowTrailInterval->setPosition(tgui::bindLeft(id), tgui::bindBottom(empiShadowTrailIntervalLabel) + GUI_LABEL_PADDING_Y);
// For some reason, ScrollablePanels' sizes don't fit the last widget, so this is to make sure this one does
auto scrollablePanelBuffer = tgui::Label::create();
scrollablePanelBuffer->setPosition(0, tgui::bindBottom(empiShadowTrailInterval) + GUI_PADDING_Y);
propertiesPanel->add(scrollablePanelBuffer);
tgui::Layout fillWidth = tgui::bindWidth(propertiesPanel) - GUI_PADDING_X * 2;
empiLoopAnimation->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiAnimatable->setSize(fillWidth, 0);
empiBaseSprite->setSize(fillWidth, 0);
empiAnimatable->setAnimatablePictureSize(fillWidth, tgui::bindMin(tgui::bindWidth(propertiesPanel) - GUI_PADDING_X * 2, 120));
empiBaseSprite->setAnimatablePictureSize(fillWidth, tgui::bindMin(tgui::bindWidth(propertiesPanel) - GUI_PADDING_X * 2, 120));
empiHitboxRadius->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiDespawnTime->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiSpawnType->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiSpawnTypeTime->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiSpawnTypeX->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiSpawnTypeY->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiSpawnLocationManualSet->setSize(fillWidth, TEXT_BUTTON_HEIGHT);
empiShadowTrailLifespan->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiShadowTrailInterval->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiDamage->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiOnCollisionAction->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiPierceResetTime->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiBulletModel->setSize(fillWidth, TEXT_BOX_HEIGHT);
empiInheritRadius->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritDespawnTime->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritShadowTrailInterval->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritShadowTrailLifespan->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritAnimatables->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritDamage->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritPierceResetTime->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
empiInheritSoundSettings->setSize(CHECKBOX_SIZE, CHECKBOX_SIZE);
propertiesPanel->add(id);
propertiesPanel->add(empiAnimatableLabel);
propertiesPanel->add(empiAnimatable);
propertiesPanel->add(empiLoopAnimation);
propertiesPanel->add(empiBaseSpriteLabel);
propertiesPanel->add(empiBaseSprite);
propertiesPanel->add(isBullet);
propertiesPanel->add(empiHitboxRadiusLabel);
propertiesPanel->add(empiHitboxRadius);
propertiesPanel->add(empiDespawnTimeLabel);
propertiesPanel->add(empiDespawnTime);
propertiesPanel->add(empiSpawnTypeLabel);
propertiesPanel->add(empiSpawnType);
propertiesPanel->add(empiSpawnTypeTimeLabel);
propertiesPanel->add(empiSpawnTypeTime);
propertiesPanel->add(empiSpawnTypeXLabel);
propertiesPanel->add(empiSpawnTypeX);
propertiesPanel->add(empiSpawnTypeYLabel);
propertiesPanel->add(empiSpawnTypeY);
propertiesPanel->add(empiSpawnLocationManualSet);
propertiesPanel->add(empiShadowTrailLifespanLabel);
propertiesPanel->add(empiShadowTrailLifespan);
propertiesPanel->add(empiShadowTrailIntervalLabel);
propertiesPanel->add(empiShadowTrailInterval);
propertiesPanel->add(empiDamageLabel);
propertiesPanel->add(empiDamage);
propertiesPanel->add(empiOnCollisionActionLabel);
propertiesPanel->add(empiOnCollisionAction);
propertiesPanel->add(empiPierceResetTimeLabel);
propertiesPanel->add(empiPierceResetTime);
propertiesPanel->add(empiSoundSettingsLabel);
propertiesPanel->add(empiSoundSettings);
propertiesPanel->add(empiBulletModelLabel);
propertiesPanel->add(empiBulletModel);
propertiesPanel->add(empiInheritRadius);
propertiesPanel->add(empiInheritDespawnTime);
propertiesPanel->add(empiInheritShadowTrailInterval);
propertiesPanel->add(empiInheritShadowTrailLifespan);
propertiesPanel->add(empiInheritAnimatables);
propertiesPanel->add(empiInheritDamage);
propertiesPanel->add(empiInheritPierceResetTime);
propertiesPanel->add(empiInheritSoundSettings);
propertiesPanel->onSizeChange.connect([this](sf::Vector2f newSize) {
// This is here because of some random bug with SoundSettingsGroup
empiSoundSettings->setSize(newSize.x - GUI_PADDING_X * 2, 0);
spawnTypePositionMarkerPlacerFinishEditing->setPosition(newSize.x - spawnTypePositionMarkerPlacerFinishEditing->getSize().x, newSize.y - spawnTypePositionMarkerPlacerFinishEditing->getSize().y * 2);
});
tabs->addTab(PROPERTIES_TAB_NAME, propertiesPanel);
}
{
// Movement tab
movementEditorPanel = EMPABasedMovementEditorPanel::create(mainEditorWindow, clipboard);
movementEditorPanel->onEMPAListModify.connect([this](std::vector<std::shared_ptr<EMPAction>> newActions, float newSumOfDurations) {
// This shouldn't be undoable here because it's already undoable from EMPABasedMovementEditorPanel.
// Note: Setting the limits of a SliderWithEditBox to some number and then setting it back does not
// revert the SliderWithEditBox's value
this->emp->setActions(newActions);
// Max time for despawn time is sum of actions' durations
this->empiDespawnTime->setMax(newSumOfDurations);
onEMPModify.emit(this, this->emp);
});
movementEditorPanel->setActions(this->emp->getActions());
empiDespawnTime->setMax(movementEditorPanel->getSumOfDurations());
tabs->addTab(MOVEMENT_TAB_NAME, movementEditorPanel, false, false);
}
symbolTableEditorWindow = ChildWindow::create();
symbolTableEditor = ValueSymbolTableEditor::create(false, false);
symbolTableEditorWindow->setKeepInParent(false);
symbolTableEditorWindow->add(symbolTableEditor);
symbolTableEditorWindow->setSize("50%", "50%");
symbolTableEditorWindow->setTitle("Movable Point ID " + std::to_string(emp->getID()) + " Variables");
symbolTableEditorWindow->setFallbackEventHandler([this](sf::Event event) {
return symbolTableEditor->handleEvent(event);
});
symbolTableEditor->onValueChange.connect([this](ValueSymbolTable table) {
this->emp->setSymbolTable(table);
onChange(table);
onEMPModify.emit(this, this->emp);
});
}
EditorMovablePointPanel::~EditorMovablePointPanel() {
levelPack->getOnChange()->sink().disconnect<EditorMovablePointPanel, &EditorMovablePointPanel::onLevelPackChange>(this);
mainEditorWindow.removeChildWindow(symbolTableEditorWindow);
}
CopyOperationResult EditorMovablePointPanel::copyFrom() {
// Can't copy this widget
return CopyOperationResult(nullptr, "");
}
PasteOperationResult EditorMovablePointPanel::pasteInto(std::shared_ptr<CopiedObject> pastedObject) {
// Same functionality as paste2Into()
return paste2Into(pastedObject);
}
PasteOperationResult EditorMovablePointPanel::paste2Into(std::shared_ptr<CopiedObject> pastedObject) {
// Paste the first copied EditorMovablePoint to override emp's properties
auto derived = std::static_pointer_cast<CopiedEditorMovablePoint>(pastedObject);
if (derived) {
std::shared_ptr<EditorMovablePoint> copiedEMP = derived->getEMP();
mainEditorWindow.promptConfirmation("Overwrite this movable point's properties with the copied movable point's properties? This will not change this movable point's children.", copiedEMP, this)->sink()
.connect<EditorMovablePointPanel, &EditorMovablePointPanel::onPasteIntoConfirmation>(this);
return PasteOperationResult(true, "");
}
return PasteOperationResult(false, "Type mismatch");
}
bool EditorMovablePointPanel::handleEvent(sf::Event event) {
if (tabs->handleEvent(event)) {
return true;
} else if (placingSpawnLocation) {
if (spawnTypePositionMarkerPlacer->handleEvent(event)) {
return true;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
finishEditingSpawnTypePosition();
return true;
}
} else if (event.type == sf::Event::KeyPressed) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl) || sf::Keyboard::isKeyPressed(sf::Keyboard::RControl)) {
if (event.key.code == sf::Keyboard::Z) {
undoStack.undo();
return true;
} else if (event.key.code == sf::Keyboard::Y) {
undoStack.redo();
return true;
} else if (event.key.code == sf::Keyboard::V) {
clipboard.paste(this);
return true;
}
} else if (event.key.code == sf::Keyboard::V) {
mainEditorWindow.addChildWindow(symbolTableEditorWindow);
return true;
}
}
return false;
}
tgui::Signal & EditorMovablePointPanel::getSignal(tgui::String signalName) {
if (signalName == onEMPModify.getName().toLower()) {
return onEMPModify;
}
return tgui::Panel::getSignal(signalName);
}
void EditorMovablePointPanel::propagateChangesToChildren() {
symbolTableEditor->setSymbolTablesHierarchy(symbolTables);
// movementEditorPanel acts as just a middleman between this widget and child widgets that
// use emp's ValueSymbolTable
movementEditorPanel->propagateChangesToChildren();
}
ValueSymbolTable EditorMovablePointPanel::getLevelPackObjectSymbolTable() {
return emp->getSymbolTable();
}
void EditorMovablePointPanel::updateAllWidgetValues() {
// Update widgets whose values can be changed by the player
ignoreSignals = true;
empiAnimatable->setValue(emp->getAnimatable());
empiLoopAnimation->setChecked(emp->getLoopAnimation());
empiBaseSprite->setValue(emp->getAnimatable());
isBullet->setChecked(emp->getIsBullet());
empiHitboxRadius->setText(emp->getRawHitboxRadius());
empiDespawnTime->setValue(emp->getDespawnTime());
empiSpawnType->setSelectedItemById(getID(emp->getSpawnType()));
// empiSpawnTypeTime should always display 0 if the EMP is the main EMP of its EditorAttack
// because it will always be spawned instantly
empiSpawnTypeTime->setText(emp->isMainEMP() ? "0" : emp->getSpawnType()->getRawTime());
empiSpawnTypeX->setText(emp->getSpawnType()->getRawX());
empiSpawnTypeY->setText(emp->getSpawnType()->getRawY());
empiShadowTrailLifespan->setText(emp->getRawShadowTrailLifespan());
empiShadowTrailInterval->setText(emp->getRawShadowTrailInterval());
empiDamage->setText(emp->getRawDamage());
empiOnCollisionAction->setSelectedItemById(getID(emp->getOnCollisionAction()));
empiPierceResetTime->setText(emp->getRawPierceResetTime());
empiSoundSettings->initSettings(emp->getSoundSettings());
if (emp->getBulletModelID() >= 0) {
empiBulletModel->setSelectedItemById(std::to_string(emp->getBulletModelID()));
} else {
empiBulletModel->setSelectedItemById("");
}
empiInheritRadius->setChecked(emp->getInheritRadius());
empiInheritDespawnTime->setChecked(emp->getInheritDespawnTime());
empiInheritShadowTrailInterval->setChecked(emp->getInheritShadowTrailInterval());
empiInheritShadowTrailLifespan->setChecked(emp->getInheritShadowTrailLifespan());
empiInheritAnimatables->setChecked(emp->getInheritAnimatables());
empiInheritDamage->setChecked(emp->getInheritDamage());
empiInheritPierceResetTime->setChecked(emp->getInheritPierceResetTime());
empiInheritSoundSettings->setChecked(emp->getInheritSoundSettings());
empiSpawnTypeTime->setEnabled(!emp->isMainEMP());
empiOnCollisionAction->setEnabled(emp->getIsBullet());
empiHitboxRadius->setEnabled((!emp->getInheritRadius() || this->emp->getBulletModelID() < 0) && emp->getIsBullet());
empiDespawnTime->setEnabled(!emp->getInheritDespawnTime() || this->emp->getBulletModelID() < 0);
empiShadowTrailInterval->setEnabled(!emp->getInheritShadowTrailInterval() || this->emp->getBulletModelID() < 0);
empiShadowTrailLifespan->setEnabled(!emp->getInheritShadowTrailLifespan() || this->emp->getBulletModelID() < 0);
empiAnimatable->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiBaseSprite->setEnabled(!this->emp->getInheritAnimatables() || this->emp->getBulletModelID() < 0);
empiDamage->setEnabled((!emp->getInheritDamage() || this->emp->getBulletModelID() < 0) && emp->getIsBullet());
empiPierceResetTime->setEnabled((!emp->getInheritPierceResetTime() || this->emp->getBulletModelID() < 0) && emp->getIsBullet());
empiSoundSettings->setEnabled(!emp->getInheritSoundSettings() || this->emp->getBulletModelID() < 0);
empiLoopAnimation->setVisible(!emp->getAnimatable().isSprite());
empiBaseSprite->setVisible(!emp->getLoopAnimation() && !emp->getAnimatable().isSprite());
empiBaseSpriteLabel->setVisible(empiBaseSprite->isVisible());
empiPierceResetTimeLabel->setVisible((emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && emp->getIsBullet());
empiPierceResetTime->setVisible((emp->getOnCollisionAction() == BULLET_ON_COLLISION_ACTION::PIERCE_ENTITY) && emp->getIsBullet());
ignoreSignals = false;
}
void EditorMovablePointPanel::onLevelPackChange(LevelPack::LEVEL_PACK_OBJECT_HIERARCHY_LAYER_ROOT_TYPE type, int id) {
if (type == LevelPack::LEVEL_PACK_OBJECT_HIERARCHY_LAYER_ROOT_TYPE::SPRITE_SHEET) {
// Reload animatables-related widgets
empiAnimatable->repopulateAnimatables();
empiBaseSprite->repopulateAnimatables();
} else if (type == LevelPack::LEVEL_PACK_OBJECT_HIERARCHY_LAYER_ROOT_TYPE::BULLET_MODEL) {
// Reload bullet model-related widgets when some bullet model is modified
if (emp->getBulletModelID() == id) {
emp->loadBulletModel(*levelPack);
}
empiBulletModel->removeAllItems();
empiBulletModel->addItem("None", "-1");
for (auto it = levelPack->getBulletModelIteratorBegin(); it != levelPack->getBulletModelIteratorEnd(); it++) {
empiBulletModel->addItem(it->second->getName(), std::to_string(it->second->getID()));
}
}
// TODO: when sounds folder is modified, empiSoundSettings->populateFileNames(format(RELATIVE_LEVEL_PACK_SOUND_FOLDER_PATH, levelPack->getName().c_str()));
}
void EditorMovablePointPanel::finishEditingSpawnTypePosition() {
propertiesPanel->removeAllWidgets();
for (auto widget : savedWidgets) {
propertiesPanel->add(widget);
}
savedWidgets.clear();
propertiesPanel->setHorizontalScrollbarValue(horizontalScrollPos);
propertiesPanel->setVerticalScrollbarValue(verticalScrollPos);
std::string oldPosX = emp->getSpawnType()->getRawX();
std::string oldPosY = emp->getSpawnType()->getRawY();
sf::Vector2f newPos = spawnTypePositionMarkerPlacer->getMarkerPositions()[0];
undoStack.execute(UndoableCommand(
[this, newPos]() {
emp->getSpawnType()->setX(formatNum(newPos.x));
emp->getSpawnType()->setY(formatNum(newPos.y));
onEMPModify.emit(this, this->emp);
this->ignoreSignals = true;
empiSpawnTypeX->setText(formatNum(newPos.x));
empiSpawnTypeY->setText(formatNum(newPos.y));
this->ignoreSignals = false;
},
[this, oldPosX, oldPosY]() {
emp->getSpawnType()->setX(oldPosX);
emp->getSpawnType()->setY(oldPosY);
onEMPModify.emit(this, this->emp);
this->ignoreSignals = true;
empiSpawnTypeX->setText(oldPosX);
empiSpawnTypeY->setText(oldPosY);
this->ignoreSignals = false;
}));
placingSpawnLocation = false;
}
void EditorMovablePointPanel::onPasteIntoConfirmation(EDITOR_WINDOW_CONFIRMATION_PROMPT_CHOICE choice, std::shared_ptr<EditorMovablePoint> newEMP) {
if (choice == EDITOR_WINDOW_CONFIRMATION_PROMPT_CHOICE::YES) {
auto oldAnimatable = emp->getAnimatable();
auto oldLoopAnimation = emp->getLoopAnimation();
auto oldBaseSprite = emp->getBaseSprite();
auto oldIsBullet = emp->getIsBullet();
auto oldHitboxRadius = emp->getRawHitboxRadius();
auto oldDespawnTime = emp->getDespawnTime();
auto oldSpawnType = emp->getSpawnType();
auto oldShadowTrailLifespan = emp->getRawShadowTrailLifespan();
auto oldShadowTrailInterval = emp->getRawShadowTrailInterval();
auto oldDamage = emp->getRawDamage();
auto oldOnCollisionAction = emp->getOnCollisionAction();
auto oldPierceResetTime = emp->getRawPierceResetTime();
auto oldActions = emp->getActions();
auto oldBulletModelID = emp->getBulletModelID();
auto oldInheritRadius = emp->getInheritRadius();
auto oldInheritDespawnTime = emp->getInheritDespawnTime();
auto oldInheritShadowTrailInterval = emp->getInheritShadowTrailInterval();
auto oldInheritShadowTrailLifespan = emp->getInheritShadowTrailLifespan();
auto oldInheritAnimatables = emp->getInheritAnimatables();
auto oldInheritDamage = emp->getInheritDamage();
auto oldInheritSoundSettings = emp->getInheritSoundSettings();
undoStack.execute(UndoableCommand([this, newEMP]() {
emp->setAnimatable(newEMP->getAnimatable());
emp->setLoopAnimation(newEMP->getLoopAnimation());
emp->setBaseSprite(newEMP->getBaseSprite());
emp->setIsBullet(newEMP->getIsBullet());
emp->setHitboxRadius(newEMP->getRawHitboxRadius());
emp->setDespawnTime(newEMP->getDespawnTime());
emp->setSpawnType(newEMP->getSpawnType());
emp->setShadowTrailLifespan(newEMP->getRawShadowTrailLifespan());
emp->setShadowTrailInterval(newEMP->getRawShadowTrailInterval());
emp->setDamage(newEMP->getRawDamage());
emp->setOnCollisionAction(newEMP->getOnCollisionAction());
emp->setPierceResetTime(newEMP->getRawPierceResetTime());
if (newEMP->getBulletModelID() == -1) {
emp->removeBulletModel();
} else {
emp->setBulletModel(this->levelPack->getBulletModel(newEMP->getBulletModelID()));
}
emp->setActions(newEMP->getActions());
emp->setInheritRadius(newEMP->getInheritRadius(), *levelPack);
emp->setInheritDespawnTime(newEMP->getInheritDespawnTime(), *levelPack);
emp->setInheritShadowTrailInterval(newEMP->getInheritShadowTrailInterval(), *levelPack);
emp->setInheritShadowTrailLifespan(newEMP->getInheritShadowTrailLifespan(), *levelPack);
emp->setInheritAnimatables(newEMP->getInheritAnimatables(), *levelPack);
emp->setInheritDamage(newEMP->getInheritDamage(), *levelPack);
emp->setInheritSoundSettings(newEMP->getInheritSoundSettings(), *levelPack);
updateAllWidgetValues();
onEMPModify.emit(this, this->emp);
}, [this, oldAnimatable, oldLoopAnimation, oldBaseSprite, oldIsBullet, oldHitboxRadius, oldDespawnTime, oldSpawnType,
oldShadowTrailLifespan, oldShadowTrailInterval, oldDamage, oldOnCollisionAction, oldPierceResetTime, oldBulletModelID, oldActions,
oldInheritRadius, oldInheritDespawnTime, oldInheritShadowTrailInterval, oldInheritShadowTrailLifespan, oldInheritAnimatables,
oldInheritDamage, oldInheritSoundSettings]() {
emp->setAnimatable(oldAnimatable);
emp->setLoopAnimation(oldLoopAnimation);
emp->setBaseSprite(oldBaseSprite);
emp->setIsBullet(oldIsBullet);
emp->setHitboxRadius(oldHitboxRadius);
emp->setDespawnTime(oldDespawnTime);
emp->setSpawnType(oldSpawnType);
emp->setShadowTrailLifespan(oldShadowTrailLifespan);
emp->setShadowTrailInterval(oldShadowTrailInterval);
emp->setDamage(oldDamage);
emp->setOnCollisionAction(oldOnCollisionAction);
emp->setPierceResetTime(oldPierceResetTime);
if (oldBulletModelID == -1) {
emp->removeBulletModel();
} else {
emp->setBulletModel(this->levelPack->getBulletModel(oldBulletModelID));
}
emp->setActions(oldActions);
emp->setInheritRadius(oldInheritRadius, *levelPack);
emp->setInheritDespawnTime(oldInheritDespawnTime, *levelPack);
emp->setInheritShadowTrailInterval(oldInheritShadowTrailInterval, *levelPack);
emp->setInheritShadowTrailLifespan(oldInheritShadowTrailLifespan, *levelPack);
emp->setInheritAnimatables(oldInheritAnimatables, *levelPack);
emp->setInheritDamage(oldInheritDamage, *levelPack);
emp->setInheritSoundSettings(oldInheritSoundSettings, *levelPack);
updateAllWidgetValues();
onEMPModify.emit(this, this->emp);
}));
}
}
| [
"treecam42@gmail.com"
] | treecam42@gmail.com |
011193a50bfddee09b20f199e5a5035ff28b4e8b | 6fa8376cc78f1586b7df3b4e3037daeab4828e3f | /test/TestCore/TestDifferentiability.cpp | ecc8c5b0cecd804285b014a5a538e44ce4b3877f | [
"MIT"
] | permissive | alexweav/BackpropFramework | 99db0feb870698436d3cd1c7f06a6a2f60de46fe | 2de396628180db1e6535037663497f9814e83039 | refs/heads/master | 2021-01-01T17:38:53.431150 | 2018-06-04T00:53:57 | 2018-06-04T00:53:57 | 98,120,105 | 1 | 0 | MIT | 2018-06-04T00:53:58 | 2017-07-23T19:21:50 | C++ | UTF-8 | C++ | false | false | 981 | cpp | #include "TestCore.h"
TEST_F(DifferentiabilityTest, LeafNodesHaveDifferentiableTree) {
EXPECT_TRUE(cons1->HasDifferentiableTree());
EXPECT_TRUE(cons2->HasDifferentiableTree());
}
TEST_F(DifferentiabilityTest, ConstantChannelDifferentiable) {
EXPECT_TRUE(cons1->Channels(0).IsDifferentiableFunctor());
EXPECT_TRUE(cons2->Channels(0).IsDifferentiableFunctor());
}
TEST_F(DifferentiabilityTest, NonDifferentiableNodeNotDifferentiable) {
EXPECT_TRUE(nonDiffCons1->HasDifferentiableTree());
EXPECT_FALSE(nonDiffCons1->Channels(0).IsDifferentiableFunctor());
}
TEST_F(DifferentiabilityTest, TestDifferentiableTreeFunction) {
EXPECT_TRUE(addDiff->HasDifferentiableTree());
EXPECT_TRUE(addDiff->Channels(0).IsDifferentiableFunctor());
}
TEST_F(DifferentiabilityTest, TestNonDifferentiableTreeFunction) {
EXPECT_FALSE(addNonDiffComposition->HasDifferentiableTree());
EXPECT_TRUE(addNonDiffComposition->Channels(0).IsDifferentiableFunctor());
}
| [
"alexander.weaver@ttu.edu"
] | alexander.weaver@ttu.edu |
5ca95d7382764e50294cb4ae92a8aa804a1289e4 | fd7416b2cecddc2b5d531c399f2265fa57d6ab4b | /libraries/trainers/optimization/tcc/MatrixSolution.tcc | c99d0e4d356bac23c925964af7fa659c580f4b58 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | yaokeepmoving/ELL | 0bb45c04eab0773e09eee8504ea2e36baa291ee6 | 993d5370f0f7a274e8dfd8f43220c792be46f314 | refs/heads/master | 2020-04-04T14:31:37.444718 | 2018-10-25T19:03:36 | 2018-10-25T19:03:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,532 | tcc | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: MatrixSolution.tcc (optimization)
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
// utilities
#include "Exception.h"
// math
#include "VectorOperations.h"
#include "MatrixOperations.h"
namespace ell
{
namespace trainers
{
namespace optimization
{
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::Resize(const InputType& inputExample, const OutputType& outputExample)
{
math::ColumnMatrix<double> matrix(inputExample.Size(), outputExample.Size());
_weights.Swap(matrix);
if constexpr (!isDouble)
{
_doubleInput.Resize(inputExample.Size());
}
if constexpr (isBiased)
{
_bias.Resize(outputExample.Size());
}
}
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::operator=(const MatrixSolution<IOElementType, isBiased>& other)
{
_weights.CopyFrom(other._weights);
if constexpr (isBiased)
{
_bias.CopyFrom(other._bias);
}
}
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::operator=(SumExpression<ScaledExpression<MatrixSolution<IOElementType, isBiased>>, ScaledExpression<MatrixSolution<IOElementType, isBiased>>> expression)
{
const auto& thisTerm = expression.lhs;
const auto& otherTerm = expression.rhs;
if (&(thisTerm.lhs.get()) != this)
{
throw utilities::LogicException(utilities::LogicExceptionErrors::notImplemented, "First term should be a scaled version of this solution");
}
double thisScale = thisTerm.rhs;
const auto& otherSolution = otherTerm.lhs.get();
double otherScale = otherTerm.rhs;
math::ScaleAddUpdate(otherScale, otherSolution._weights, thisScale, _weights);
if constexpr (isBiased)
{
math::ScaleAddUpdate(otherScale, otherSolution.GetBias(), thisScale, _bias);
}
}
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::operator=(SumExpression<ScaledExpression<MatrixSolution<IOElementType, isBiased>>, OuterProductExpression<IOElementType>> expression)
{
const auto& thisTerm = expression.lhs;
const auto& updateTerm = expression.rhs;
if (&(thisTerm.lhs.get()) != this)
{
throw utilities::LogicException(utilities::LogicExceptionErrors::notImplemented, "The first term should be a scaled version of this solution");
}
double thisScale = thisTerm.rhs;
const auto& columnVectorReference = updateTerm.lhs;
const auto& rowVectorReference = updateTerm.rhs;
_weights *= thisScale;
if constexpr (isDouble)
{
math::RankOneUpdate(1.0, columnVectorReference, rowVectorReference, _weights);
}
else
{
auto doubleColumnVector = _doubleInput.Transpose();
doubleColumnVector.CopyFrom(columnVectorReference);
math::RankOneUpdate(1.0, doubleColumnVector, rowVectorReference, _weights);
}
if constexpr (isBiased)
{
math::ScaleAddUpdate(1.0, rowVectorReference, thisScale, _bias);
}
}
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::operator+=(OuterProductExpression<IOElementType> expression)
{
const auto& columnVectorReference = expression.lhs;
const auto& rowVectorReference = expression.rhs;
if constexpr (isDouble)
{
math::RankOneUpdate(1.0, columnVectorReference, rowVectorReference, _weights);
}
else
{
auto doubleColumnVector = _doubleInput.Transpose();
doubleColumnVector.CopyFrom(columnVectorReference);
math::RankOneUpdate(1.0, doubleColumnVector, rowVectorReference, _weights);
}
if constexpr (isBiased)
{
math::ScaleAddUpdate(1.0, rowVectorReference, 1.0, _bias);
}
}
template <typename IOElementType, bool isBiased>
math::RowVector<double> MatrixSolution<IOElementType, isBiased>::Multiply(const InputType& input) const
{
math::RowVector<double> result(_weights.NumColumns());
if constexpr (isBiased)
{
result.CopyFrom(_bias);
}
if constexpr (isDouble)
{
math::MultiplyScaleAddUpdate(1.0, input, _weights, 1.0, result);
}
else
{
_doubleInput.CopyFrom(input);
math::MultiplyScaleAddUpdate(1.0, _doubleInput, _weights, 1.0, result);
}
return result;
}
template <typename IOElementType, bool isBiased>
double MatrixSolution<IOElementType, isBiased>::GetNorm2SquaredOf(const InputType& input)
{
double result = input.Norm2Squared();
if constexpr (isBiased)
{
result += 1.0;
}
return result;
}
template <typename IOElementType, bool isBiased>
void MatrixSolution<IOElementType, isBiased>::InitializeAuxiliaryVariable(AuxiliaryDoubleType& aux)
{
aux.Resize(_weights.NumColumns()); aux.Reset();
}
template <typename IOElementType, bool isBiased>
double Norm1(const MatrixSolution<IOElementType, isBiased>& solution)
{
double result = solution.GetMatrix().ReferenceAsVector().Norm1();
if constexpr (isBiased)
{
result += solution.GetBias().Norm1();
}
return result;
}
template <typename IOElementType, bool isBiased>
double Norm2Squared(const MatrixSolution<IOElementType, isBiased>& solution)
{
double result = solution.GetMatrix().ReferenceAsVector().Norm2Squared();
if constexpr (isBiased)
{
result += solution.GetBias().Norm2Squared();
}
return result;
}
template <typename IOElementType, bool isBiased>
math::RowVector<double> operator*(math::ConstRowVectorReference<IOElementType> input, const MatrixSolution<IOElementType, isBiased>& solution)
{
return solution.Multiply(input);
}
}
}
}
| [
"oferd@microsoft.com"
] | oferd@microsoft.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.