text
stringlengths 8
6.88M
|
|---|
#include "data_associate_known.h" // import file to test
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include "ut.hpp"
using namespace boost::ut;
using namespace boost::ut::bdd;
int main() {
"data_associate_known"_test = [] {
given("I have some arguments") = [] {
cVector2d z[2] = {{25.783699379426974, -1.4642259491817695},
{25.286434348683521, 0.14502450890426782}};
const int idz[2] = {0, 21};
Vector2d zf[35]; // will be modified in func
Vector2d zn[35]; // will be modified in func
int idf[35] = {}; // will be modified in func
size_t count_zf = 0;
size_t count_zn = 0;
int table[35]; // initilize here, will be modified in func
for (size_t i = 0; i < 35; i++) {
table[i] = -1;
}
when("I call data_associate_known()") = [&] {
int table_target[35];
for (size_t i = 0; i < 35; i++) {
table_target[i] = -1;
}
table_target[0] = 0;
table_target[21] = 1;
const Vector2d zn_target[2] = {25.783699379426974, -1.4642259491817695,
25.286434348683521, 0.14502450890426782};
// modifies table, zf, idf, zn and the count_zf, count_zh
data_associate_known(z, idz, 2, table, 0, zf, idf, &count_zf, zn, &count_zn);
then("This is equal with the actual result [table]") = [&] {
for (size_t i = 0; i < 35; i++) {
expect(abs(table[i] - table_target[i]) < 1e-10) << std::setprecision(12) << table[i] << " != " << table_target[i];
}
};
// zn needs to be allocated inside data_associate_known()
then("This is equal with the actual result [zn]") = [&] {
for (size_t i = 0; i < 2; i++) {
double zni0 = zn[i][0];
double zni1 = zn[i][1];
double zn_target_i0 = zn[i][0];
double zn_target_i1 = zn[i][1];
expect(fabs(zni0 - zn_target_i0) < 1e-10) << std::setprecision(12) << zni0 << " != " << zn_target_i0;
expect(fabs(zni1 - zn_target_i1) < 1e-10) << std::setprecision(12) << zni1 << " != " << zn_target_i1;
}
};
// zf, idf still NULL in this case
};
};
};
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int test,i;
double p1,p2,r,cal;
while(scanf("%d",&test)==1)
{
for(i=1; i<=test; i++)
{
scanf("%lf %lf %lf",&p1,&p2,&r);
cal=sqrt(pow(p1,2)+pow(p2,2));
printf("%0.2lf %0.2lf\n",r-cal,r+cal);
}
}
return 0;
}
|
// Alfred Ledgin
// 10/31/2015
// CS 303
// Project 2
#pragma once
#include <iostream>
#include <string>
using namespace std;
class StringToInt
// The purpose of this class is to convert a string of characters representing
// a positive integer to the integer value represented. This will only
// convert strings consisting of the characters '0' through '9'.
{
public:
StringToInt()
{
numString = "";
numInt = 0;
}
// Preconditions: A converter needs to be declared.
// Postconditions: This is the default constructor. It allows
// declaration of an empty converter, with an empty string,
// and the integer value set to 0 by default.
StringToInt(const string& input)
{
numString = input;
try
{
numInt = convert();
}
catch(exception)
{
throw std::exception("String must only contain digits.");
}
}
// Preconditions: A converter needs to be created with a given string.
// Postconditions: This constructor creates a converter with the given
// string and calls convert() to convert it to the integer value.
void input(const string& input)
{
numString = input;
try
{
numInt = convert();
}
catch (exception)
{
throw std::exception("String must only contain digits.");
}
}
// Preconditions: A converter's string needs to be changed.
// Postconditions: This changes a converter's string to the given
// string and calls convert() to convert it to the integer value.
const int obtainInt() const {return numInt;}
// Preconditions: A converter's integer value is needed.
// Postconditions: This function returns the integer value, which has
// already been converted from the input string, or was set to 0
// if no input string was given.
const int obtainInt(const string& input)
{
numString = input;
try
{
numInt = convert();
}
catch (exception)
{
throw std::exception("String must only contain digits.");
}
return numInt;
}
// Preconditions: Single-statement conversion from a string to an
// integer is needed.
// Postconditions: This function takes an input string, converts it,
// and returns the resulting integer.
private:
const int convert() const
{
int result = 0;
for (int counter = numString.length() - 1; counter >= 0; counter--)
// Iterate from the last char through the first.
{
if (isdigit(numString[counter]))
result += ((numString[counter] - 48)
// First convert ASCII char to corresponding int value.
* pow(10, (numString.length() - 1) - counter));
// Then make that value the appropriate digit by
// multiplying it by the appropriate power of 10.
else
throw std::exception("String must only contain digits.");
}
return result;
}
// Preconditions: The converted result of a converter's string is
// needed.
// Postconditions: This function converts the stored string to the
// integer value represented by the string.
// Reference (Inspiration for Algorithm):
// Doutt, Gerald. "Lectures on Subroutines,
// ASCII-Binary Conversion."
// University of Missouri-Kansas City.
// Royall Hall, Kansas City, MO.
// Spring 2015. CS 282 Course Lectures.
string numString;
int numInt;
};
|
//===========================================================================
//! @file primitive.cpp
//! @brief プリミティブ描画
//===========================================================================
namespace {
std::vector<Matrix> matrixStack_;
Matrix matWorld_ = Matrix::identity();
gpu::Buffer* dynamicBuffer_;
std::unique_ptr<gpu::ShaderVs> shaderVs3D_;
std::unique_ptr<gpu::ShaderPs> shaderPsFlat_;
std::unique_ptr<gpu::ShaderPs> shaderPsTexture_;
gpu::ConstantBuffer<cbModel> cbWorld_;
const u32 MAX_VERTEX_COUNT = 65536* 1024; // 最大登録頂点数
const u32 BUFFER_SIZE = u32(sizeof(Vertex)) * MAX_VERTEX_COUNT;
u32 usedCount_ = 0; // 使用中の頂点数
u32 drawCount_; // 頂点個数
Vertex vertex_; // 頂点の一時領域
PRIMITIVE_TYPE type_ = PT_POINTS; // 現在のプリミティブの種類
Vertex* pvertex_; // 現在マップされている頂点の先頭
} // namespace
//---------------------------------------------------------------------------
//! 初期化
//---------------------------------------------------------------------------
bool PRIM_Initialize()
{
// 動的頂点バッファの初期化
dynamicBuffer_ = new gpu::Buffer();
if(dynamicBuffer_->initialize(BUFFER_SIZE, D3D11_USAGE_DYNAMIC, D3D11_BIND_VERTEX_BUFFER) == false) {
return false;
}
return true;
}
//---------------------------------------------------------------------------
//! 解放
//---------------------------------------------------------------------------
void PRIM_Finalize()
{
shaderVs3D_.reset();
shaderPsFlat_.reset();
shaderPsTexture_.reset();
GM_SAFE_DELETE(dynamicBuffer_);
}
//==============================================================
// OpenGL互換関数
//==============================================================
//---------------------------------------------------------------------------
//! 行列の設定
//---------------------------------------------------------------------------
void dxLoadMatrixf(const Matrix& matWorld)
{
auto p = cbWorld_.begin();
p->matWorld_ = matWorld;
cbWorld_.end();
// 内部に退避
matWorld_ = matWorld;
gpu::setConstantBuffer(1, cbWorld_);
}
//---------------------------------------------------------------------------
//! 行列スタックへ退避
//---------------------------------------------------------------------------
void dxPushMatrix()
{
matrixStack_.emplace_back(matWorld_);
}
//---------------------------------------------------------------------------
//! 行列スタックから復帰
//---------------------------------------------------------------------------
void dxPopMatrix()
{
matWorld_ = matrixStack_.back();
matrixStack_.pop_back();
dxLoadMatrixf(matWorld_); // 再設定
}
//---------------------------------------------------------------------------
//! 描画開始
//! @param [in] type プリミティブの種類
//---------------------------------------------------------------------------
void dxBegin(PRIMITIVE_TYPE type)
{
// メモリマップ開始
D3D11_MAP map = D3D11_MAP_WRITE_NO_OVERWRITE;
// 満杯近くなら再確保
if(MAX_VERTEX_COUNT - 65536 * 10 < usedCount_) {
map = D3D11_MAP_WRITE_DISCARD;
usedCount_ = 0; // 最初から利用
}
D3D11_MAPPED_SUBRESOURCE mapped;
device::D3DContext()->Map(dynamicBuffer_->getD3DBuffer(), 0, map, 0, &mapped);
// 利用中の先頭アドレス
pvertex_ = &static_cast<Vertex*>(mapped.pData)[usedCount_];
// 上と同じ
//pvertex_ = static_cast<Vertex*> (mapped.pData);
//++usedCount_;
type_ = type;
}
//---------------------------------------------------------------------------
//! 頂点キック (Kick)
//---------------------------------------------------------------------------
void dxVertex3f(f32 x, f32 y, f32 z)
{
// 値の設定
vertex_.position_.x_ = x;
vertex_.position_.y_ = y;
vertex_.position_.z_ = z;
// 頂点キック
*pvertex_++ = vertex_; // 一時ワークから書き出し
drawCount_++;
}
//---------------------------------------------------------------------------
//! 頂点キック (Kick) Vector3
//---------------------------------------------------------------------------
void dxVertex3fv(const Vector3& pos)
{
dxVertex3f(pos.x_, pos.y_, pos.z_);
}
//---------------------------------------------------------------------------
//! カラーu8
//---------------------------------------------------------------------------
void dxColor4ub(u8 r, u8 g, u8 b, u8 a)
{
vertex_.color_ = Color(r, g, b, a);
}
//------------------------------------------------------
//! カラーu8
//------------------------------------------------------
void dxColor4ub(const Color& color)
{
vertex_.color_ = Color(color.r_, color.g_, color.b_, color.a_);
}
//---------------------------------------------------------------------------
//! カラーf32
//---------------------------------------------------------------------------
void dxColor4f(f32 fr, f32 fg, f32 fb, f32 fa)
{
u8 r = (u8)std::max(0.0f, std::min(fr * 255.5f, 255.5f));
u8 g = (u8)std::max(0.0f, std::min(fg * 255.5f, 255.5f));
u8 b = (u8)std::max(0.0f, std::min(fb * 255.5f, 255.5f));
u8 a = (u8)std::max(0.0f, std::min(fa * 255.5f, 255.5f));
vertex_.color_ = Color(r, g, b, a);
}
//---------------------------------------------------------------------------
//! カラーf32
//---------------------------------------------------------------------------
void dxColor4f(const Vector4& color)
{
u8 r = (u8)std::max(0.0f, std::min(color.r_ * 255.5f, 255.5f));
u8 g = (u8)std::max(0.0f, std::min(color.g_ * 255.5f, 255.5f));
u8 b = (u8)std::max(0.0f, std::min(color.b_ * 255.5f, 255.5f));
u8 a = (u8)std::max(0.0f, std::min(color.a_ * 255.5f, 255.5f));
vertex_.color_ = Color(r, g, b, a);
}
//---------------------------------------------------------------------------
//! テクスチャ座標
//---------------------------------------------------------------------------
void dxTexCoord2f(f32 u, f32 v)
{
vertex_.uv_.x_ = u;
vertex_.uv_.y_ = v;
}
//---------------------------------------------------------------------------
//! 法線
//---------------------------------------------------------------------------
void dxNormal3fv(const Vector3& v)
{
// 値の設定
vertex_.normal_.x_ = v.x_;
vertex_.normal_.y_ = v.y_;
vertex_.normal_.z_ = v.z_;
}
//---------------------------------------------------------------------------
//! 描画終了
//---------------------------------------------------------------------------
void dxEnd()
{
// メモリマッピング終了
device::D3DContext()->Unmap(dynamicBuffer_->getD3DBuffer(), 0);
// 描画
gpu::setVertexBuffer(dynamicBuffer_, sizeof(Vertex)); // 頂点バッファ
// 描画
gpu::draw(type_, drawCount_, usedCount_);
usedCount_ += drawCount_;
drawCount_ = 0;
}
//---------------------------------------------------------------------------
//! テクスチャの設定
//---------------------------------------------------------------------------
void dxTexture(ptr<gpu::Texture> texture)
{
auto shaderVs = ShaderManager::getShaderVs("vsStandard");
auto shaderPs = ShaderManager::getShaderPs("psStandard");
auto shaderPsTex = ShaderManager::getShaderPs("psTexture3D");
gpu::setShader(shaderVs, (texture) ? shaderPsTex : shaderPs);
gpu::setTexture(0, texture);
}
|
#define _CRT_RAND_S
#include <iostream>
#include <Windows.h>
#include <string>
#include <thread>
#include <chrono>
#include <random>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <Wincrypt.h>
#include "Console.h"
#include "Hash.h"
#include "Rand.h"
#include "xxhash.h"
#define NUMBER_OF_THREADS 1
#define BIT_LENGTH 32
#define BYTE_LENGTH BIT_LENGTH / 8
#define TABLE_SIZE 65536 // 2 ^ (BIT_LENGTH / 2)
#define BIT_LENGTH_64 64
#define BYTE_LENGTH_64 BIT_LENGTH / 8
#define TABLE_SIZE_24 16777216 // 2 ^ 22
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
struct threads {
bool collision;
thread::id thread_id;
};
threads T[NUMBER_OF_THREADS] = { false };
int _thread_id = 0;
int _thread_id_unique = 0;
bool found = false;
uint32_t _count = 0;
int _collision_count = 0;
bool one_second = true;
// вывести кол-во посчитанных хэшей
void showCount() {
printf("\r %d", _count);
}
void showCount(string v1, int v2) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { 0, 7 });
printf("\r %s: %d", v1, v2);
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { 0, 6 });
}
// атака дней рождений
void birthdayAttack64(bool &found) {
bool _found = false;
uint32_t tab1[TABLE_SIZE_24];
uint32_t tab2[TABLE_SIZE_24];
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[BYTE_LENGTH_64] = {};
mt19937 gen;
uint64_t seed = 0;
CryptGenRandom(hProvider, BYTE_LENGTH_64, pbData);
for (int i = 0; i < 8; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint64_t temp;
string buf;
do {
// генерация таблиц
for (int i = 0; i < TABLE_SIZE_24; i++) {
temp = gen();
buf = "";
for (int i = 0; i < BYTE_LENGTH_64; i++) {
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp << 16 >> 24) & 0xFF);
buf += (char)((temp << 8 >> 24) & 0xFF);
buf += (char)((temp >> 24) & 0xFF);
}
//tab1[i] = Crc32((u_char *)buf.c_str(), 32);
tab1[i] = XXH64((u_char *)buf.c_str(), 32, 0);
temp = gen();
buf = "";
for (int i = 0; i < BYTE_LENGTH_64; i++) {
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp << 16 >> 24) & 0xFF);
buf += (char)((temp << 8 >> 24) & 0xFF);
buf += (char)((temp >> 24) & 0xFF);
}
//tab2[i] = Crc32((u_char *)buf.c_str(), 32);
tab1[i] = XXH64((u_char *)buf.c_str(), 32, 0);
}
thread::id this_id = std::this_thread::get_id();
T[_thread_id_unique++].thread_id = this_id;
for (int i = 0; i < TABLE_SIZE_24; i++) {
if (found)
return;
;
_count++;
//showCount();
printf("\r %i", _count);
for (int j = 0; j < TABLE_SIZE_24; j++) {
if (tab1[i] == tab2[j]) {
found = true;
_collision_count++;
showCount(" collisions found: ", _collision_count);
T[_thread_id].collision = true;
T[_thread_id].thread_id = this_id;
++_thread_id;
/*cout << "\n\r collision found. " << tab1[i] << " = " << tab2[j];
cout << " in thread #" << T[_thread_id].thread_id << "\n";
*/
}
}
}
} while (!found);
}
void birthdayAttack32(bool &found) {
bool _found = false;
uint32_t tab1[TABLE_SIZE];
uint32_t tab2[TABLE_SIZE];
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[BYTE_LENGTH] = {};
mt19937 gen;
uint32_t seed = 0;
CryptGenRandom(hProvider, BYTE_LENGTH, pbData);
for (int i = 0; i < BYTE_LENGTH; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint32_t temp;
string buf;
// генерация таблиц
for (int i = 0; i < TABLE_SIZE; i++) {
buf = "";
for (int i = 0; i < BYTE_LENGTH; i++) {
temp = gen();
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp << 16 >> 24) & 0xFF);
buf += (char)((temp << 8 >> 24) & 0xFF);
buf += (char)((temp >> 24) & 0xFF);
}
tab1[i] = Crc32((u_char *)buf.c_str(), 32);
buf = "";
for (int i = 0; i < BYTE_LENGTH; i++) {
temp = gen();
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp << 16 >> 24) & 0xFF);
buf += (char)((temp << 8 >> 24) & 0xFF);
buf += (char)((temp >> 24) & 0xFF);
}
tab2[i] = Crc32((u_char *)buf.c_str(), 32);
}
thread::id this_id = std::this_thread::get_id();
T[_thread_id_unique++].thread_id = this_id;
for (int i = 0; i < TABLE_SIZE; i++) {
if (found)
return;
;
_count++;
//showCount();
printf("\r %i", _count);
for (int j = 0; j < TABLE_SIZE; j++) {
if (tab1[i] == tab2[j]) {
found = true;
_collision_count++;
showCount(" collisions found: ", _collision_count);
T[_thread_id].collision = true;
T[_thread_id].thread_id = this_id;
++_thread_id;
/*cout << "\n\r collision found. " << tab1[i] << " = " << tab2[j];
cout << " in thread #" << T[_thread_id].thread_id << "\n";
*/
}
}
}
}
void birthdayAttack16(bool &found) {
bool _found = false;
uint16_t tab1[256];
uint16_t tab2[256];
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[16] = {};
mt19937 gen;
uint16_t seed = 0;
CryptGenRandom(hProvider, 2, pbData);
for (int i = 0; i < 2; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint16_t temp;
string buf;
int _thread_id = 0;
// генерация таблиц
for (int i = 0; i < 256; i++) {
temp = (uint16_t)gen();
buf = "";
for (int i = 0; i < 2; i++) {
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp >> 8) & 0xFF);
}
tab1[i] = Crc16((u_char *)buf.c_str(), 16);
temp = (uint16_t)gen();
buf = "";
for (int i = 0; i < 2; i++) {
buf += (char)((temp << 24 >> 24) & 0xFF);
buf += (char)((temp >> 8) & 0xFF);
}
tab2[i] = Crc16((u_char *)buf.c_str(), 16);
}
for (int i = 0; i < 256; i++) {
if (found)
break;
_count++;
showCount();
for (int j = 0; j < 256; j++) {
if (tab1[i] == tab2[j]) {
Sleep(1);
found = true;
thread::id this_id = std::this_thread::get_id();
if (T[_thread_id].collision)
++_thread_id;
T[_thread_id].collision = true;
T[_thread_id].thread_id = this_id;
/*cout << "\n\r collision found. " << tab1[i] << " = " << tab2[j];
cout << " in thread #" << T[_thread_id].thread_id << "\n";
*/
}
}
}
}
// атака брутфорсом
void bruteforce64(bool &found, string v, uint64_t main) {
srand(time(NULL));
/*random_device r;
default_random_engine e1(r());*/
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[32] = {};
//cout << endl << " current hash: ";
//cout << hex << main;
//mt19937_64 gen(rd());
//fast_srand(seed);
mt19937_64 gen;
uint64_t seed = 0;
CryptGenRandom(hProvider, BYTE_LENGTH, pbData);
for (int i = 0; i < BYTE_LENGTH; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint64_t n;
unsigned long long hexx;
string s;
//for (int i = 0; i < 1000000; i++) {
do {
printf("\r %d", _count);
for (int cycle = 0; cycle < 50000; cycle++) {
s = "";
n = gen();
u_char* ch = new u_char();
memcpy(ch, (char*)&n, 4);
/*for (int i = 0; i < 4; i++) {
s += (char)((n << 24 >> 24) & 0xFF);
s += (char)((n << 16 >> 24) & 0xFF);
s += (char)((n << 8 >> 24) & 0xFF);
s += (char)((n >> 24) & 0xFF);
}*/
//hexx = XXH32((u_char *)s.c_str(), 16, 0);
hexx = XXH64((u_char *)s.c_str(), 32, 0);
//hexx = Crc32((u_char *)bytes, 32);
hexx = Crc32((u_char *)s.c_str(), 16);
_count++;
//cout << "\n" << v << " " << hex << hexx;
//printf("\n %s %d", v, hexx);
if (main == hexx) {
cout << endl << " found. number of checked hashes: " << _count;
found = true;
break;
}
}
} while (!found);
cout << " \nhash found: ";
return;
}
void bruteforce32(bool &found, string v, uint32_t main) {
srand(time(NULL));
/*random_device r;
default_random_engine e1(r());*/
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[BYTE_LENGTH] = {};
//cout << endl << " current hash: ";
//cout << hex << main;
//mt19937_64 gen(rd());
//fast_srand(seed);
mt19937 gen;
uint32_t seed = 0;
CryptGenRandom(hProvider, BYTE_LENGTH, pbData);
for (int i = 0; i < BYTE_LENGTH; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint32_t n;
unsigned long hexx;
string s;
//for (int i = 0; i < 1000000; i++) {
do {
printf("\r %d", _count);
//auto t1 = Clock::now();
for (int cycle = 0; cycle < 50000; cycle++) {
s = "";
n = gen();
//u_char* ch = new u_char();
//memcpy(ch, (char*)&n, 4);
/*for (int i = 0; i < 32; i++)
s += (char)rand() % 256;*/
/*for (int i = 0; i < 4; i++) {
s += (char)((n << 24 >> 24) & 0xFF);
s += (char)((n << 16 >> 24) & 0xFF);
s += (char)((n << 8 >> 24) & 0xFF);
s += (char)((n >> 24) & 0xFF);
}*/
//hexx = XXH32((u_char *)s.c_str(), 16, 0);
//hexx = Crc32((u_char *)bytes, 32);
hexx = Crc32((u_char *)s.c_str(), 16);
//hexx = XXH32((u_char *)s.c_str(), 16, 0);
_count++;
//cout << "\n" << v << " " << hex << hexx;
//printf("\n %s %d", v, hexx);
if (main == hexx) {
cout << endl << " found. number of checked hashes: " << _count;
found = true;
break;
}
}
//auto t2 = Clock::now();
//auto t0 = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
//cout << t0;
} while (!found);
cout << " \nhash found: ";
return;
}
void bruteforce16(bool &found, string v, uint16_t main) {
srand(time(NULL));
/*random_device r;
default_random_engine e1(r());*/
HCRYPTPROV hProvider = 0;
CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
unsigned char pbData[2] = {};
mt19937 gen;
uint16_t seed = 0;
CryptGenRandom(hProvider, 2, pbData);
for (int i = 0; i < 2; i++) {
seed = seed << 8;
seed += pbData[i];
}
gen.seed(seed);
uint16_t n;
uint16_t hexx;
string s;
//for (int i = 0; i < 1000000; i++) {
do {
//printf("\r %d", _count);
for (int cycle = 0; cycle < 50000; cycle++) {
s = "";
//u_char* ch = new u_char();
//memcpy(ch, (char*)&n, 4);
for (int i = 0; i < 2; i++) {
n = gen();
s += (char)((n << 8 >> 8) & 0xFF);
s += (char)((n >> 8) & 0xFF);
}
hexx = Crc16(reinterpret_cast<const uint8_t*>(s.c_str()), 8);
//hexx = Crc32((u_char *)s.c_str(), 16);
_count++;
//cout << "\n" << v << " " << hex << hexx;
//printf("\n %s %d", v, hexx);
if (main == hexx) {
cout << endl << " found. number of checked hashes: " << dec << _count;
found = true;
break;
}
}
} while (!found);
cout << " \nhash found: ";
return;
}
int main() {
srand(time(NULL));
ShowConsoleCursor(false);
unsigned __int64 i = 0;
int mode = 0;
cout << endl << " choose mode:";
cout << endl << " 1. birthday attack";
cout << endl << " 2. hash bruteforce attack";
cout << endl << " 0. exit";
cout << endl << " >: ";
cin >> mode;
found = false;
//bruteforce(found);
std::thread thr[8];
switch (mode) {
case 1:
for (int num = 0; num < NUMBER_OF_THREADS; num++) {
//thr[num] = thread(birthdayAttack16, ref(found));
//thr[num] = thread(birthdayAttack32, ref(found));
thr[num] = thread(birthdayAttack64, ref(found));
//thr[num].join();
}
break;
case 2:
{
string str = "";
cout << "\n type some sort of string: \n >: ";
cin >> str;
//string str = "qwertyuiopasdfghjklzxcvbnm481516";
//uint16_t main = Crc16((u_char *)str.c_str(), 8);
uint32_t main = Crc32((u_char *)str.c_str(), 16);
cout << " current hash: " << hex << main << "\n";
for (int num = 0; num < NUMBER_OF_THREADS; num++) {
//thr[num] = thread(bruteforce16, ref(found), "core " + to_string(num), main);
thr[num] = thread(bruteforce32, ref(found), "core " + to_string(num), main);
}
/*thr[0] = thread(bruteforce32, ref(found), "core 1");
thr[1] = thread(bruteforce32, ref(found), "core 2");*/
break;
}
case 0:
break;
}
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
Sleep(1);
thr[i].join();
}
/*for (thread & t : thr) {
Sleep(1);
t.join();
}*/
/*for (i = 0; i < LLONG_MAX * 2; i++) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { 0, 0 });
cout << i;
}*/
switch (mode) {
case 1:
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
if (T[i].collision)
cout << "\n\r collision found" << " in thread #" << T[i].thread_id;
}
break;
case 2:
cout << "\n\r hash found at " << _count << " hash";
break;
default:
break;
}
//system("pause");
return 0;
}
|
#pragma once
#pragma once
#include "../../Graphics/Skybox/Skybox.h"
#include "../../UI/Dependencies/IncludeImGui.h"
namespace ae
{
namespace priv
{
namespace ui
{
inline void SkyboxToEditor( ae::Skybox& _Skybox )
{
ImGui::Text( "Skybox" );
const CubeMap* CurrentCubeMap = _Skybox.GetCubeMap();
std::string CurrentCubeMapName = CurrentCubeMap == nullptr ? "None" : CurrentCubeMap->GetName();
ImGui::InputText( "Cube Map Name", &CurrentCubeMapName, ImGuiInputTextFlags_ReadOnly );
std::string CurrentCubeMapID = CurrentCubeMap == nullptr ? "Invalid ID" : std::to_string( CurrentCubeMap->GetResourceID() );
ImGui::InputText( "Cube Map ID", &CurrentCubeMapID, ImGuiInputTextFlags_ReadOnly );
ImGui::Separator();
}
}
} // priv
} //
|
#include <iostream>
using namespace std;
//void display(int arr[]){
// int size = sizeof(arr)/sizeof(int);
// for(int i=0; i<7; i++){
// cout << arr[i] << endl;
// }
//}
void testArray(int a);
int main() {
int arr[5] = {1,2,3,4,5};
testArray(arr[0]);
return 0;
}
void testArray(int c){
}
//void testArray(int arr[5]){
// cout << arr[2] << endl;
//}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @file
* @author Owner: Karianne Ekern (karie)
*
*/
#include "core/pch.h"
#include "adjunct/quick/widgets/OpBookmarkView.h"
#include "adjunct/quick/managers/DesktopBookmarkManager.h"
#include "adjunct/quick/menus/DesktopMenuHandler.h"
#include "adjunct/quick/models/DesktopHistoryModel.h"
#include "adjunct/quick/windows/BrowserDesktopWindow.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/dragdrop/dragdrop_manager.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
/***********************************************************************************
*
* Construct
*
***********************************************************************************/
// static
OP_STATUS OpBookmarkView::Construct(OpBookmarkView** obj,
PrefsCollectionUI::integerpref splitter_prefs_setting,
PrefsCollectionUI::integerpref viewstyle_prefs_setting,
PrefsCollectionUI::integerpref detailed_splitter_prefs_setting,
PrefsCollectionUI::integerpref detailed_viewstyle_prefs_setting)
{
*obj = OP_NEW(OpBookmarkView, ());
if (!*obj)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError((*obj)->init_status))
{
OP_DELETE(*obj);
return OpStatus::ERR_NO_MEMORY;
}
(*obj)->SetPrefsmanFlags(splitter_prefs_setting,viewstyle_prefs_setting,detailed_splitter_prefs_setting,detailed_viewstyle_prefs_setting);
(*obj)->Init();
return OpStatus::OK;
}
/***********************************************************************************
*
* OpBookmarkView
*
***********************************************************************************/
OpBookmarkView::OpBookmarkView()
{
// When creating a new BookmarkView -> Get the sorting from prefs
m_sort_column = g_pcui->GetIntegerPref(PrefsCollectionUI::HotlistSortBy);
m_sort_ascending = g_pcui->GetIntegerPref(PrefsCollectionUI::HotlistSortAsc);
// Some corrections so that we can keep using settings from 6.x
// Keep in sync with code in HotlistManager.cpp
if( m_sort_column > 6 )
{
if( m_sort_column == 16 ) // Unsorted
{
m_sort_column = -1;
m_sort_ascending = 1;
}
else if( m_sort_column == 1024 ) // Name
m_sort_column = 0;
else if( m_sort_column == 2048 ) // Created
m_sort_column = 4;
else if( m_sort_column == 4096 ) // Visited
m_sort_column = 5;
}
m_hotlist_view->SetBoldFolders(TRUE);
m_hotlist_view->SetAllowMultiLineItems(TRUE);
// --- SetTreeModel of TreeView --------------
if(g_hotlist_manager->GetBookmarksModel()->Loaded())
{
m_model = g_hotlist_manager->GetBookmarksModel();
// --- SetTreeModel of TreeView --------------
m_hotlist_view->SetTreeModel(m_model,m_sort_column, m_sort_ascending);
m_folders_view->SetTreeModel(m_model,m_sort_column, m_sort_ascending);
}
else
{
// Ignore Drag N Drop before the m_model is set.
SetIgnoresMouse(TRUE);
g_desktop_bookmark_manager->AddBookmarkListener(this);
}
}
/***********************************************************************************
*
* OnSetDetailed
*
***********************************************************************************/
void OpBookmarkView::OnSetDetailed(BOOL detailed)
{
SetHorizontal(detailed != FALSE);
m_hotlist_view->SetName(m_detailed ? "Bookmarks View" : "Bookmarks View Small");
m_hotlist_view->SetColumnWeight(1, 50);
m_hotlist_view->SetColumnWeight(2, 150);
m_hotlist_view->SetColumnVisibility(1, m_detailed);
m_hotlist_view->SetColumnVisibility(2, m_detailed);
m_hotlist_view->SetColumnVisibility(3, FALSE);
m_hotlist_view->SetColumnVisibility(4, FALSE);
m_hotlist_view->SetColumnVisibility(5, FALSE);
m_folders_view->SetName("Bookmarks Folders View");
m_hotlist_view->SetLinkColumn(IsSingleClick() ? 0 : -1);
}
/***********************************************************************************
*
* OnSortingChanged
*
***********************************************************************************/
void OpBookmarkView::OnSortingChanged(OpWidget *widget)
{
int column = 0;
BOOL ascending = false;
if( widget == m_folders_view )
{
column = m_folders_view->GetSortByColumn();
ascending = m_folders_view->GetSortAscending();
if( m_hotlist_view )
{
m_hotlist_view->Sort(column,ascending);
}
}
else if( widget == m_hotlist_view )
{
column = m_hotlist_view->GetSortByColumn();
ascending = m_hotlist_view->GetSortAscending();
if( m_folders_view )
{
m_folders_view->Sort(column,ascending);
}
}
else
{
return;
}
m_sort_column = column;
m_sort_ascending = ascending;
g_pcui->WriteIntegerL(PrefsCollectionUI::HotlistSortBy, column);
g_pcui->WriteIntegerL(PrefsCollectionUI::HotlistSortAsc, ascending);
g_prefsManager->CommitL();
}
/***********************************************************************************
*
* OnMouseEvent
*
***********************************************************************************/
void OpBookmarkView::HandleMouseEvent(OpTreeView* widget, HotlistModelItem* item, INT32 pos, MouseButton button, BOOL down, UINT8 nclicks)
{
BOOL shift = GetWidgetContainer()->GetView()->GetShiftKeys() & SHIFTKEY_SHIFT;
// single or double click mode
BOOL click_state_ok = (IsSingleClick() && !down && nclicks == 1 && !shift) || nclicks == 2;
// UNIX behavior. I guess everyone wants it.
if( down && nclicks == 1 && button == MOUSE_BUTTON_3 )
{
g_input_manager->InvokeAction(OpInputAction::ACTION_OPEN_LINK_IN_NEW_PAGE);
return;
}
if (click_state_ok)
{
g_input_manager->InvokeAction(OpInputAction::ACTION_OPEN_LINK);
}
}
/***********************************************************************************
*
* ShowContextMenu
*
***********************************************************************************/
BOOL OpBookmarkView::ShowContextMenu(const OpPoint &point,
BOOL center,
OpTreeView* view,
BOOL use_keyboard_context)
{
if (!view)
return FALSE;
HotlistModelItem* item = static_cast<HotlistModelItem*>(view->GetSelectedItem());
const char *menu_name = 0;
if( item && item->GetIsTrashFolder() )
menu_name = "Bookmark Trash Popup Menu";
else
menu_name = "Bookmark Item Popup Menu";
if (menu_name)
{
OpPoint p = point + GetScreenRect().TopLeft();
g_application->GetMenuHandler()->ShowPopupMenu(menu_name, PopupPlacement::AnchorAt(p, center), 0,use_keyboard_context);
}
return TRUE;
}
/***********************************************************************************
*
* OnDragStart
*
***********************************************************************************/
void OpBookmarkView::OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y)
{
if (widget == m_folders_view || widget == m_hotlist_view)
{
HotlistModelItem* item = GetItemByPosition(pos);
if( item )
{
// Close the folder when dragging
if (item->IsFolder())
{
m_hotlist_view->OpenItem(pos, FALSE);
}
DesktopDragObject* drag_object = 0;
drag_object = widget->GetDragObject(DRAG_TYPE_BOOKMARK, x, y);
if( drag_object )
{
BookmarkItemData item_data;
if( g_desktop_bookmark_manager->GetItemValue(item->GetID(), item_data ) )
{
drag_object->SetID(item->GetID());
drag_object->SetURL(item_data.url.CStr());
drag_object->SetTitle(item_data.name.CStr());
DragDrop_Data_Utils::SetText(drag_object, item_data.url.CStr());
}
}
g_drag_manager->StartDrag(drag_object, NULL, FALSE);
}
}
}
/***********************************************************************************
*
* DropURLItem
*
***********************************************************************************/
void OpBookmarkView::DropURLItem(HotlistModelItem* target, DesktopDragObject* drag_object, DesktopDragObject::InsertType insert_type)
{
INT32 new_selection_id = -1;
INT32 target_id = target ? target->GetID() : -1;
if( drag_object->GetURLs().GetCount() > 0 )
{
for( UINT32 i=0; i < drag_object->GetURLs().GetCount(); i++ )
{
BookmarkItemData item_data;
if( i == 0 )
item_data.name.Set( drag_object->GetTitle() );
item_data.url.Set( *drag_object->GetURLs().Get(i) );
if(i == 0)
{
item_data.description.Set( DragDrop_Data_Utils::GetText(drag_object) );
}
g_desktop_bookmark_manager->DropItem( item_data, target_id, insert_type, TRUE, drag_object->GetType(), &new_selection_id );
}
}
else
{
BookmarkItemData item_data;
item_data.name.Set( drag_object->GetTitle() );
item_data.url.Set( drag_object->GetURL() );
item_data.description.Set( DragDrop_Data_Utils::GetText(drag_object) );
g_desktop_bookmark_manager->DropItem( item_data, target_id, insert_type, TRUE, drag_object->GetType(), &new_selection_id );
}
}
/***********************************************************************************
*
* UpdateDragObject
*
***********************************************************************************/
void OpBookmarkView::UpdateDragObject(HotlistModelItem* target, DesktopDragObject* drag_object, DesktopDragObject::InsertType insert_type)
{
BookmarkItemData item_data;
INT32 target_id = target ? target->GetID() : -1;
if( g_desktop_bookmark_manager->DropItem( item_data, target_id, insert_type, FALSE, drag_object->GetType() ) )
{
drag_object->SetInsertType(insert_type);
drag_object->SetDesktopDropType(DROP_COPY);
}
}
/***********************************************************************************
*
* DropHistoryItem
*
***********************************************************************************/
void OpBookmarkView::DropHistoryItem(HotlistModelItem* target, DesktopDragObject* drag_object, DesktopDragObject::InsertType insert_type)
{
for (INT32 i = 0; i < drag_object->GetIDCount(); i++)
{
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
HistoryModelItem* history_item = history_model->FindItem(drag_object->GetID(i));
if (history_item)
{
BookmarkItemData item_data;
history_item->GetAddress(item_data.url);
history_item->GetTitle(item_data.name);
INT32 id = target ? target->GetID() : -1;
// TODO/Note: The other paths here call DropItem. This does NewBookmark directly.
// Means if duplicate, nothing will happen.
// Note: Calling NewBookmark instead of Drop here, means the position you drop to wont be used, item is dropped to Root
//g_hotlist_manager->NewBookmark( item_data, id, GetParentDesktopWindow(), FALSE );
g_desktop_bookmark_manager->DropItem(item_data, id, insert_type, TRUE, drag_object->GetType());
}
}
}
/***********************************************************************************
*
* UpdateHistoryDragObject
*
***********************************************************************************/
void OpBookmarkView::UpdateHistoryDragObject(HotlistModelItem* target, DesktopDragObject* drag_object, DesktopDragObject::InsertType insert_type)
{
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
HistoryModelItem* history_item = history_model->FindItem(drag_object->GetID(0));
if (history_item)
return UpdateDragObject(target, drag_object, insert_type);
}
/***********************************************************************************
*
* DropWindowItem
*
***********************************************************************************/
void OpBookmarkView::DropWindowItem(HotlistModelItem* target, DesktopDragObject* drag_object, DesktopDragObject::InsertType insert_type)
{
DesktopWindowCollection& model = g_application->GetDesktopWindowCollection();
for (INT32 i = 0; i < drag_object->GetIDCount(); i++)
{
DesktopWindowCollectionItem* item = model.GetItemByID(drag_object->GetID(i));
if (!item || item->GetType() != WINDOW_TYPE_DOCUMENT || !item->GetDesktopWindow())
continue;
OpWindowCommander* document = static_cast<DocumentDesktopWindow*>(item->GetDesktopWindow())->GetWindowCommander();
BookmarkItemData item_data;
RETURN_VOID_IF_ERROR(item_data.name.Set(document->GetCurrentTitle()));
RETURN_VOID_IF_ERROR(item_data.url.Set(document->GetCurrentURL(FALSE)));
INT32 id = target ? target->GetID() : -1;
g_desktop_bookmark_manager->DropItem(item_data, id, insert_type, TRUE, drag_object->GetType());
}
}
BOOL OpBookmarkView::OnExternalDragDrop(OpTreeView* tree_view, OpTreeModelItem* item, DesktopDragObject* drag_object, DropType drop_type, DesktopDragObject::InsertType insert_type, BOOL drop, INT32& new_selection_id)
{
// Set type correctly
INT32 target_id = item ? item->GetID() : HotlistModel::BookmarkRoot;
HotlistModelItem * target = m_model->GetItemByID(target_id);
if (drag_object->GetType() == DRAG_TYPE_HISTORY)
{
if (drop)
{
DropHistoryItem(target, drag_object, insert_type);
}
else if( drag_object->GetIDCount() > 0 )
{
UpdateHistoryDragObject(target, drag_object, insert_type);
}
}
else if (drag_object->GetType() == DRAG_TYPE_WINDOW)
{
if (drop)
{
DropWindowItem(target, drag_object, insert_type);
}
else if (drag_object->GetIDCount() > 0)
{
UpdateDragObject(target, drag_object, insert_type);
}
}
else if (drag_object->GetURL() && *drag_object->GetURL() )
{
if (drop)
{
DropURLItem(target, drag_object, insert_type);
}
else
{
UpdateDragObject(target, drag_object, insert_type);
}
}
return TRUE;
}
BOOL OpBookmarkView::OnInputAction(OpInputAction* action)
{
BOOL special_folder;
OpTreeView* tree_view = GetTreeViewFromInputContext(action->GetFirstInputContext());
HotlistModelItem* item;
item = (HotlistModelItem*)tree_view->GetSelectedItem();
if (!item && m_view_style != STYLE_TREE && tree_view != m_folders_view)
item = (HotlistModelItem*)m_folders_view->GetSelectedItem();
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_SAVE_SELECTED_BOOKMARKS_AS:
case OpInputAction::ACTION_EXPORT_SELECTED_BOOKMARKS_TO_HTML:
{
// Disable if no items are selected or if the selected item is a separator
child_action->SetEnabled((item != NULL) && !item->IsSeparator());
return TRUE;
}
}
break;
} // ENC case ACTION_GET_ACTION_STATE
case OpInputAction::ACTION_EDIT_PROPERTIES:
{
if (!item && m_folders_view)
item = (HotlistModelItem*)m_folders_view->GetSelectedItem();
if( tree_view->GetSelectedItemCount() == 1 && item)
{
g_desktop_bookmark_manager->EditItem(item->GetID(), GetParentDesktopWindow() );
}
return TRUE;
}
}
if (item)
{
// Selected item is special folder...
special_folder = item->GetIsSpecialFolder();
if (!special_folder)
{
// ...or inside special folder
special_folder = item->GetParentFolder() && item->GetParentFolder()->GetIsSpecialFolder();
}
}
else // !item
{
special_folder = FALSE;
}
// these actions don't need a selected item
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_EDIT_PROPERTIES:
{
BOOL enabled = (tree_view->GetSelectedItemCount() == 1);
if (item && item->IsSeparator())
enabled = FALSE;
child_action->SetEnabled(enabled);
return TRUE;
}
case OpInputAction::ACTION_OPEN_LINK:
{
if(child_action->GetActionData() || child_action->GetActionDataString())
return FALSE;
BOOL enabled = tree_view->GetSelectedItemCount();
if (item && item->IsSeparator())
enabled = FALSE;
child_action->SetEnabled(enabled);
return TRUE;
}
case OpInputAction::ACTION_PASTE:
{
child_action->SetEnabled(g_desktop_bookmark_manager->GetBookmarkModel()->Loaded() &&
g_desktop_bookmark_manager->GetClipboard()->GetCount());
return TRUE;
}
case OpInputAction::ACTION_NEW_SEPERATOR:
case OpInputAction::ACTION_NEW_FOLDER:
case OpInputAction::ACTION_NEW_BOOKMARK:
child_action->SetEnabled(g_desktop_bookmark_manager->GetBookmarkModel()->Loaded());
return TRUE;
}
break;
}
case OpInputAction::ACTION_NEW_SEPERATOR:
{
int item_id = item ? item->GetID() : GetCurrentFolderID();
if (item)
{
if (item->GetIsTrashFolder() || item ->GetIsInsideTrashFolder())
{
item_id = item->GetModel()->GetModelType();
}
else
item_id = item->GetID();
}
g_desktop_bookmark_manager->NewSeparator(item_id);
return TRUE;
}
case OpInputAction::ACTION_NEW_FOLDER:
{
INT32 item_id;
if (item)
{
item_id = item->GetID();
}
else
{
item_id = GetCurrentFolderID();
}
g_desktop_bookmark_manager->NewBookmarkFolder(NULL, item_id, tree_view);
return TRUE;
}
case OpInputAction::ACTION_NEW_BOOKMARK:
{
g_desktop_bookmark_manager->NewBookmark(item ? item->GetID() : GetCurrentFolderID(), GetParentDesktopWindow() );
return TRUE;
}
case OpInputAction::ACTION_DELETE:
case OpInputAction::ACTION_CUT:
{
OpINT32Vector id_list;
tree_view->GetSelectedItems( id_list );
if( id_list.GetCount() == 0 )
{
return FALSE;
}
if( action->GetAction() == OpInputAction::ACTION_DELETE )
{
// remember the next item to active after deleting.
INT32 last_item = tree_view->GetItemByID(id_list.Get(id_list.GetCount()-1));
INT32 last_line = tree_view->GetLineByItem(last_item);
INT32 select_line = last_line - id_list.GetCount() + 1;
g_desktop_bookmark_manager->Delete(id_list);
INT32 line = (select_line >= tree_view->GetLineCount()) ? tree_view->GetLineCount() - 1 : select_line;
tree_view->SetSelectedItem(tree_view->GetItemByLine(line));
}
else if( action->GetAction() == OpInputAction::ACTION_CUT )
{
g_desktop_bookmark_manager->CutItems ( id_list );
}
return TRUE;
}
case OpInputAction::ACTION_COPY:
{
OpINT32Vector id_list;
tree_view->GetSelectedItems( id_list );
if( id_list.GetCount() == 0 )
{
return FALSE;
}
else if( action->GetAction() == OpInputAction::ACTION_COPY )
{
g_desktop_bookmark_manager->CopyItems( id_list );
}
return TRUE;
}
break;
case OpInputAction::ACTION_PASTE:
{
g_desktop_bookmark_manager->PasteItems(item );
return TRUE;
}
case OpInputAction::ACTION_EXPORT_SELECTED_BOOKMARKS_TO_HTML:
{
if( tree_view->GetSelectedItemCount() > 0 && item )
{
OpINT32Vector item_list;
tree_view->GetSelectedItems(item_list);
g_hotlist_manager->SaveSelectedAs( item->GetID(), item_list, HotlistManager::SaveAs_Html );
}
return TRUE;
}
case OpInputAction::ACTION_SAVE_SELECTED_BOOKMARKS_AS:
{
OpINT32Vector id_list;
tree_view->GetSelectedItems( id_list, TRUE );
if( id_list.GetCount() > 0 && item )
{
g_hotlist_manager->SaveSelectedAs( item->GetID(), id_list, HotlistManager::SaveAs_Export );
}
return TRUE;
}
// Set where we should add the bookmarks to, the action is performed in BrowserDesktopWindow
case OpInputAction::ACTION_ADD_ALL_TO_BOOKMARKS:
{
action->SetActionData(GetSelectedFolderID());
}
break;
}
return OpHotlistTreeView::OnInputAction(action);
}
INT32 OpBookmarkView::OnDropItem(HotlistModelItem* to,DesktopDragObject* drag_object, INT32 i, DropType drop_type, DesktopDragObject::InsertType insert_type, INT32 *first_id, BOOL force_delete)
{
HotlistModelItem* from = m_model->GetItemByID(drag_object->GetID(i));
CoreBookmarkPos pos(to, insert_type);
g_bookmark_manager->MoveBookmark(BookmarkWrapper(from)->GetCoreItem(), pos.previous, pos.parent);
*first_id = from->GetID();
return 0;
}
void OpBookmarkView::SetModel(BookmarkModel* model)
{
OP_ASSERT(!m_model);
if(!m_model)
{
m_model = model;
// --- SetTreeModel of TreeView --------------
m_hotlist_view->SetTreeModel(m_model,m_sort_column, m_sort_ascending);
m_folders_view->SetTreeModel(m_model,m_sort_column, m_sort_ascending);
SetDetailed(m_detailed, TRUE); // was called once in Init() but didn't take effect as the model wasn't set there.
InitModel();
}
}
void OpBookmarkView::OnBookmarkModelLoaded()
{
SetIgnoresMouse(FALSE);
SetModel(g_hotlist_manager->GetBookmarksModel());
}
void OpBookmarkView::OnDeleted()
{
if(g_desktop_bookmark_manager)
g_desktop_bookmark_manager->RemoveBookmarkListener(this);
OpHotlistTreeView::OnDeleted();
}
|
#include<iostream>
using namespace std;
int addtwo(int a, int b){
int sum;
sum = a + b;
return sum;
}
void printsome(int x,int y){
cout << " EXecuted function" << endl;
cout << "inputted value :" << x <<","<<y << endl;
}
int y = 5;
int main(){
int x = 89;
int y = 56;
printsome(89,56);
int tot = addtwo(89,56);
cout << "Sum of two numbers:" << tot << endl;
}
|
#include <iostream>
#include <string>
std::string a1z26Crypt(std::string input);
std::string a1z26Decrypt(std::string input);
|
/*
replay
Software Library
Copyright (c) 2010-2019 Marius Elvert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cstdint>
#include <filesystem>
#include <replay/bstream.hpp>
#include <replay/pixbuf_io.hpp>
#include <boost/numeric/conversion/cast.hpp>
#ifdef REPLAY_USE_STBIMAGE
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#endif
#ifdef REPLAY_USE_STBIMAGE_WRITE
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#endif
namespace
{
int stb_read_callback(void* user, char* data, int size)
{
std::istream* file(reinterpret_cast<std::istream*>(user));
file->read(data, size);
return static_cast<int>(file->gcount());
}
void stb_skip_callback(void* user, int n)
{
std::istream* file(reinterpret_cast<std::istream*>(user));
for (int i = 0; i < n; ++i)
file->get();
}
int stb_eof_callback(void* user)
{
std::istream* file(reinterpret_cast<std::istream*>(user));
return file->eof() ? 1 : 0;
}
class tga_header
{
public:
tga_header()
: id_length(0)
, colormap_type(0)
, image_type(0)
, width(0)
, height(0)
, pixeldepth(0)
, image_descriptor(0)
{
colormap[0] = colormap[1] = colormap[2] = colormap[3] = colormap[4] = 0;
origin[0] = origin[1] = 0;
}
replay::pixbuf load(replay::input_binary_stream& file);
void save(replay::output_binary_stream& file, replay::pixbuf const& source);
private:
std::uint8_t id_length;
std::uint8_t colormap_type;
std::uint8_t image_type;
std::uint8_t colormap[5];
std::uint16_t origin[2];
std::uint16_t width;
std::uint16_t height;
std::uint8_t pixeldepth;
std::uint8_t image_descriptor;
replay::pixbuf load_type2(replay::input_binary_stream& file);
};
} // namespace
#ifdef REPLAY_USE_STBIMAGE_WRITE
/** Serialize by encoding a PNG file via stbimage_write.
\param file The file to serialize to.
\param source The image to serialize.
\ingroup Imaging
*/
void replay::pixbuf_io::save_to_png_file(std::ostream& file, pixbuf const& source)
{
auto write_callback = [](void* context, void* data, int size) {
auto file = reinterpret_cast<std::ostream*>(context);
file->write(reinterpret_cast<char const*>(data), size);
};
auto stride = boost::numeric_cast<int>(source.width() * source.channel_count());
auto width = boost::numeric_cast<int>(source.width());
auto height = boost::numeric_cast<int>(source.height());
auto channel_count = boost::numeric_cast<int>(source.channel_count());
stbi_write_png_to_func(write_callback, &file, width, height, channel_count,
source.ptr() + stride * (height - 1), -stride);
}
#endif
replay::pixbuf tga_header::load_type2(replay::input_binary_stream& file)
{
using namespace replay;
// read in colormap dummy data
file >> colormap[0] >> colormap[1] >> colormap[2] >> colormap[3] >> colormap[4];
// read in image specification
file >> origin[0] >> origin[1] >> width >> height >> pixeldepth >> image_descriptor;
// only TARGA-24 and TARGA-32 are supported
if ((pixeldepth != 24) && (pixeldepth != 32))
throw pixbuf_io::unrecognized_format();
// read the freeform id
std::uint8_t dummy;
for (int i = 0; i < id_length; ++i)
file >> dummy;
using index_type = replay::pixbuf::index_type;
// now read the image data
replay::pixbuf result(width, height, pixeldepth == 24 ? pixbuf::color_format::rgb : pixbuf::color_format::rgba);
auto pixelcount = index_type(width) * height;
auto pixel = result.ptr();
std::uint8_t buffer[4];
if (pixeldepth == 24)
{
for (index_type i = 0; i < pixelcount; ++i)
{
file.read(buffer, 3);
*(pixel++) = buffer[2];
*(pixel++) = buffer[1];
*(pixel++) = buffer[0];
}
}
else // pixeldepth == 32
{
for (index_type i = 0; i < pixelcount; ++i)
{
file.read(buffer, 4);
*(pixel++) = buffer[2];
*(pixel++) = buffer[1];
*(pixel++) = buffer[0];
*(pixel++) = buffer[3];
}
}
return result;
}
/** Deserialize a TGA encoded file.
\ingroup Imaging
*/
replay::pixbuf replay::pixbuf_io::load_from_tga_file(std::istream& file)
{
tga_header header;
input_binary_stream binary_file(file);
return header.load(binary_file);
}
/** Serialize by encoding a TGA file.
\ingroup Imaging
*/
void replay::pixbuf_io::save_to_tga_file(std::ostream& file, const pixbuf& source)
{
tga_header header;
output_binary_stream binary_file(file);
header.save(binary_file, source);
}
/** Save an image.
\note Only TGA and PNG are supported right now.
\param filename Path of the file to be saved.
\param source The image to be saved.
\ingroup Imaging
*/
void replay::pixbuf_io::save_to_file(std::filesystem::path const& filename, pixbuf const& source)
{
auto const extension = filename.extension().string();
std::ofstream file;
file.exceptions(std::ifstream::badbit | std::ifstream::eofbit | std::ifstream::failbit);
file.open(filename, std::ios_base::out | std::ios_base::binary);
if (extension == ".tga")
{
save_to_tga_file(file, source);
}
#ifdef REPLAY_USE_STBIMAGE_WRITE
else if (extension == ".png")
{
save_to_png_file(file, source);
}
#endif
else
{
throw pixbuf_io::unrecognized_format();
}
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
replay::pixbuf tga_header::load(replay::input_binary_stream& file)
{
using namespace replay;
file >> id_length >> colormap_type >> image_type;
// colormaps are not supported
if (colormap_type != 0)
throw pixbuf_io::unrecognized_format();
replay::pixbuf result;
switch (image_type)
{
// uncompressed, unmapped BGR image
case 2:
result = load_type2(file);
break;
// FIXME: add this
// compressed, unmapped
// case 10: load_type10( dst, file ); break;
default:
throw pixbuf_io::unrecognized_format();
}
if (image_descriptor & (1 << 5))
result.flip();
return result;
}
void tga_header::save(replay::output_binary_stream& file, replay::pixbuf const& source)
{
if (!source.empty() && ((source.channel_count() == 3) || (source.channel_count() == 4)))
{
image_type = 2;
width = boost::numeric_cast<std::uint16_t>(source.width());
height = boost::numeric_cast<std::uint16_t>(source.height());
pixeldepth = boost::numeric_cast<std::uint8_t>(source.channel_count() * 8);
}
else
{
throw replay::pixbuf_io::write_error();
}
file << id_length << colormap_type << image_type;
// write colormap dummy data
file << colormap[0] << colormap[1] << colormap[2] << colormap[3] << colormap[4];
// write image specification
file << origin[0] << origin[1] << width << height << pixeldepth << image_descriptor;
unsigned int pixelcount = width * height;
const std::uint8_t* pixel = source.ptr();
std::uint8_t buffer[4];
if (pixeldepth == 24)
{
for (unsigned int i = 0; i < pixelcount; ++i)
{
buffer[2] = *(pixel++);
buffer[1] = *(pixel++);
buffer[0] = *(pixel++);
file.write(buffer, 3);
}
}
else // pixeldepth == 32
{
for (unsigned int i = 0; i < pixelcount; ++i)
{
buffer[2] = *(pixel++);
buffer[1] = *(pixel++);
buffer[0] = *(pixel++);
buffer[3] = *(pixel++);
file.write(buffer, 4);
}
}
}
/** Load an image.
The format is guessed from the filename's extension.
\note Only TGA and PNG are supported right now.
\param filename Path of the file to be loaded.
\ingroup Imaging
*/
replay::pixbuf replay::pixbuf_io::load_from_file(std::filesystem::path const& filename)
{
auto const extension = filename.extension().string();
std::ifstream file;
file.open(filename, std::ios_base::in | std::ios_base::binary);
if (!file.good())
throw read_error("Unable to open file " + filename.string());
#ifdef REPLAY_USE_STBIMAGE
stbi_io_callbacks callbacks;
callbacks.read = &stb_read_callback;
callbacks.skip = &stb_skip_callback;
callbacks.eof = &stb_eof_callback;
int rx = 0, ry = 0, comp = 0;
auto* data = stbi_load_from_callbacks(&callbacks, static_cast<std::istream*>(&file), &rx, &ry, &comp, 0);
if (!data)
{
throw pixbuf_io::unrecognized_format();
}
replay::pixbuf::color_format format = pixbuf::color_format::rgba;
if (comp != 4)
{
if (comp == 3)
format = replay::pixbuf::color_format::rgb;
else if (comp == 1)
format = replay::pixbuf::color_format::greyscale;
else
{
stbi_image_free(data);
throw pixbuf_io::unrecognized_format();
}
}
pixbuf result(rx, ry, format);
auto target = result.ptr();
std::size_t byte_count = rx * ry * comp;
for (std::size_t i = 0; i < byte_count; ++i)
target[i] = data[i];
stbi_image_free(data);
result.flip();
return result;
#else
file.exceptions(std::ifstream::badbit | std::ifstream::eofbit | std::ifstream::failbit);
if (extension == ".tga")
{
return load_from_tga_file(file);
}
#ifdef REPLAY_USE_LIBPNG
else if (extension == ".png")
{
return load_from_png_file(file);
}
#endif
throw pixbuf_io::unrecognized_format();
#endif
}
/** Load an image.
The format is guessed from the files contents.
\param filename Path of the file to be loaded.
\ingroup Imaging
*/
replay::pixbuf replay::pixbuf_io::load_from_file(std::istream& file)
{
#ifdef REPLAY_USE_STBIMAGE
stbi_io_callbacks callbacks;
callbacks.read = &stb_read_callback;
callbacks.skip = &stb_skip_callback;
callbacks.eof = &stb_eof_callback;
int rx = 0, ry = 0, comp = 0;
auto* data = stbi_load_from_callbacks(&callbacks, static_cast<std::istream*>(&file), &rx, &ry, &comp, 0);
if (!data)
{
const char* failure = stbi_failure_reason();
throw pixbuf_io::read_error(failure);
}
replay::pixbuf::color_format format = pixbuf::color_format::rgba;
if (comp != 4)
{
if (comp == 3)
format = replay::pixbuf::color_format::rgb;
else if (comp == 1)
format = replay::pixbuf::color_format::greyscale;
else
{
stbi_image_free(data);
throw pixbuf_io::unrecognized_format();
}
}
pixbuf result(rx, ry, format);
auto target = result.ptr();
std::size_t byte_count = rx * ry * comp;
for (std::size_t i = 0; i < byte_count; ++i)
target[i] = data[i];
stbi_image_free(data);
result.flip();
return result;
#else
throw pixbuf_io::unrecognized_format();
#endif
}
#endif
|
#ifndef OBJETOS_H
#define OBJETOS_H
class Objeto
{
public:
SDL_Surface* imagem;
SDL_Rect quadro, posicao;
Mix_Chunk* chunk;
bool visivel;
/*void Desenhar()
{
SDL_BlitSurface(this.imagem, &this.quadro, janela, &this.posicao);
};*/
private:
};
Objeto iniciar, iniciar_over, creditos, creditos_over, sair, sair_over, indicador;
#endif
|
#pragma once
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <iostream>
using namespace cv;
using namespace std;
float Point_Distance_2(Point2f p1, Point2f p2);
float Point_Distance_3(Point3f p1, Point3f p2);
RotatedRect Rect_Rotate(RotatedRect rect);
//定义结构:包含轮廓总集、选定轮廓的序号;
typedef struct ContoursRequired
{
vector<vector<Point>> contours;
int LightBar_1;
int LightBar_2;
} ContoursRequired;
//定义结构:包含输出的图像、装甲板角点的像素坐标、装甲板中心的像素坐标;
typedef struct ImageAndPoint
{
Mat Image;
vector<Point2f> ImagePoint;
Point2f Center;
} ImageAndPoint;
//定义探测类
class Detection
{
public:
Detection();
~Detection();
// 预处理:转变为二值图像;
Mat PreCompile(Mat Image, String S);
// 获得所需的轮廓:返回 contours 和轮廓序号 LightBar_1、LightBar_2;
ContoursRequired GetRequiredContours(Mat Image);
// 选择装甲板的四个角点;
vector<Point2f> ChoosePoint(Point2f vertices_1[4], Point2f vertices_2[4]);
//返回装甲板中心点;
Point2f GetCenter(vector<Point2f> vertice);
// 画出装甲板的四个角点和中心点
ImageAndPoint DrawingImage(Mat Image, Mat Image_Two_Value, ContoursRequired CN);
};
|
// PCL lib Functions for processing point clouds
#ifndef PROCESSPOINTCLOUDS_H_
#define PROCESSPOINTCLOUDS_H_
#include <pcl/io/pcd_io.h>
#include <pcl/common/common.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/crop_box.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/common/transforms.h>
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <chrono>
#include <unordered_set>
#include "render/box.h"
#include "kdtree.h"
template<typename PointT>
class ProcessPointClouds {
public:
//constructor
ProcessPointClouds();
//deconstructor
~ProcessPointClouds();
void numPoints(typename pcl::PointCloud<PointT>::Ptr cloud);
typename pcl::PointCloud<PointT>::Ptr FilterCloud(typename pcl::PointCloud<PointT>::Ptr cloud, float filterRes, Eigen::Vector4f minPoint, Eigen::Vector4f maxPoint);
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> SeparateClouds(pcl::PointIndices::Ptr inliers, typename pcl::PointCloud<PointT>::Ptr cloud);
/**
* @brief Extract plane from point cloud with list of point indices
*
* Only the first 3 point indices will be used to form the plane
*
* @param points Point cloud
* @param indexList List of point indices to include in plane fit
* @param normalMagnitude Magnitude of plane normal vector
* @return std::vector<double> Plane coefficients
*/
std::vector<double> GetPlaneCoefficients(const typename pcl::PointCloud<PointT>::Ptr cloud, const std::unordered_set<int> &indexList, double &normalMagnitude);
/**
* @brief Single plane segmentation RANSAC implementation
*
* Three points chosen at random are used to generate a plane and all remaining point distances to plane are tested.
*
* @param cloud Point cloud
* @param maxIterations Number of planes to test
* @param distanceTol Distance to include test points as inliers
* @return std::unordered_set<int> Best set of inlier point indices
*/
std::unordered_set<int> GetGroundPlane(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceTol);
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> SegmentPlane(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceThreshold);
// std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> SegmentPlanePcl(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceThreshold);
std::vector<typename pcl::PointCloud<PointT>::Ptr> Clustering(typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize);
// std::vector<typename pcl::PointCloud<PointT>::Ptr> ClusteringPcl(typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize);
void Proximity(const float distanceTol, const typename pcl::PointCloud<PointT>::Ptr cloud, const int targetId, KdTree<PointT> &tree, std::unordered_set<int> &processedPoints, std::vector<int> &cluster);
std::vector<std::vector<int>> euclideanCluster(const typename pcl::PointCloud<PointT>::Ptr cloud, KdTree<PointT> &tree, float distanceTol, int minSize, int maxSize);
Box BoundingBox(typename pcl::PointCloud<PointT>::Ptr cluster);
void savePcd(typename pcl::PointCloud<PointT>::Ptr cloud, std::string file);
typename pcl::PointCloud<PointT>::Ptr loadPcd(std::string file);
std::vector<boost::filesystem::path> streamPcd(std::string dataPath);
};
#endif /* PROCESSPOINTCLOUDS_H_ */
|
/*
* Password.h
*
* Created on: 18/06/2015
* Author: root
*/
#ifndef PASSWORD_H_
#define PASSWORD_H_
#include "define.h"
using namespace std;
class Password
{
public:
static string makeStr(string soureStr,string targetStr);
static string getStr(string& str);
};
#endif /* PASSWORD_H_ */
|
/*
Copyright 2022 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "sql_json_reader.hpp"
#include <iostream>
#include <memory>
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
using orkhestrafs::sql_parsing::SQLJSONReader;
using rapidjson::Document;
using rapidjson::FileReadStream;
void SQLJSONReader::ReadQuery(const std::string& filename,
std::map<int, std::vector<std::string>>& data) {
// TODO(Kaspar): Same as rapidjosn_reader::Read - Remove the duplication
FILE* file_pointer = fopen(filename.c_str(), "r");
if (!file_pointer) {
throw std::runtime_error("Couldn't find: " + filename);
}
char read_buffer[8192];
FileReadStream input_stream(file_pointer, read_buffer, sizeof(read_buffer));
auto document = std::make_unique<Document>();
document->ParseStream(input_stream);
fclose(file_pointer);
const std::string params = "params";
const std::string type = "type";
for (const auto& element : document->GetObject()) {
int current_key = std::stoi(element.name.GetString());
std::vector<std::string> current_params;
current_params.emplace_back(
element.value.GetObject()[type.c_str()].GetString());
for (const auto& param :
element.value.GetObject()[params.c_str()].GetArray()) {
if (param.IsInt()) {
current_params.push_back(std::to_string(param.GetInt()));
} else if (param.IsString()) {
current_params.emplace_back(param.GetString());
} else {
throw std::runtime_error("Incorrect type");
}
}
data.insert({current_key, current_params});
}
}
|
#include <initializer_list>
#include <algorithm>
class vector1 {
int sz;
double* elem;
public:
vector1(int);
~vector1();
int size();
double get(int) const;
void set(int, double);
};
|
#include "../include/io.h"
#include "../../core/include/error.hpp"
#include <fstream>
namespace li {
/*
Matrix_<LI_U8> imload(const char *fname) {
std::ifstream ifs(fname, std::ifstream::binary);
if (ifs) {
BitMapFileHeader *fh = new BitMapFileHeader;
BitMapInfoHeader *ih = new BitMapInfoHeader;
ifs.read((char *) fh, sizeof(BitMapFileHeader));
ifs.read((char *) ih, sizeof(BitMapInfoHeader));
auto offset = fh->Offset;
auto width = ih->Width;
auto height = ih->Height;
auto bitcnt = ih->BitCount;
auto imsize = ih->ImageSize;
int channels = bitcnt / 8;
LI_U8 *buf = new LI_U8[imsize];
LI_U8 *img = new LI_U8[width * height * channels];
ifs.seekg(offset);
ifs.read((char *) buf, imsize);
ifs.close();
auto padding = (width * channels) % 4 ? 4 - (width * channels) % 4 : 0;
LI_U8 *ptr_buf = buf;
LI_U8 *ptr_img = img;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
ptr_img[0] = ptr_buf[2];
ptr_img[1] = ptr_buf[1];
ptr_img[2] = ptr_buf[0];
ptr_buf += channels;
ptr_img += channels;
}
ptr_buf += padding;
}
delete[] buf;
return Matrix_<LI_U8>(width, height, channels, img);
} else {
ERR("Open file failed");
}
}
*/
bool imsave(Image &_im, const char *fname) {
BitMapFileHeader *fh = new BitMapFileHeader;
BitMapInfoHeader *ih = new BitMapInfoHeader;
int width = _im.width;
int height = _im.height;
int channels = _im.channels;
int padding = (width * channels) % 4 ? 4 - (width * channels) % 4 : 0;
int step = width * channels + padding;
int imgSize = step * height;
ih->InfoSize = sizeof(BitMapInfoHeader);
ih->Height = height;
ih->Width = width;
ih->Planes = 1;
ih->BitCount = 8 * channels;
ih->Compression = 0;
ih->ImageSize = imgSize;
ih->HResolution = 2835;
ih->VResolution = 2835;
ih->ColorCount = 0;
ih->ColorImportant = 0;
fh->Type[0] = 'B';
fh->Type[1] = 'M';
fh->Reserved1 = 0;
fh->Reserved2 = 0;
fh->Offset = sizeof(BitMapFileHeader) + sizeof(BitMapInfoHeader);
fh->FileSize = imgSize + fh->Offset;
LI_U8 *colorTab = new LI_U8[256 * 4];\
LI_U8 *ptr_tab = colorTab;
for (int i = 0; i < 256; ++i) {
ptr_tab[0] = i;
ptr_tab[1] = i;
ptr_tab[2] = i;
ptr_tab[3] = 0;
ptr_tab += 4;
}
if (channels == 1) {
ih->ColorCount = 256;
fh->Offset += 256 * 4;
fh->FileSize += 256 * 4;
}
LI_U8 *buf = new LI_U8[step * height];
LI_U8 *ptr_buf = buf + (height - 1) * step;
LI_U8 *ptr_img = _im.data;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (channels == 3) {
ptr_buf[2] = ptr_img[0];
ptr_buf[1] = ptr_img[1];
ptr_buf[0] = ptr_img[2];
} else {
if (channels == 1)
ptr_buf[0] = ptr_img[0];
}
ptr_buf += channels;
ptr_img += channels;
}
ptr_buf += padding;
ptr_buf -= 2 * step;
}
std::ofstream ofs(fname, std::ofstream::binary);
if (ofs) {
ofs.write((char *) fh, sizeof(BitMapFileHeader));
ofs.write((char *) ih, sizeof(BitMapInfoHeader));
if (channels == 1) {
ofs.write((char *) colorTab, 1024);
}
ofs.write((char *) buf, imgSize);
ofs.close();
} else {
delete[](buf);
delete(ih);
delete(fh);
delete[](colorTab);
ERR("Open file failed");
}
delete[](buf);
delete(ih);
delete(fh);
delete[](colorTab);
return true;
}
Image imload(const char *fname) {
std::ifstream ifs(fname, std::ifstream::binary);
if (ifs) {
BitMapFileHeader *fh = new BitMapFileHeader;
BitMapInfoHeader *ih = new BitMapInfoHeader;
ifs.read((char *) fh, sizeof(BitMapFileHeader));
ifs.read((char *) ih, sizeof(BitMapInfoHeader));
auto offset = fh->Offset;
auto width = ih->Width;
auto height = ih->Height;
auto bitcnt = ih->BitCount;
auto imsize = ih->ImageSize;
int channels = bitcnt / 8;
LI_U8 *buf = new LI_U8[imsize];
LI_U8 *img = new LI_U8[width * height * channels];
ifs.seekg(offset);
ifs.read((char *) buf, imsize);
ifs.close();
auto padding = (width * channels) % 4 ? 4 - (width * channels) % 4 : 0;
//auto step = (width + padding) * channels;
auto step = width * channels + padding;
LI_U8 *ptr_buf = buf + (height - 1) * step;
LI_U8 *ptr_img = img;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (channels == 3) {
ptr_img[0] = ptr_buf[2];
ptr_img[1] = ptr_buf[1];
ptr_img[2] = ptr_buf[0];
} else {
if (channels == 1)
ptr_img[0] = ptr_buf[0];
}
ptr_buf += channels;
ptr_img += channels;
}
ptr_buf += padding;
ptr_buf -= 2 * step;
}
delete[] buf;
delete fh;
delete ih;
return Image(width, height, channels, img);
} else {
ERR("Open file failed");
}
}
}
|
// Created on: 1999-03-10
// Created by: data exchange team
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepAP214_AppliedSecurityClassificationAssignment_HeaderFile
#define _StepAP214_AppliedSecurityClassificationAssignment_HeaderFile
#include <Standard.hxx>
#include <StepAP214_HArray1OfSecurityClassificationItem.hxx>
#include <StepBasic_SecurityClassificationAssignment.hxx>
#include <Standard_Integer.hxx>
class StepBasic_SecurityClassification;
class StepAP214_SecurityClassificationItem;
class StepAP214_AppliedSecurityClassificationAssignment;
DEFINE_STANDARD_HANDLE(StepAP214_AppliedSecurityClassificationAssignment, StepBasic_SecurityClassificationAssignment)
class StepAP214_AppliedSecurityClassificationAssignment : public StepBasic_SecurityClassificationAssignment
{
public:
//! Returns a AppliedSecurityClassificationAssignment
Standard_EXPORT StepAP214_AppliedSecurityClassificationAssignment();
Standard_EXPORT void Init (const Handle(StepBasic_SecurityClassification)& aAssignedSecurityClassification, const Handle(StepAP214_HArray1OfSecurityClassificationItem)& aItems);
Standard_EXPORT void SetItems (const Handle(StepAP214_HArray1OfSecurityClassificationItem)& aItems);
Standard_EXPORT Handle(StepAP214_HArray1OfSecurityClassificationItem) Items() const;
Standard_EXPORT const StepAP214_SecurityClassificationItem& ItemsValue (const Standard_Integer num) const;
Standard_EXPORT Standard_Integer NbItems() const;
DEFINE_STANDARD_RTTIEXT(StepAP214_AppliedSecurityClassificationAssignment,StepBasic_SecurityClassificationAssignment)
protected:
private:
Handle(StepAP214_HArray1OfSecurityClassificationItem) items;
};
#endif // _StepAP214_AppliedSecurityClassificationAssignment_HeaderFile
|
#include<string>
#include<iostream>
#include<fstream>
#include<conio.h>
//#include<stdio.h>
using namespace std;
const string filename="dict.txt";
string InDictionary(string& infile,string dic_word)
{
infile>>dic_word;
return (dic_word);
}
int main()
{
ifstream infile(filename,ios::in);
string usr_word,fin_word;
usr_word=InDictionary(infile,fin_word);
cout<<usr_word<<endl;
getch();
}
|
#ifndef _TPC8407_h
#define _TPC8407_h
#include "Arduino.h"
class TPC8407 {
private:
int fet2, fet4, fet6, fet8;
int vel;
public:
TPC8407(int _fet2, int _fet4, int _fet6, int _fet8, int _vel);
TPC8407(int _fet2, int _fet4, int _fet6, int _fet8);
void forward();
void forward(int pwm);
void back();
void back(int pwm);
void halt();
void brake();
};
#endif
|
int Solution::solve(vector<vector<int> > &A, int B) {
// int solve(vector<vector<int> > &A, int B) {
int N = A.size();
// vector<int> vertical(N,0);
vector<vector<int> > horizontal(N, vector<int> (N, 0));
int sum = 0;
for (int i = 0; i < N; i++)
{
sum = 0;
for (int j = 0; j < N; j++)
{
sum += A[i][j];
horizontal[i][j] = sum;
}
}
//horizontal contains sum of rows prefix
// for(int j = 0; j < N; j++)
// {
// for(int i = 0; i < N; i++)
// {
// cout<<horizontal[j][i]<<" ";
// }
// cout<<endl;
// }
sum = 0;
int maxSum = INT_MIN;
for (int j = 0; j <= N - B; j++)
{
sum = 0;
for (int i = 0; i <= N - B; i++)
{
if (!i)
{
int row = 0;
while (row < B)
{
if (j - 1 < 0)
{
sum += horizontal[i + row][j + B - 1];
}
else
{
sum += horizontal[i + row][j + B - 1] - horizontal[i + row][j - 1];
}
row++;
}
if (sum > maxSum)
maxSum = sum;
continue;
}
if (j - 1 < 0)
{
sum -= horizontal[i - 1][j + B - 1];
sum += horizontal[i + B - 1][j + B - 1];
}
else
{
sum -= horizontal[i - 1][j + B - 1] - horizontal[i - 1][j - 1];
sum += horizontal[i + B - 1][j + B - 1] - horizontal[i + B - 1][j - 1];
}
// int row = 0;
// while(row < B)
// {
// if(j - 1 < 0)
// {
// sum += horizontal[i+row][j+B-1];
// }
// else
// {
// sum += horizontal[i+row][j+B-1] - horizontal[i+row][j-1];
// }
// row++;
// }
if (sum > maxSum)
maxSum = sum;
// sum = 0;
}
}
return maxSum;
}
|
#pragma once
#include "IP.h"
class TCP : public IP
{
private:
WORD m_Sourceport;
WORD m_Destinationport;
DWORD m_Sequencenumber;
DWORD m_Acknowledgementnumber;
BYTE m_TCPheaderlengthUnused;//4+4
BYTE m_UnusedFlags;//2+6
WORD m_Windowsize;
WORD m_Checksum;
WORD m_Urgentpointer;
public:
TCP(void) { ; }
~TCP(void) { ; }
virtual BOOL Write(BYTE *link);
virtual BOOL Read(BYTE *link);
void setSourceport(WORD Sourceport);
void setDestinationport(WORD Destinationport);
void setSequencenumber(DWORD Sequencenumber);
void setAcknowledgementnumber(DWORD Acknowledgementnumber);
void setTCPheaderlengthUnused(BYTE TCPheaderlengthUnused);
void setUnusedFlags(BYTE UnusedFlags);
void setWindowsize(WORD Windowsize);
void setChecksum(WORD Checksum);
void setUrgentpointer(WORD Urgentpointer);
WORD getSourceport() const;
WORD getDestinationport() const;
DWORD getSequencenumber() const;
DWORD getAcknowledgementnumber() const;
BYTE getTCPheaderlengthUnused() const;
BYTE getUnusedFlags() const;
WORD getWindowsize() const;
WORD getChecksum() const;
WORD getUrgentpointer() const;
};
|
/*
ID: stevenh6
TASK: milk
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
ofstream fout ("milk.out");
ifstream fin ("milk.in");
class Farmer {
public:
int units, ppu;
};
bool compare(Farmer first, Farmer second) {
return first.ppu < second.ppu;
}
int main() {
int N, M;
int cost = 0;
fin >> N >> M;
Farmer farmers[M];
for (int i = 0; i < M; i++) {
fin >> farmers[i].ppu >> farmers[i].units;
}
sort(farmers, farmers + M, compare);
int count = 0;
while (N > 0) {
if (farmers[count].units >= N) {
cost += N * farmers[count].ppu;
N = 0;
} else {
cost += farmers[count].units * farmers[count].ppu;
N -= farmers[count].units;
count++;
}
}
fout << cost << endl;
return 0;
}
|
#include <iostream>
#define N 10
#define P 1000000
long long permute(int d, long long order, bool used[], int pass);
int fac(int n);
int main()
{
bool used[N] = {0};
std::cout << permute(0, 0, used, P) << "\n";
}
long long permute(int d, long long order, bool used[], int pass)
{
for (int i = 0; i < N; i++) {
if (!used[i]) {
if (pass > fac(N-1-d))
pass -= fac(N-1-d);
else {
used[i] = 1;
return permute(d+1, order * 10 + i, used, pass);
}
}
}
return order;
}
int fac(int n)
{
int product = 1;
for (; n > 1; n--)
product *= n;
return product;
}
|
#pragma once
#include <sstream>
#include <asio.hpp>
class StreamBuffer {
public:
class const_iterator {
public:
const_iterator & operator++();
bool operator!=(const const_iterator &) const;
asio::mutable_buffer operator*() const;
};
const_iterator begin() const;
const_iterator end() const;
};
class StreamBufferSequence {
public:
class const_iterator {
public:
const_iterator & operator++();
bool operator!=(const const_iterator &) const;
const StreamBuffer & operator*() const;
};
const_iterator begin() const;
const_iterator end() const;
};
|
// distinct elements in the range [l, r]
struct node{
int val;
int l, r;
node(int a=-1, int b=-1, int c=0){
val=c;l=a;r=b;
}
};
node tree[8600010]; // nlog(n) space = 8600010
int idx=0;
int build(int l, int r){
if(l==r)
return idx++;
int mid = (l+r)/2;
tree[idx].l = build(l, mid);
tree[idx].r = build(mid+1, r);
return idx++;
}
int update(int l, int r, int root, int e, int o){
int plus=0;
if((l>e or r<e) and (l>o or r<o or o==-1))
return root;
if(l<=e and e<=r) plus++;
if(l<=o and o<=r and o!=-1) plus--;
if(l==e and r==e){
tree[idx]=node(-1, -1, 1);
return idx++;
}
if(l==o and r==o){
tree[idx]=node(-1, -1, 0);
return idx++;
}
int mid = (l+r)/2;
tree[idx]=node(update(l, mid, tree[root].l, e, o),
update(mid+1, r, tree[root].r, e, o), tree[root].val+plus);
return idx++;
}
int query(int a, int b, int l, int r, int root){
if(l>b or r<a)
return 0;
if(l<=a and b<=r)
return tree[root].val;
int mid = (a+b)/2;
return query(a, mid, l, r, tree[root].l) + query(mid+1, b, l, r, tree[root].r);
}
int main()
{sws;
int n, m, a, b;
int v[MAX], aux[MAX];
int root[MAX];
cin >> n >> m;
for(int i=0;i<n;i++){
cin >> v[i]; aux[i]=v[i];
}
sort(v, v+n);
map<int, int> comp;
for(int i=0, j=0;i<n;i++)
if(i==0 or v[i]!=v[i-1])
comp[v[i]]=j++;
root[0]=build(0, n-1);
int last[MAX];
memset(last, -1, sizeof(last));
for(int i=0;i<n;i++){
root[i+1] = update(0, n-1, root[i], i, last[comp[aux[i]]]);
last[comp[aux[i]]]=i;
}
for(int i=0;i<m;i++){
cin >> a >> b;
cout << query(0, n-1, a-1, n-1, root[b]) << endl;
}
return 0;
}
|
// Player.cpp
#include "provided.h"
#include "support.h"
using namespace std;
class HumanPlayerImpl
{
public:
int chooseMove(const Scaffold& s, int N, int color);
};
class BadPlayerImpl
{
public:
int chooseMove(const Scaffold& s, int N, int color);
};
class SmartPlayerImpl
{
public:
int chooseMove(const Scaffold& s, int N, int color);
};
int HumanPlayerImpl::chooseMove(const Scaffold& s, int N, int color)
{
if (N <= 0 || (color != RED && color != BLACK))
{
exit(1);
}
int move;
int open = 0;
do
{
//enter move after prompt, loops if not valid
cout << "Enter a move: ";
cin >> move;
for (int i = s.levels(); i > 0; i--)
{
if (s.checkerAt(move, i) == VACANT)
{
open = 1;
break;
}
}
}
while (move <= 0 || move > s.cols() || open == 0);
return move;
}
int BadPlayerImpl::chooseMove(const Scaffold& s, int N, int color)
{
if (N <= 0 || (color != RED && color != BLACK))
{
exit(1);
}
int move;
int open = 0;
//set seed for rand() function
srand(unsigned(time(NULL)));
do
{
//pick random move between 1 and # of columns, loops until valid
move = (rand() % s.cols()) + 1;
for (int i = s.levels(); i > 0; i--)
{
if (s.checkerAt(move, i) == VACANT)
{
open = 1;
break;
}
}
}
while (move <= 0 || move > s.cols() || open == 0);
return move;
}
//evaluates board state (rating function)
int evaluate(const Scaffold& s, int N, int color, int lastcolumn)
{
int n1 = 0;
int n2 = 0;
int lastlevel = 0;
for (int i = s.levels(); i >= 1; i--)
{
if (s.checkerAt(lastcolumn, i) != VACANT)
{
//identifies which level last move was on
lastlevel = i;
break;
}
}
//checks for connect N from W to E and sets score if possible
for (int i = -N+1; i < N; i++)
{
if (lastcolumn+i > 0 && lastcolumn+i <= s.cols() && lastlevel > 0 && lastlevel <= s.levels())
{
if (s.checkerAt(lastcolumn+i, lastlevel) == color)
{
n1++;
n2 = 0;
if (n1 == N)
{
return (1000+s.numberEmpty());
}
}
else if (s.checkerAt(lastcolumn+i, lastlevel) == oppositeColor(color))
{
n2++;
n1 = 0;
if (n2 == N)
{
return -(1000+s.numberEmpty());
}
}
else
{
n1 = 0;
n2 = 0;
}
}
else
{
n1 = 0;
n2 = 0;
}
}
n1 = 0;
n2 = 0;
//checks for connect N from S to N and sets score if possible
for (int i = -N+1; i < N; i++)
{
if (lastcolumn > 0 && lastcolumn <= s.cols() && lastlevel+i > 0 && lastlevel+i <= s.levels())
{
if (s.checkerAt(lastcolumn, lastlevel+i) == color)
{
n1++;
n2 = 0;
if (n1 == N)
{
return (1000+s.numberEmpty());
}
}
else if (s.checkerAt(lastcolumn, lastlevel+i) == oppositeColor(color))
{
n2++;
n1 = 0;
if (n2 == N)
{
return -(1000+s.numberEmpty());
}
}
else
{
n1 = 0;
n2 = 0;
}
}
else
{
n1 = 0;
n2 = 0;
}
}
n1 = 0;
n2 = 0;
//checks for connect N from SW to NE and sets score if possible
for (int i = -N+1; i < N; i++)
{
if (lastcolumn+i > 0 && lastcolumn+i <= s.cols() && lastlevel+i > 0 && lastlevel+i <= s.levels())
{
if (s.checkerAt(lastcolumn+i, lastlevel+i) == color)
{
n1++;
n2 = 0;
if (n1 == N)
{
return (1000+s.numberEmpty());
}
}
else if (s.checkerAt(lastcolumn+i, lastlevel+i) == oppositeColor(color))
{
n2++;
n1 = 0;
if (n2 == N)
{
return -(1000+s.numberEmpty());
}
}
else
{
n1 = 0;
n2 = 0;
}
}
else
{
n1 = 0;
n2 = 0;
}
}
n1 = 0;
n2 = 0;
//checks for connect N from NW to SE and sets score if possible
for (int i = -N+1; i < N; i++)
{
if (lastcolumn+i > 0 && lastcolumn+i <= s.cols() && lastlevel-i > 0 && lastlevel-i <= s.levels())
{
if (s.checkerAt(lastcolumn+i, lastlevel-i) == color)
{
n1++;
n2 = 0;
if (n1 == N)
{
return (1000+s.numberEmpty());
}
}
else if (s.checkerAt(lastcolumn+i, lastlevel-i) == oppositeColor(color))
{
n2++;
n1 = 0;
if (n2 == N)
{
return -(1000+s.numberEmpty());
}
}
else
{
n1 = 0;
n2 = 0;
}
}
else
{
n1 = 0;
n2 = 0;
}
}
n1 = 0;
n2 = 0;
//if no moves left return 0 for tie
if (s.numberEmpty() == 0)
{
return 0;
}
//return -10000 indicating game not over
return -10000;
}
//minimax implementation to determine optimal move
vector<int> determineBestMove(AlarmClock& ac, Scaffold& s, int N, int color, int mod)
{
bool valid;
vector<int> rating;
vector<int> eval;
map<int,int> moves;
map<int,int>::iterator it;
int best;
int turn;
int stop = false;
//identifies whose turn it is throughout recursion
if (mod % 2 == 0)
{
turn = color;
}
else
{
turn = oppositeColor(color);
}
//defaults first move to center of board
if (s.numberEmpty() == s.cols()*s.levels())
{
return {0,s.cols()/2};
}
for (int i = 1; i <= s.cols(); i++)
{
valid = s.makeMove(i, color);
if (valid == true)
{
//limits move to 10 seconds
if (ac.timedOut() == false)
{
//if move can be made evaluate board or traverse down tree
eval = {evaluate(s, N, turn, i),i};
if (eval[0] == -10000)
{
eval = determineBestMove(ac, s, N, oppositeColor(color), mod+1);
}
}
else
{
eval = {0,i};
stop = true;
}
//add score to vector and corresponding move to map, undo the move
rating.push_back(eval[0]);
moves[eval[0]] = i;
s.undoMove();
if (stop == true)
{
cerr << "Timed Out!" << endl;
break;
}
}
}
//min or max from vector depending on the turn
if (turn == color)
{
best = *max_element(rating.begin(), rating.end());
}
else
{
best = *min_element(rating.begin(), rating.end());
}
//find corresponding move in map and return both values in vector
it = moves.find(best);
return {best, it->second};
}
int SmartPlayerImpl::chooseMove(const Scaffold& s, int N, int color)
{
if (N <= 0 || (color != RED && color != BLACK))
{
exit(1);
}
AlarmClock ac(9900);
vector<int> move;
//make copy of Scaffold bc of const modifier
Scaffold copy = s;
move = determineBestMove(ac, copy, N, color, 0);
return move[1];
}
//******************** Player derived class functions *************************
// These functions simply delegate to the Impl classes' functions.
// You probably don't want to change any of this code.
HumanPlayer::HumanPlayer(string nm)
: Player(nm)
{
m_impl = new HumanPlayerImpl;
}
HumanPlayer::~HumanPlayer()
{
delete m_impl;
}
int HumanPlayer::chooseMove(const Scaffold& s, int N, int color)
{
return m_impl->chooseMove(s, N, color);
}
BadPlayer::BadPlayer(string nm)
: Player(nm)
{
m_impl = new BadPlayerImpl;
}
BadPlayer::~BadPlayer()
{
delete m_impl;
}
int BadPlayer::chooseMove(const Scaffold& s, int N, int color)
{
return m_impl->chooseMove(s, N, color);
}
SmartPlayer::SmartPlayer(string nm)
: Player(nm)
{
m_impl = new SmartPlayerImpl;
}
SmartPlayer::~SmartPlayer()
{
delete m_impl;
}
int SmartPlayer::chooseMove(const Scaffold& s, int N, int color)
{
return m_impl->chooseMove(s, N, color);
}
|
#ifndef HUMANA_HPP
# define HUMANA_HPP
# include <string>
# include <iostream>
# include "Weapon.hpp"
class HumanA
{
private:
const std::string name_;
const Weapon &weapon_;
HumanA();
public:
void attack(void) const;
HumanA(const std::string &name, const Weapon &weapon);
~HumanA();
};
#endif
|
/*
* TMenuPopupBox.cpp
*
* Created on: May 26, 2017
* Author: Alex
*/
#include "TMenuPopupBox.h"
#include <efl_extension.h>
void popup_close_cb(void *data, Evas_Object *obj, void *event_info);
TMenuPopupBox::TMenuPopupBox(std::vector<const char*> buttonList):TPopupBox() {
Evas_Object *btn;
Evas_Object *box;
elm_popup_align_set(myPopup,ELM_NOTIFY_ALIGN_FILL, 1.0);
evas_object_size_hint_weight_set(myPopup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
eext_object_event_callback_add(myPopup, EEXT_CALLBACK_BACK, popup_close_cb, this);
eext_object_event_callback_add(myPopup, EEXT_CALLBACK_MORE, popup_close_cb, this);
evas_object_smart_callback_add(myPopup, "block,clicked", popup_close_cb, this);
/* box */
box = elm_box_add(myPopup);
evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_box_padding_set(box, 16, 16);
elm_box_pack_end(box, evasRectangleAdd());
int tag = 1;
for (const char* title : buttonList) {
btn = elmButtonAdd(title, "default", tag++);
evas_object_size_hint_weight_set(btn, 0.5, EVAS_HINT_EXPAND);
evas_object_size_hint_min_set(btn, 300, 80);
evas_object_size_hint_align_set(btn, 0.5, 0.5);
evas_object_show(btn);
elm_box_pack_end(box, btn);
}
elm_box_pack_end(box, evasRectangleAdd());
evas_object_size_hint_min_set(box, 350, 192);
elm_object_content_set(myPopup, box);
}
TMenuPopupBox::~TMenuPopupBox() {
// TODO Auto-generated destructor stub
}
Evas_Object * TMenuPopupBox::evasRectangleAdd(){
Evas_Object *rect = evas_object_rectangle_add((Evas *)myPopup);
evas_object_color_set(rect, 200, 0, 0, 255);
evas_object_size_hint_weight_set(rect, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(rect, EVAS_HINT_FILL, EVAS_HINT_FILL);
evas_object_show(rect);
return rect;
}
|
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char marca[40]; //Marca studentului
char model[40]; //Model studentului
char origine[40]; //Originea aleasa
int anu; //anul inmatricularii
float pret;
};
struct Person *Person_insert(struct Person *who,int n)
{
who = malloc(sizeof(struct Person));
assert(who != NULL);
if(*n<=100){
for(i=0;i<*n;i++){
printf("\n****************************************\n\n");
printf("Introdu datele masinii %d\n",i+1);
printf("Marca: ");
scanf("%s",a->marca);
printf("Model: ");
scanf("%s",a->model);
printf("Originea: ");
scanf("%s",a->origine);
printf("Anul de productie: ");
scanf("%d",a->anu);
printf("Pretul($): ");
scanf("%f",a->pret);
}
}else{
system("cls");
printf("\aNumarul introdus depaseste marimea maxim a tabloului\n");
system("pause");
}
return a;
}
void Person_destroy(struct Person *who)
{
assert(who != NULL);
free(who->name);
free(who);
}
void Person_print(struct Person *who)
{
printf("Name: %s\n", who->name);
printf("\tAge: %d\n", who->age);
printf("\tHeight: %d\n", who->height);
printf("\tWeight: %d\n", who->weight);
}
int main(int argc, char *argv[])
{
// make two people structures
struct Person *who;
// print them out and where they are in memory
printf("Joe is at memory location %p:\n", joe);
Person_print(joe);
printf("Frank is at memory location %p:\n", frank);
Person_print(frank);
// make everyone age 20 years and print them again
joe->age += 20;
joe->height -= 2;
joe->weight += 40;
Person_print(joe);
frank->age += 20;
frank->weight += 20;
Person_print(frank);
// destroy them both so we clean up
Person_destroy(joe);
Person_destroy(frank);
return 0;
}
|
/*
* Copyright (c) 2015-2020 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <forward_list>
#include <functional>
#include <iterator>
#include <list>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/sorters/merge_sorter.h>
#include <testing-tools/distributions.h>
TEST_CASE( "merge_sorter tests", "[merge_sorter]" )
{
// Collection to sort
std::vector<int> vec; vec.reserve(80);
auto distribution = dist::shuffled{};
distribution(std::back_inserter(vec), 80, 0);
SECTION( "sort with random-access iterable" )
{
cppsort::merge_sort(vec);
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
}
SECTION( "sort with random-access iterable and compare" )
{
cppsort::merge_sort(vec, std::greater<>{});
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
}
SECTION( "sort with random-access iterators" )
{
cppsort::merge_sort(std::begin(vec), std::end(vec));
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
}
SECTION( "sort with random-access iterators and compare" )
{
cppsort::merge_sort(std::begin(vec), std::end(vec), std::greater<>{});
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
}
SECTION( "sort with bidirectional iterators" )
{
std::list<int> li(std::begin(vec), std::end(vec));
cppsort::merge_sort(std::begin(li), std::end(li));
CHECK( std::is_sorted(std::begin(li), std::end(li)) );
}
SECTION( "sort with bidirectional iterators and compare" )
{
std::list<int> li(std::begin(vec), std::end(vec));
cppsort::merge_sort(std::begin(li), std::end(li), std::greater<>{});
CHECK( std::is_sorted(std::begin(li), std::end(li), std::greater<>{}) );
}
SECTION( "sort with forward iterators" )
{
std::forward_list<int> li(std::begin(vec), std::end(vec));
cppsort::merge_sort(std::begin(li), std::end(li));
CHECK( std::is_sorted(std::begin(li), std::end(li)) );
}
SECTION( "sort with forward iterators and compare" )
{
std::forward_list<int> li(std::begin(vec), std::end(vec));
cppsort::merge_sort(std::begin(li), std::end(li), std::greater<>{});
CHECK( std::is_sorted(std::begin(li), std::end(li), std::greater<>{}) );
}
}
|
$NetBSD$
* don't use kqueue on netbsd since it misses EVFILT_USER
--- vio/viosocket.cc.orig 2019-12-09 19:53:17.000000000 +0000
+++ vio/viosocket.cc
@@ -68,6 +68,10 @@
#include "mysql/psi/mysql_socket.h"
+#ifdef __NetBSD__
+#undef HAVE_KQUEUE
+#endif
+
int vio_errno(Vio *vio MY_ATTRIBUTE((unused))) {
/* These transport types are not Winsock based. */
#ifdef _WIN32
|
#include <iostream>
using namespace std;
int main() {
int q;
cin >> q;
for (int t = 0; t < q; ++t) {
int a;
cin >> a;
int k;
for (k = 30; k >= 0; --k) {
if ((a >> k) & 1) break;
}
int ans = (1 << (k + 1)) - 1;
if (a != ans) {
cout << ans << endl;
} else {
// aのa未満で最大の約数が答え
ans = 1;
for (int i = 2; i * i <= a; ++i) {
if (a % i == 0) {
ans = a / i;
break;
}
}
cout << ans << endl;
}
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef DOM_DOMRUNTIME_H
#define DOM_DOMRUNTIME_H
#include "modules/ecmascript/ecmascript.h"
#include "modules/dom/domutils.h"
#include "modules/dom/src/dominternaltypes.h"
#include "modules/doc/documentorigin.h"
#ifdef SVG_DOM
# include "modules/dom/src/domsvg/domsvgenum.h"
#endif // SVG_DOM
class ES_Object;
class EcmaScript_Object;
class FramesDocument;
class DOM_EnvironmentImpl;
class DOM_ProxyEnvironmentImpl;
class DOM_Object;
#ifdef CLIENTSIDE_STORAGE_SUPPORT
class DOM_Storage_OperationCallback;
#endif //CLIENTSIDE_STORAGE_SUPPORT
#ifdef DOM_WEBWORKERS_SUPPORT
class DOM_WebWorker;
#endif // DOM_WEBWORKERS_SUPPORT
#include "modules/url/url2.h"
class DOM_ConstructorInformation
{
public:
DOM_ConstructorInformation(const char *name, unsigned ns, unsigned id)
: name(name),
ns(ns),
id(id)
{
}
const char *name;
unsigned ns:8;
unsigned id:24;
};
class DOM_Runtime : public ES_Runtime
{
private:
DOM_EnvironmentImpl *environment;
DocumentOrigin* origin;
BOOL owns_environment;
DOM_Runtime *cached_target_runtime;
/**< Target runtime in last successful security check where this
runtime was the source runtime. */
DOM_Runtime *cached_source_runtime;
/**< Source runtime in last successful security check where this
runtime was the target runtime. */
void ClearTargetSecurityCheckCache()
{
if (cached_target_runtime)
{
cached_target_runtime->cached_source_runtime = NULL;
cached_target_runtime = NULL;
}
}
void ClearSourceSecurityCheckCache()
{
if (cached_source_runtime)
{
cached_source_runtime->cached_target_runtime = NULL;
cached_source_runtime = NULL;
}
}
public:
static void CacheSecurityCheck(DOM_Runtime *target_runtime, DOM_Runtime *source_runtime)
{
target_runtime->ClearSourceSecurityCheckCache();
source_runtime->ClearTargetSecurityCheckCache();
target_runtime->cached_source_runtime = source_runtime;
source_runtime->cached_target_runtime = target_runtime;
}
static BOOL QuickSecurityCheck(DOM_Runtime *target_runtime, DOM_Runtime *source_runtime)
{
return target_runtime == source_runtime || target_runtime->cached_source_runtime == source_runtime;
}
#include "modules/dom/src/domruntime.h.inc"
/** Important: this enumeration needs to be kept in sync with:
g_DOM_htmlClassNames in domhtml/htmlelem.cpp
g_DOM_htmlPrototypeClassNames in in domhtml/htmlelem.cpp
g_DOM_htmlProperties in domhtml/htmlproperties.cpp
This means the elements must be in the same order in all four
places. You cannot add or remove any elements without
updating all four. */
enum HTMLElementPrototype
{
UNKNOWN_ELEMENT_PROTOTYPE,
HTML_PROTOTYPE,
HEAD_PROTOTYPE,
LINK_PROTOTYPE,
TITLE_PROTOTYPE,
META_PROTOTYPE,
BASE_PROTOTYPE,
ISINDEX_PROTOTYPE,
STYLE_PROTOTYPE,
BODY_PROTOTYPE,
FORM_PROTOTYPE,
SELECT_PROTOTYPE,
OPTGROUP_PROTOTYPE,
OPTION_PROTOTYPE,
INPUT_PROTOTYPE,
TEXTAREA_PROTOTYPE,
BUTTON_PROTOTYPE,
LABEL_PROTOTYPE,
FIELDSET_PROTOTYPE,
LEGEND_PROTOTYPE,
OUTPUT_PROTOTYPE,
DATALIST_PROTOTYPE,
PROGRESS_PROTOTYPE,
METER_PROTOTYPE,
KEYGEN_PROTOTYPE,
ULIST_PROTOTYPE,
OLIST_PROTOTYPE,
DLIST_PROTOTYPE,
DIRECTORY_PROTOTYPE,
MENU_PROTOTYPE,
LI_PROTOTYPE,
DIV_PROTOTYPE,
PARAGRAPH_PROTOTYPE,
HEADING_PROTOTYPE,
QUOTE_PROTOTYPE,
PRE_PROTOTYPE,
BR_PROTOTYPE,
FONT_PROTOTYPE,
HR_PROTOTYPE,
MOD_PROTOTYPE,
#ifdef PARTIAL_XMLELEMENT_SUPPORT // See bug 286692
XML_PROTOTYPE,
#endif // #ifdef PARTIAL_XMLELEMENT_SUPPORT // See bug 286692
ANCHOR_PROTOTYPE,
IMAGE_PROTOTYPE,
OBJECT_PROTOTYPE,
PARAM_PROTOTYPE,
APPLET_PROTOTYPE,
EMBED_PROTOTYPE,
MAP_PROTOTYPE,
AREA_PROTOTYPE,
SCRIPT_PROTOTYPE,
TABLE_PROTOTYPE,
TABLECAPTION_PROTOTYPE,
TABLECOL_PROTOTYPE,
TABLESECTION_PROTOTYPE,
TABLEROW_PROTOTYPE,
TABLECELL_PROTOTYPE,
FRAMESET_PROTOTYPE,
FRAME_PROTOTYPE,
IFRAME_PROTOTYPE,
#ifdef MEDIA_HTML_SUPPORT
MEDIA_PROTOTYPE,
AUDIO_PROTOTYPE,
VIDEO_PROTOTYPE,
SOURCE_PROTOTYPE,
TRACK_PROTOTYPE,
#endif //MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
CANVAS_PROTOTYPE,
#endif // CANVAS_SUPPORT
MARQUEE_PROTOTYPE,
TIME_PROTOTYPE,
HTMLELEMENT_PROTOTYPES_COUNT
};
#ifdef SVG_DOM
/** Important: this enumeration needs to be kept in sync with:
g_DOM_svgObjectPrototypeClassNames in domsvg/domsvgobject.cpp
This means the elements must be in the same order in both places.
You cannot add or remove any elements without updating both. */
enum SVGObjectPrototype
{
SVGNUMBER_PROTOTYPE,
SVGLENGTH_PROTOTYPE,
SVGPOINT_PROTOTYPE,
SVGANGLE_PROTOTYPE,
SVGTRANSFORM_PROTOTYPE,
SVGPATHSEG_PROTOTYPE,
SVGMATRIX_PROTOTYPE,
SVGPAINT_PROTOTYPE,
SVGASPECTRATIO_PROTOTYPE,
SVGCSSPRIMITIVEVALUE_PROTOTYPE,
SVGRECT_PROTOTYPE,
SVGCSSRGBCOLOR_PROTOTYPE,
SVGPATH_PROTOTYPE,
SVGRGBCOLOR_PROTOTYPE,
SVGOBJECT_PROTOTYPES_COUNT
};
/** Important: this enumeration needs to be kept in sync with:
g_DOM_svgElementPrototypeClassNames in domsvg/domsvgelement.cpp
This means the elements must be in the same order in both places.
You cannot add or remove any elements without updating both. */
enum SVGElementPrototype
{
SVG_PROTOTYPE,
SVG_CIRCLE_PROTOTYPE,
SVG_ELLIPSE_PROTOTYPE,
SVG_LINE_PROTOTYPE,
SVG_PATH_PROTOTYPE,
SVG_POLYLINE_PROTOTYPE,
SVG_POLYGON_PROTOTYPE,
SVG_RECT_PROTOTYPE,
SVG_SVG_PROTOTYPE,
SVG_TEXT_PROTOTYPE,
SVG_TEXTCONTENT_PROTOTYPE,
SVG_TSPAN_PROTOTYPE,
SVG_TREF_PROTOTYPE,
SVG_ANIMATE_PROTOTYPE,
SVG_G_PROTOTYPE,
SVG_A_PROTOTYPE,
SVG_SCRIPT_PROTOTYPE,
SVG_MPATH_PROTOTYPE,
SVG_FONT_PROTOTYPE,
SVG_GLYPH_PROTOTYPE,
SVG_MISSINGGLYPH_PROTOTYPE,
SVG_FOREIGN_OBJECT_PROTOTYPE,
SVG_DEFS_PROTOTYPE,
SVG_DESC_PROTOTYPE,
SVG_TITLE_PROTOTYPE,
SVG_SYMBOL_PROTOTYPE,
SVG_USE_PROTOTYPE,
SVG_IMAGE_PROTOTYPE,
SVG_SWITCH_PROTOTYPE,
SVG_LINEARGRADIENT_PROTOTYPE,
SVG_RADIALGRADIENT_PROTOTYPE,
SVG_STOP_PROTOTYPE,
#ifdef SVG_FULL_11
SVG_PATTERN_PROTOTYPE,
SVG_TEXTPATH_PROTOTYPE,
SVG_MARKER_PROTOTYPE,
SVG_VIEW_PROTOTYPE,
SVG_MASK_PROTOTYPE,
SVG_FEFLOOD_PROTOTYPE,
SVG_FEBLEND_PROTOTYPE,
SVG_FECOLORMATRIX_PROTOTYPE,
SVG_FECOMPONENTTRANSFER_PROTOTYPE,
SVG_FECOMPOSITE_PROTOTYPE,
SVG_FECONVOLVEMATRIX_PROTOTYPE,
SVG_FEDIFFUSELIGHTNING_PROTOTYPE,
SVG_FEDISPLACEMENTMAP_PROTOTYPE,
SVG_FEIMAGE_PROTOTYPE,
SVG_FEMERGE_PROTOTYPE,
SVG_FEMORPHOLOGY_PROTOTYPE,
SVG_FEOFFSET_PROTOTYPE,
SVG_FESPECULARLIGHTNING_PROTOTYPE,
SVG_FETILE_PROTOTYPE,
SVG_FETURBULENCE_PROTOTYPE,
SVG_STYLE_PROTOTYPE,
SVG_CLIPPATH_PROTOTYPE,
SVG_FEFUNCR_PROTOTYPE,
SVG_FEFUNCG_PROTOTYPE,
SVG_FEFUNCB_PROTOTYPE,
SVG_FEFUNCA_PROTOTYPE,
SVG_FEDISTANTLIGHT_PROTOTYPE,
SVG_FESPOTLIGHT_PROTOTYPE,
SVG_FEPOINTLIGHT_PROTOTYPE,
SVG_FEMERGENODE_PROTOTYPE,
SVG_FEGAUSSIANBLUR_PROTOTYPE,
SVG_FILTER_PROTOTYPE,
#endif // SVG_FULL_11
#ifdef SVG_TINY_12
SVG_AUDIO_PROTOTYPE,
SVG_VIDEO_PROTOTYPE,
SVG_ANIMATION_PROTOTYPE,
SVG_TEXTAREA_PROTOTYPE,
#endif // SVG_TINY_12
SVGELEMENT_PROTOTYPES_COUNT
};
#endif // SVG_DOM
enum Type
{
TYPE_DOCUMENT,
/**< The main runtime of a document. (A "normal" runtime). */
#ifdef DOM_WEBWORKERS_SUPPORT
TYPE_DEDICATED_WEBWORKER,
/**< A dedicated web worker. */
TYPE_SHARED_WEBWORKER,
/**< A shared web worker. */
#endif // DOM_WEBWORKERS_SUPPORT
#ifdef EXTENSION_SUPPORT
TYPE_EXTENSION_JS
/**< A runtime that is running ExtensionJS with shared access to
a DOM environment. */
#endif // EXTENSION_SUPPORT
}; // Type
public:
DOM_Runtime();
virtual ~DOM_Runtime();
virtual void GCTrace();
URL GetOriginURL() { return origin->security_context; }
/**< Returns the Origin URL that together with the effective domain and other information
in the Origin object decides the security context for a runtime. */
DocumentOrigin *GetMutableOrigin() { return origin; }
/**< Returns the DocumentOrigin object that decides the security context for a runtime. */
OP_STATUS GetSerializedOrigin(TempBuffer &buffer, unsigned flags = DOM_Utils::SERIALIZE_FALLBACK_AS_NULL);
/**< Get a serialized representation of the runtime's (origin) URL.
See DOM_Utils::GetSerializedOrigin() documentation for details
on serialisation.
@param buffer The result buffer.
@param flags Flags, see OriginSerializationFlags. The default value
ensures specification compliance.
@returns OpStatus::OK on success, OpStatus::ERR_NO_MEMORY on OOM. */
OP_STATUS GetDisplayURL(OpString& display_url);
/**< Returns the URL most useful in public messages for this runtime. Typically the origin, but
in case of anonymous/sandboxed runtimes it might be something different.
@param[out] display_url Set to the url or left empty if there is no reasonable url.
@returns OpStatus::OK normally, OpStatus::ERR_NO_MEMORY on OOM. */
const uni_char *GetDomain();
void GetDomain(const uni_char **domain, URLType *type, int *port);
OP_STATUS SetDomainChecked(const uni_char *domain);
/**< Check if 'domain' is a valid domain (proper suffix of current domain)
and set it if it is. Returns OpStatus::ERR if the domain was not
valid and OpStatus::ERR_NO_MEMORY on OOM. */
BOOL HasOverriddenDomain();
/**< Returns TRUE if the current domain is not from the document's URL,
but is set for instance by assigning document.domain. (In fact, TRUE
if the domain has been changed by a call to SetDomainChecked.) */
OP_STATUS Construct(Type type, DOM_EnvironmentImpl *environment, const char* classname, DocumentOrigin* doc_origin, BOOL owns_environment = TRUE, ES_Runtime *parent_runtime = NULL);
#ifdef DOM_WEBWORKERS_SUPPORT
OP_STATUS Construct(Type type, DOM_EnvironmentImpl *environment, URL base_worker_url);
#endif // DOM_WEBWORKERS_SUPPORT
void Detach();
void Reset();
DOM_EnvironmentImpl *GetEnvironment() { return environment; }
BOOL HasSharedEnvironment() { return !owns_environment; }
/**< Returns TRUE if this runtime runs in the context of another environment.
At present, only so for isolated userJS/extension runtimes. */
ES_Object *GetPrototype(Prototype prototype);
void RecordConstructor(Prototype prototype, DOM_Object* constructor);
ES_Object *GetHTMLElementPrototype(HTMLElementPrototype prototype);
void RecordHTMLElementConstructor(HTMLElementPrototype prototype, DOM_Object* constructor);
#ifdef SVG_DOM
ES_Object* GetSVGObjectPrototype(SVGObjectPrototype prototype);
ES_Object *GetSVGElementPrototype(SVGElementPrototype prototype, DOM_SVGElementInterface ifs);
#endif // SVG_DOM
#ifdef SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
void SetRelaxedLoadSaveSecurity(BOOL value) { relaxed_load_save_security = value; }
BOOL HasRelaxedLoadSaveSecurity() { return relaxed_load_save_security; }
#endif // SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
Link *AddAccessedProxyEnvironment(DOM_ProxyEnvironmentImpl *environment, Link *group);
enum ConstructorTableNamespace
{
CTN_BASIC,
CTN_HTMLELEMENT,
CTN_SVGELEMENT,
CTN_SVGOBJECT
};
static void InitializeConstructorsTableL(OpString8HashTable<DOM_ConstructorInformation> *table, unsigned &longest_name);
const char *GetConstructorName(Prototype prototype);
ES_Object *CreateConstructorL(DOM_Object *target, const char *name, ConstructorTableNamespace ns, unsigned id);
OP_STATUS CreateConstructor(ES_Value *value, DOM_Object *target, const char *name, unsigned ns, unsigned id);
#ifdef ECMASCRIPT_DEBUGGER
// Overriding ES_Runtime
virtual const char *GetDescription() const;
virtual OP_STATUS GetWindows(OpVector<Window> &windows);
virtual OP_STATUS GetURLDisplayName(OpString &str);
# ifdef EXTENSION_SUPPORT
virtual OP_STATUS GetExtensionName(OpString &extension_name);
# endif // EXTENSION_SUPPORT
#endif // ECMASCRIPT_DEBUGGER
private:
OP_STATUS PreparePrototype(ES_Object *object, Prototype type);
const char *GetPrototypeClass(Prototype prototype);
const char *GetHTMLPrototypeClass(HTMLElementPrototype prototype);
#ifdef SVG_DOM
const char *GetSVGObjectPrototypeClass(SVGObjectPrototype prototype);
const char *GetSVGElementPrototypeClass(SVGElementPrototype prototype);
#endif // SVG_DOM
ES_Object *SetPrototype(DOM_Object *&prototype, ES_Object *prototype_prototype, const char *object_class);
/**< If object_class is NULL, 'Object' will be used. */
/**< Traps and calls PreparePrototypeL(). */
void PreparePrototypeL(ES_Object *object, Prototype type);
/**< Autogenerated from prototypes.txt. Lives in domprototypes.cpp. */
ES_Object **prototypes;
DOM_Object **constructors;
#ifdef SVG_DOM
ES_Object **svgobject_prototypes;
ES_Object **svgelement_prototypes;
#endif // SVG_DOM
ES_Object **htmlelement_prototypes;
DOM_Object **htmlelement_constructors;
#ifdef SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
BOOL relaxed_load_save_security;
#endif // SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
class AccessedProxyEnvironment
: public Link
{
public:
AccessedProxyEnvironment(DOM_ProxyEnvironmentImpl *environment, Link *group)
: environment(environment),
group(group)
{
}
DOM_ProxyEnvironmentImpl *environment;
Link *group;
};
Head accessed_proxy_environments;
Type type;
};
#endif // DOM_DOMRUNTIME_H
|
// 消息处理对象的基类模板,需要关注消息总线的类可以以该模板类为基类,这样就能
// 以简单的函数调用和相同的形式将自己的成员函数注册到消息总线
//
#ifndef MSGBUS_HANDLER_BASE_H
#define MSGBUS_HANDLER_BASE_H
#include "threadpool.h"
#include "msgbus_interface.h"
#include "lock.hpp"
#include <map>
#include <boost/unordered_map.hpp>
#include <string>
#include <boost/bind.hpp>
#include <boost/shared_array.hpp>
#include <boost/enable_shared_from_this.hpp>
namespace NetMsgBus
{
#define DECLARE_SP_PTR(T) typedef boost::shared_ptr<T> T##Ptr
class MsgHandlerMgr;
template <class T> class MsgHandler: public IMsgHandler, public boost::enable_shared_from_this< T >
{
protected:
MsgHandler(){}
public:
friend class MsgHandlerMgr;
typedef bool (T::*HandlerT)(const std::string&, MsgBusParam&, bool&);
typedef bool (T::*ConstHandlerT)(const std::string&, MsgBusParam&, bool&) const;
struct HandlerTWrapper
{
HandlerTWrapper()
:type(0),
handler_func(NULL)
{
}
HandlerTWrapper(int ltype, HandlerT lhandlerfunc)
:type(ltype),
handler_func(lhandlerfunc)
{
}
// 消息处理函数的调用类型,0代表在消息总线的同步消息处理线程中调用(和SendMsg的调用线程一致)
// 1-代表该处理函数是一个耗时函数,因此会在放到线程池中调用
// 2-stand for this handler can be called safely in any thread.
// 3-代表该函数是一个UI函数,需要在UI线程中处理
//
int type;
HandlerT handler_func;
};
// 消息处理函数集合类型
//typedef typename std::map< std::string, HandlerTWrapper > HandlerContainerT;
typedef typename boost::unordered_map< std::string, HandlerTWrapper > HandlerContainerT;
// 删除该对象在消息总线上注册的所有函数
virtual ~MsgHandler()
{
RemoveAllHandlers();
}
// 由消息总线调用的消息处理函数接口,对象中的所有注册过的函数都在这里进行相应的消息函数调用
bool OnMsg(const std::string& msgid, MsgBusParam& param, bool& is_continue)
{
HandlerTWrapper hwrapper;
{
core::common::locker_guard guard(handlers_lock_);
typename HandlerContainerT::iterator it = all_handlers_.find(msgid);
if( it == all_handlers_.end() )
{
return false;
}
hwrapper = it->second;
}
is_continue = true;
bool result = false;
{
if(hwrapper.type == 0 || hwrapper.type == 2)
{
if(hwrapper.handler_func != NULL)
result = (dynamic_cast<T*>(this)->*(hwrapper.handler_func))(msgid, param, is_continue);
}
else if(hwrapper.type == 1)
{// long time function, to avoid others can not going on, we put it into threadpool.
result = threadpool::queue_work_task(boost::bind(hwrapper.handler_func, this->shared_from_this(), msgid, param, is_continue), 0);
}
else if(hwrapper.type == 3)
{// UI event, let the ui thread to handle the function
// ::SendMessage(m_hWnd, WM_CALL_MYFUNC, boost::bind(it->second.handler_func, this, msgid, param, is_continue), NULL );
}
}
return result;
}
void AddHandler(const std::string& msgid, HandlerT handler_func, int type)
{
HandlerTWrapper hwrapper(type, handler_func);
{
core::common::locker_guard guard(handlers_lock_);
all_handlers_[msgid] = hwrapper;
}
RegisterMsg(msgid, this->shared_from_this(), type != 2);
}
void RemoveHandler(const std::string& msgid)
{
{
core::common::locker_guard guard(handlers_lock_);
all_handlers_.erase(msgid);
}
UnRegisterMsg(msgid, dynamic_cast<IMsgHandler*>(this));
}
// 从消息总线删除所有的注册消息
void RemoveAllHandlers()
{
core::common::locker_guard guard(handlers_lock_);
typename HandlerContainerT::const_iterator it = all_handlers_.begin();
while(it != all_handlers_.end())
{
UnRegisterMsg(it->first, dynamic_cast<IMsgHandler*>(this));
++it;
}
all_handlers_.clear();
}
private:
HandlerContainerT all_handlers_;
core::common::locker handlers_lock_;
};
}
#endif
|
/**
* @file testCommandMap.cxx
* @author Krzysztof Ciba (Krzysztof.Ciba@NOSPAMagh.edu.pl)
* @date 23/11/2006
* @brief Just a test program for CommandMap interface
*/
// includes from standard libraries
#include <string>
#include <iostream>
// local includes
#ifndef DUMMYGEN_EXTERN_C_H
#include "DUMMYGEN_extern_C.h"
#endif
#ifndef DUMMY_MAP_H
#include "DUMMYGEN_map.h"
#endif
#ifndef COMMAND_H
#include "Command.h"
#endif
#ifndef CLUTILS_H
#include "CLUtils.h"
#endif
extern "C" {
void init_();
void print_i1_();
void print_i2_();
void print_d1_();
void print_d1_();
void print_planet_();
void print_rtab_();
void print_itab_();
void print_dtab_();
void print_day_();
void writeout_();
};
// namespaces used
using namespace std;
using namespace CLUE;
ostream& cpp( ostream& stream )
{
stream << " C++ ";
return stream;
}
int main() {
cout << cpp << "testCommandMap: initalize Fortran 77 common..." << endl;
init_();
writeout_();
DUMMYGEN_LUT dlut;
cout << cpp << dlut << endl;
try {
string cname("i1");
cout << cpp
<< "testCommandMap: testing command getter from CommandMap for command name: "
<< cname << endl;
CommandBase* I1 = dlut.command(cname);
Command<int>* icmd = dynamic_cast< Command<int>* >( I1 );
print_i1_();
cout << (*icmd) << endl;
icmd->set(999);
print_i1_();
vector<string> cms; //< CoMmandStrings - sorry CMS :)
cout << cpp << "testCommandMap: testing parsing of command vector..." << endl;
print_i1_();
print_i2_();
print_rtab_();
print_planet_();
print_day_();
cms.push_back("I1 123");
cms.push_back("I2 321");
cms.push_back("rtab 2 0.999");
cms.push_back("Planet VENUS");
cms.push_back("DAY 1 WEE");
cms.push_back("DAY 7 END");
cms.push_back("FOO bar baz");
vector<string>::iterator it;
unsigned int i = 1;
cout << cpp << "testCommandMap: commands to parse are:" << endl;
for (it = cms.begin(); it != cms.end(); ++it, ++i)
cout << cpp << "[" << i << "] " << (*it) << endl;
cout << cpp << "testCommandMap: invoking CommandMap parse..." << endl;
dlut.parse( cms );
cout << cpp << "testCommandMap: checking the new values..." << endl;
print_i1_();
print_i2_();
print_rtab_();
print_planet_();
print_day_();
}
catch ( CLUException& e ) {
cout << e.what() << endl;
}
return 0;
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <cassert>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
inline LightSceneItem::LightType LightSceneItem::getLightType() const
{
return static_cast<LightType>(static_cast<int>(mPackedShaderData.lightType));
}
inline void LightSceneItem::setLightType(LightType lightType)
{
mPackedShaderData.lightType = static_cast<float>(lightType);
// Sanity checks
assert(lightType == LightType::DIRECTIONAL || mPackedShaderData.radius > 0.0f);
assert(lightType != LightType::DIRECTIONAL || 0.0f == mPackedShaderData.radius);
}
inline void LightSceneItem::setLightTypeAndRadius(LightType lightType, float radius)
{
mPackedShaderData.lightType = static_cast<float>(lightType);
mPackedShaderData.radius = radius;
// Sanity checks
assert(lightType == LightType::DIRECTIONAL || mPackedShaderData.radius > 0.0f);
assert(lightType != LightType::DIRECTIONAL || 0.0f == mPackedShaderData.radius);
}
inline const glm::vec3& LightSceneItem::getColor() const
{
return mPackedShaderData.color;
}
inline void LightSceneItem::setColor(const glm::vec3& color)
{
mPackedShaderData.color = color;
// Sanity checks
assert(mPackedShaderData.color.r >= 0.0f && mPackedShaderData.color.g >= 0.0f && mPackedShaderData.color.b >= 0.0f);
}
inline float LightSceneItem::getRadius() const
{
return mPackedShaderData.radius;
}
inline void LightSceneItem::setRadius(float radius)
{
mPackedShaderData.radius = radius;
// Sanity checks
assert(mPackedShaderData.lightType == static_cast<float>(LightType::DIRECTIONAL) || mPackedShaderData.radius > 0.0f);
assert(mPackedShaderData.lightType != static_cast<float>(LightType::DIRECTIONAL) || 0.0f == mPackedShaderData.radius);
}
inline float LightSceneItem::getInnerAngle() const
{
return mInnerAngle;
}
inline void LightSceneItem::setInnerAngle(float innerAngle)
{
mInnerAngle = innerAngle;
// Derive data
mPackedShaderData.innerAngle = std::cos(mInnerAngle);
// Sanity checks
assert(mInnerAngle >= 0.0f);
assert(mInnerAngle < mOuterAngle);
}
inline float LightSceneItem::getOuterAngle() const
{
return mOuterAngle;
}
inline void LightSceneItem::setOuterAngle(float outerAngle)
{
mOuterAngle = outerAngle;
// Derive data
mPackedShaderData.outerAngle = std::cos(mOuterAngle);
// Sanity checks
assert(mOuterAngle < glm::radians(90.0f));
assert(mInnerAngle < mOuterAngle);
}
inline void LightSceneItem::setInnerOuterAngle(float innerAngle, float outerAngle)
{
mInnerAngle = innerAngle;
mOuterAngle = outerAngle;
// Derive data
mPackedShaderData.innerAngle = std::cos(mInnerAngle);
mPackedShaderData.outerAngle = std::cos(mOuterAngle);
// Sanity checks
assert(mInnerAngle >= 0.0f);
assert(mOuterAngle < glm::radians(90.0f));
assert(mInnerAngle < mOuterAngle);
}
inline float LightSceneItem::getNearClipDistance() const
{
return mPackedShaderData.nearClipDistance;
}
inline void LightSceneItem::setNearClipDistance(float nearClipDistance)
{
mPackedShaderData.nearClipDistance = nearClipDistance;
// Sanity check
assert(mPackedShaderData.nearClipDistance >= 0.0f);
}
inline bool LightSceneItem::isVisible() const
{
return (mPackedShaderData.visible != 0);
}
//[-------------------------------------------------------]
//[ Public RendererRuntime::ISceneItem methods ]
//[-------------------------------------------------------]
inline SceneItemTypeId LightSceneItem::getSceneItemTypeId() const
{
return TYPE_ID;
}
inline void LightSceneItem::setVisible(bool visible)
{
mPackedShaderData.visible = static_cast<uint32_t>(visible);
}
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
inline LightSceneItem::LightSceneItem(SceneResource& sceneResource) :
ISceneItem(sceneResource),
mInnerAngle(0.0f),
mOuterAngle(0.1f)
{
setInnerOuterAngle(glm::radians(40.0f), glm::radians(50.0f));
}
inline LightSceneItem::~LightSceneItem()
{
// Nothing here
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
|
/*
* @lc app=leetcode.cn id=80 lang=cpp
*
* [80] 删除排序数组中的重复项 II
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n==0)return 0;
int slow= 0;
int fast = 1;
int cnt = 1;
while (fast < n)
{
if(nums[slow]!=nums[fast]){
slow++;
nums[slow] = nums[fast];
fast++;
cnt = 1;
}else{
cnt++;
if(cnt<=2){
slow++;
nums[slow] = nums[fast];
fast++;
}else{
fast++;
}
}
}
return slow+1;
}
};
// @lc code=end
|
// Copyright (c) 2013-2015 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config.hpp>
#if defined(PIKA_HAVE_MODULE_MPI_BASE)
# include <pika/concurrency/spinlock.hpp>
# include <pika/modules/runtime_configuration.hpp>
# include <pika/mpi_base/mpi.hpp>
# include <cstdlib>
# include <string>
# include <pika/config/warnings_prefix.hpp>
namespace pika { namespace util {
struct PIKA_EXPORT mpi_environment
{
static bool check_mpi_environment(runtime_configuration const& cfg);
static int init(
int* argc, char*** argv, const int required, const int minimal, int& provided);
static void init(int* argc, char*** argv, runtime_configuration& cfg);
static void finalize();
static bool enabled();
static bool multi_threaded();
static bool has_called_init();
static int rank();
static int size();
static MPI_Comm& communicator();
static std::string get_processor_name();
struct PIKA_EXPORT scoped_lock
{
scoped_lock();
scoped_lock(scoped_lock const&) = delete;
scoped_lock& operator=(scoped_lock const&) = delete;
~scoped_lock();
void unlock();
};
struct PIKA_EXPORT scoped_try_lock
{
scoped_try_lock();
scoped_try_lock(scoped_try_lock const&) = delete;
scoped_try_lock& operator=(scoped_try_lock const&) = delete;
~scoped_try_lock();
void unlock();
bool locked;
};
using mutex_type = pika::concurrency::detail::spinlock;
private:
static mutex_type mtx_;
static bool enabled_;
static bool has_called_init_;
static int provided_threading_flag_;
static MPI_Comm communicator_;
static int is_initialized_;
};
}} // namespace pika::util
# include <pika/config/warnings_suffix.hpp>
#else
# include <pika/modules/runtime_configuration.hpp>
# include <pika/config/warnings_prefix.hpp>
namespace pika { namespace util {
struct PIKA_EXPORT mpi_environment
{
static bool check_mpi_environment(runtime_configuration const& cfg);
};
}} // namespace pika::util
# include <pika/config/warnings_suffix.hpp>
#endif
|
#include "manager_controller.h"
#include "Registration/RegisterManager.h"
#include "Registration/RegisterSendKeyManager.h"
#include "Auth/LoginManager.h"
#include "Auth/LoginSendKeyManager.h"
#include "iostream"
namespace m2 {
namespace server {
ManagerController::ManagerController(Database *database): db(database)
{
}
responsePtr ManagerController::doProcess(requestPtr request)
{
responsePtr answer = std::make_shared<HttpResponse>();
std::string uri = request->getHeader().uri_;
std::string data = request->getData();
std::string response;
HttpResponse::Code code = HttpResponse::Code::OK;
// http://localhost:8282/some/command1
if (uri == "/user/register/sendKey") {
RegisterSendKeyManager sendKeyManager(db);
code = sendKeyManager.doAction(data, response);
std::cout<<"REQUEST: "<<response<<std::endl;
}
else if (uri == "/user/register") {
RegisterManager registerManager(db);
code = registerManager.doAction(data, response);
}
else if (uri == "/user/auth/sendKey") {
LoginSendKeyManager sendKeyManager(db);
code = sendKeyManager.doAction(data, response);
}
else if (uri == "/user/auth") {
LoginManager loginManager(db);
code = loginManager.doAction(data, response);
}
else {
code = HttpResponse::Code::NOT_FOUND;
response = Manager::createError("Something wrong");
}
answer->setData(response, code);
return answer;
}
}} // m2::server
|
/*
* color_grid.cpp
* Purpose: Contain the Spectrum-imitating "color grid". The color grid is one eighth the height and
* width of the screen and holds one color per cell at a time. This is to imitate the
* Spectrum's "attribute clash", which was caused by the console's ability to only display
* two colors at a time.
*
* @author Jeremy Elkayam
*/
#include "color_grid.hpp"
ColorGrid::ColorGrid(int square_size, float view_width, float view_height) {
this->square_size = square_size;
//Populate the color grid. This is a grid of 8x8 squares with one color each.
//The height of the array, the number of rows, should be
for(int row=0;row<(((int)view_height)/square_size);row++){
grid.emplace_back(
vector<sf::RectangleShape>(
(unsigned long)view_width/square_size));
//We have allocated the vector of RectangleShapes. Let's fill it up and initialize their
//color (which will change) and position (which won't)
for(int col=0;col<(((int)view_width)/square_size);col++){
grid[row][col]=sf::RectangleShape(sf::Vector2f(square_size,square_size));
//Because row corresponds to ycor and col is xcor, we have to do this. A bit weird, I know.
grid[row][col].setPosition(square_size*col,square_size*row);
//The reset() method should color them all in white for us, so we don't need to
//do that here.
}
}
}
void ColorGrid::reset() {
for(int row=0;row<grid.size();row++){
for(int col=0;col<grid[row].size();col++){
grid[row][col].setFillColor(sf::Color::White);
}
}
}
void ColorGrid::update(sf::FloatRect object_bounds, sf::Color color) {
int paint_from_col = (int) object_bounds.left / square_size;
int paint_from_row = (int) object_bounds.top / square_size;
auto how_many_cols = (int) ceil(object_bounds.width / square_size);
auto how_many_rows = (int) ceil(object_bounds.height / square_size);
for (int row = paint_from_row; row <= paint_from_row + how_many_rows; row++) {
if (row >= 0 && row < grid.size()) { //protect us from hitting nonexistent grid squares
for (int col = paint_from_col; col <= paint_from_col + how_many_cols; col++) {
if (col >= 0 && col < grid[row].size()) { //more protection
//if we're sure we're hitting the a real square, let's paint.
grid[row][col].setFillColor(color);
}
}
}
}
}
void ColorGrid::draw(sf::RenderWindow &window) {
for(int row=0;row<grid.size();row++){
for(int col=0;col<grid[row].size();col++){
window.draw(grid[row][col],sf::BlendMultiply);
}
}
}
|
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Standard_ShortReal_HeaderFile
#define _Standard_ShortReal_HeaderFile
#include <cmath>
#include <float.h>
#include <Standard_values.h>
#include <Standard_TypeDef.hxx>
// *********************************** //
// Class methods //
// //
// Machine-dependent values //
// Should be taken from include file //
// *********************************** //
//-------------------------------------------------------------------
// ShortRealSmall : Returns the smallest positive ShortReal
//-------------------------------------------------------------------
inline Standard_ShortReal ShortRealSmall()
{ return FLT_MIN; }
//-------------------------------------------------------------------
// Abs : Returns the absolute value of a ShortReal
//-------------------------------------------------------------------
inline Standard_ShortReal Abs(const Standard_ShortReal Value)
#if defined (__alpha) || defined(DECOSF1)
{ return fabsf(Value); }
#else
{ return float( fabs (Value) ) ; }
#endif
//-------------------------------------------------------------------
// ShortRealDigit : Returns the number of digits of precision in a ShortReal
//-------------------------------------------------------------------
inline Standard_Integer ShortRealDigits()
{ return FLT_DIG; }
//-------------------------------------------------------------------
// ShortRealEpsilon : Returns the minimum positive ShortReal such that
// 1.0 + x is not equal to 1.0
//-------------------------------------------------------------------
inline Standard_ShortReal ShortRealEpsilon()
{ return FLT_EPSILON; }
//-------------------------------------------------------------------
// ShortRealFirst : Returns the minimum negative value of a ShortReal
//-------------------------------------------------------------------
inline Standard_ShortReal ShortRealFirst()
{ Standard_ShortReal MaxFloatTmp = -FLT_MAX;
return MaxFloatTmp; }
//-------------------------------------------------------------------
// ShortRealFirst10Exp : Returns the minimum value of exponent(base 10) of
// a ShortReal.
//-------------------------------------------------------------------
inline Standard_Integer ShortRealFirst10Exp()
{ return FLT_MIN_10_EXP; }
//-------------------------------------------------------------------
// ShortRealLast : Returns the maximum value of a ShortReal
//-------------------------------------------------------------------
inline Standard_ShortReal ShortRealLast()
{ return FLT_MAX; }
//-------------------------------------------------------------------
// ShortRealLast10Exp : Returns the maximum value of exponent(base 10) of
// a ShortReal.
//-------------------------------------------------------------------
inline Standard_Integer ShortRealLast10Exp()
{ return FLT_MAX_10_EXP; }
//-------------------------------------------------------------------
// ShortRealMantissa : Returns the size in bits of the matissa part of a
// ShortReal.
//-------------------------------------------------------------------
inline Standard_Integer ShortRealMantissa()
{ return FLT_MANT_DIG; }
//-------------------------------------------------------------------
// ShortRealRadix : Returns the radix of exponent representation
//-------------------------------------------------------------------
inline Standard_Integer ShortRealRadix()
{ return FLT_RADIX; }
//-------------------------------------------------------------------
// ShortRealSize : Returns the size in bits of an integer
//-------------------------------------------------------------------
inline Standard_Integer ShortRealSize()
{ return BITS(Standard_ShortReal); }
//-------------------------------------------------------------------
// Max : Returns the maximum value of two ShortReals
//-------------------------------------------------------------------
inline Standard_ShortReal Max (const Standard_ShortReal Val1,
const Standard_ShortReal Val2)
{
if (Val1 >= Val2) {
return Val1;
} else {
return Val2;
}
}
//-------------------------------------------------------------------
// Min : Returns the minimum value of two ShortReals
//-------------------------------------------------------------------
inline Standard_ShortReal Min (const Standard_ShortReal Val1,
const Standard_ShortReal Val2)
{
if (Val1 <= Val2) {
return Val1;
} else {
return Val2;
}
}
// ===============================================
// Methods from Standard_Entity class which are redefined:
// - Hascode
// - IsEqual
// ===============================================
// ==================================
// Methods implemented in Standard_ShortReal.cxx
// ==================================
//! Computes a hash code for the given short real, in the range [1, theUpperBound]
//! @param theShortReal the short real value which hash code is to be computed
//! @param theUpperBound the upper bound of the range a computing hash code must be within
//! @return a computed hash code, in the range [1, theUpperBound]
Standard_EXPORT Standard_Integer HashCode (Standard_ShortReal theShortReal, Standard_Integer theUpperBound);
//-------------------------------------------------------------------
// IsEqual : Returns Standard_True if two ShortReals are equal
//-------------------------------------------------------------------
inline Standard_Boolean IsEqual (const Standard_ShortReal Value1,
const Standard_ShortReal Value2)
{ return Abs((Value1 - Value2)) < ShortRealSmall(); }
#endif
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long a=0,b=0,len,counta = 0,countb = 0;
int t;
char str[100000];
bool flaga = 0,flagb = 0;
scanf("%d",&t);
for(int j =0;j < t;j++)
{
scanf("%s",str);
len = strlen(str);
a = 0;b =0;counta = 0;countb = 0; flaga = 0; flagb = 0;
for(int i = 0;i < len;i++)
{
if( str[i] == 'A' && !flaga)
{
a++;
flaga = 1;
countb = 0;
flagb = 0;
}
else
if(str[i] == 'A' && flaga)
{
counta++;
a += counta;
counta = 0;
}
else
if(str[i] == 'B' && !flagb)
{
b++;
flagb = 1;
counta = 0;
flaga =0;
}
else
if(str[i] == 'B' && flagb)
{
countb++;
b += countb;
countb = 0;
}
else
if(str[i] == '.')
{
if(flaga)
counta++;
else
if(flagb)
countb++;
}
}
printf("%lld %lld\n",a,b);
}
return 0;
}
|
/*
* File: main.cpp
* Author: Elijah De Vera
* Created on January 5, 2021, 12:36 AM
* Purpose: Restaurant Bill
*/
//System Libraries
#include <iostream> //I/O Library
using namespace std;
//User Libraries
//Global Constants
//Math, Science, Universal, Conversion, High Dimensioned Arrays
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Initialize the Random Number Seed
//Declare Variables
double bill,
tax,
totalNoTip,
taxAmount,
tip,
total;
//Initialize Variables
bill = 8.867E1;
tax = 0.0675E0;
//Map Inputs to Outputs -> Process
taxAmount = bill * tax;
totalNoTip = bill + taxAmount;
tip = 0.2 * totalNoTip;
total = tip + totalNoTip;
//Display Inputs/Outputs
cout<<"Meal Cost: "<<bill<<endl;
cout<<"Tax Amount: "<<taxAmount<<endl;
cout<<"Tip Amount: "<<tip<<endl;
cout<<"Total: "<<total<<endl;
// Exit the Program - Cleanup
return 0;
}
|
#include <iostream>
#include "../Plain.h"
#include "../River.h"
#include "../testMacros.h"
#include "../Area.h"
#include "../exceptions.h"
#include "../Mountain.h"
#include "../World.h"
using namespace mtm;
std::map<std::string, Clan> makeClanMap(){
std::map<std::string, Clan> clan_map;
clan_map.insert(std::pair<std::string, Clan>("Marvel", Clan("Marvel")));
clan_map.insert(std::pair<std::string, Clan>("DC", Clan("DC")));
clan_map.insert(std::pair<std::string, Clan>("GOT", Clan("GOT")));
clan_map.at("Marvel").addGroup(Group("Avengers", 2, 2));
clan_map.at("Marvel").addGroup(Group("X-Men","", 10, 7, 100, 100, 80));
clan_map.at("Marvel").addGroup(Group("Deadpool","", 0, 1, 1000, 1000, 100));
clan_map.at("Marvel").addGroup(Group("Weak","", 0, 1, 1, 1, 10));
clan_map.at("Marvel").addGroup(Group("Traders","", 1, 1, 1100, 500, 10));
clan_map.at("DC").addGroup(Group("Justice League_1", 1, 1));
clan_map.at("DC").addGroup(Group("Justice League_2", 1, 1));
clan_map.at("DC").addGroup(Group("Justice League_3", 5, 5));
clan_map.at("DC").addGroup(Group("Justice League_4","", 10, 6,97,100,80));
clan_map.at("GOT").addGroup(Group("Stark","", 15, 5,30,47,70));
clan_map.at("GOT").addGroup(Group("Lannister","",5,7, 100,97,50));
clan_map.at("GOT").addGroup(Group("Baratheon","",5,5, 5,5,85));
clan_map.at("GOT").addGroup(Group("Targeryan","",21,20, 100,100,85));
clan_map.at("GOT").addGroup(Group("Targeryan_2","",1,0, 1000,1000,85));
clan_map.at("GOT").addGroup(Group("Targeryan_3","",1,0, 1,1,85));
return clan_map;
}
bool testPlain(){
AreaPtr winterfell(new Plain("Winterfell"));
AreaPtr kingslanding(new Plain("Kingslanding"));
ASSERT_EXCEPTION(Plain(""),AreaInvalidArguments);
ASSERT_NO_EXCEPTION(winterfell->addReachableArea("Kingslanding"));
ASSERT_TRUE(winterfell->isReachable("Kingslanding"));
ASSERT_FALSE(winterfell->isReachable("Kingsland"));
std::map<std::string, Clan> clan_map = makeClanMap();
ASSERT_NO_EXCEPTION(winterfell->groupArrive("Stark", "GOT", clan_map));
ASSERT_TRUE(winterfell->getGroupsNames().contains("Stark"));
ASSERT_FALSE(winterfell->getGroupsNames().contains("Lannister"));
ASSERT_NO_EXCEPTION(winterfell->groupArrive("Lannister", "GOT", clan_map));
ASSERT_TRUE(winterfell->getGroupsNames().contains("Lannister"));
ASSERT_NO_EXCEPTION(winterfell->groupArrive("Baratheon", "GOT", clan_map));
ASSERT_TRUE(winterfell->getGroupsNames().contains("Baratheon"));
ASSERT_NO_EXCEPTION(winterfell->groupArrive("Targeryan", "GOT", clan_map));
ASSERT_TRUE(winterfell->getGroupsNames().contains("Targeryan"));
ASSERT_TRUE(winterfell->getGroupsNames().contains("Targeryan_4"));
ASSERT_NO_EXCEPTION(winterfell->groupArrive("Targeryan_2","GOT", clan_map));
ASSERT_FALSE(winterfell->getGroupsNames().contains("Targeryan_2"));
ASSERT_EXCEPTION(winterfell->groupLeave("Targeryan_2"),AreaGroupNotFound);
ASSERT_NO_EXCEPTION(winterfell->groupLeave("Stark"));
ASSERT_NO_EXCEPTION(winterfell->groupLeave("Lannister"));
ASSERT_FALSE(winterfell->getGroupsNames().contains("Lannister"));
ASSERT_FALSE(winterfell->getGroupsNames().contains("Stark"));
ASSERT_EXCEPTION(winterfell->groupLeave(""),AreaGroupNotFound);
ostringstream os;
ASSERT_NO_EXCEPTION(os << clan_map.at("GOT"));
ASSERT_TRUE(VerifyOutput(os, "Clan's name: GOT\n"
"Clan's groups:\n"
"Targeryan\n"
"Targeryan_4\n"
"Lannister\n"
"Stark\n"
"Baratheon\n"
"Targeryan_3\n"));
ASSERT_EXCEPTION(winterfell->groupArrive("","",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(winterfell->groupArrive("NotFound","NotFound",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(winterfell->groupArrive("NotFound","GOT",clan_map)
,AreaGroupNotInClan);
ASSERT_EXCEPTION(winterfell->groupArrive("Baratheon","GOT",clan_map)
,AreaGroupAlreadyIn);
return true;
}
bool testMountain() {
AreaPtr m1(new Mountain("Casterly Rock"));
AreaPtr m2(new Mountain("The Eyrie"));
ASSERT_EXCEPTION(Mountain(""), AreaInvalidArguments);
ASSERT_NO_EXCEPTION(m1->addReachableArea("The Eyrie"));
ASSERT_TRUE(m1->isReachable("The Eyrie"));
ASSERT_FALSE(m1->isReachable("TheEyrie"));
std::map<std::string, Clan> clan_map = makeClanMap();
ASSERT_NO_EXCEPTION(m1->groupArrive("Avengers", "Marvel", clan_map));
ASSERT_TRUE(m1->getGroupsNames().contains("Avengers"));
ASSERT_NO_EXCEPTION(m1->groupArrive("Justice League_1", "DC", clan_map));
ASSERT_TRUE(m1->getGroupsNames().contains("Avengers"));
ASSERT_FALSE(m1->getGroupsNames().contains("Justice League_1"));//died
ASSERT_NO_EXCEPTION(m1->groupArrive("X-Men", "Marvel", clan_map));//ruler
ASSERT_NO_EXCEPTION(m1->groupArrive("Justice League_2", "DC", clan_map));
ASSERT_TRUE(m1->getGroupsNames().contains("Avengers"));
ASSERT_TRUE(m1->getGroupsNames().contains("X-Men"));
ASSERT_FALSE(m1->getGroupsNames().contains("Justice League_2"));//died
ASSERT_NO_EXCEPTION(m1->groupLeave("X-Men"));//Avengers will rule now.
ASSERT_NO_EXCEPTION(
m1->groupArrive("Justice League_3", "DC", clan_map));//won
ASSERT_TRUE(m1->getGroupsNames().contains("Justice League_3"));
ASSERT_TRUE(m1->getGroupsNames().contains("Avengers"));
ASSERT_NO_EXCEPTION(m1->groupLeave("Justice League_3"));//Avengers rule.
ASSERT_NO_EXCEPTION(
m1->groupArrive("Justice League_3", "DC", clan_map));//won
ASSERT_TRUE(m1->getGroupsNames().contains("Justice League_3"));
ASSERT_FALSE(m1->getGroupsNames().contains("Avengers"));//died
ASSERT_NO_EXCEPTION(m1->groupArrive("Justice League_4", "DC", clan_map));
ASSERT_NO_EXCEPTION(m1->groupArrive("X-Men", "Marvel", clan_map));//lost
ASSERT_TRUE(m1->getGroupsNames().contains("Justice League_3"));
ASSERT_TRUE(m1->getGroupsNames().contains("Justice League_4"));
ASSERT_TRUE(m1->getGroupsNames().contains("X-Men"));
ASSERT_NO_EXCEPTION(m1->groupLeave("Justice League_4"));//JL3 rule.
ASSERT_NO_EXCEPTION(m1->groupArrive("Deadpool", "Marvel", clan_map));//won
ASSERT_NO_EXCEPTION(m1->groupLeave("Deadpool"));//X-Men rule.
//would lose if X-Men didn't rule .
ASSERT_NO_EXCEPTION(m1->groupArrive("Weak", "Marvel", clan_map));
ASSERT_TRUE(m1->getGroupsNames().contains("Weak"));
ASSERT_TRUE(m1->getGroupsNames().contains("Justice League_3"));
ASSERT_EXCEPTION(m1->groupLeave(""),AreaGroupNotFound);
ASSERT_EXCEPTION(m1->groupLeave("Deadpool"),AreaGroupNotFound);
ASSERT_EXCEPTION(m1->groupArrive("","",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(m1->groupArrive("NotFound","NotFound",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(m1->groupArrive("NotFound","GOT",clan_map)
,AreaGroupNotInClan);
ASSERT_EXCEPTION(m1->groupArrive("Weak","Marvel",clan_map)
,AreaGroupAlreadyIn);
return true;
}
bool testRiver () {
AreaPtr r1(new River("Bravos"));
AreaPtr r2(new River("Riverrun"));
ASSERT_EXCEPTION(River(""), AreaInvalidArguments);
ASSERT_NO_EXCEPTION(r1->addReachableArea("Riverrun"));
ASSERT_TRUE(r1->isReachable("Riverrun"));
ASSERT_FALSE(r1->isReachable("riverrun"));
std::map<std::string, Clan> clan_map = makeClanMap();
ASSERT_NO_EXCEPTION(r1->groupArrive("Stark", "GOT", clan_map));
ASSERT_TRUE(r1->getGroupsNames().contains("Stark"));
ASSERT_FALSE(r1->getGroupsNames().contains("Lannister"));
ASSERT_NO_EXCEPTION(r1->groupArrive("Lannister", "GOT", clan_map));
ASSERT_TRUE(r1->getGroupsNames().contains("Lannister"));
ASSERT_NO_EXCEPTION(r1->groupArrive("X-Men", "Marvel", clan_map));
ostringstream os;
ASSERT_NO_EXCEPTION(os << *(clan_map.at("GOT").getGroup("Lannister")));
ASSERT_TRUE(VerifyOutput(os, "Group's name: Lannister\n"
"Group's clan: GOT\n"
"Group's children: 5\n"
"Group's adults: 7\n"
"Group's tools: 94\n"
"Group's food: 103\n"
"Group's morale: 55\n"));
ASSERT_NO_EXCEPTION(r1->groupArrive("Justice League_4", "DC", clan_map));
ASSERT_NO_EXCEPTION(os << *(clan_map.at("GOT").getGroup("Lannister")));
ASSERT_TRUE(VerifyOutput(os, "Group's name: Lannister\n"
"Group's clan: GOT\n"
"Group's children: 5\n"
"Group's adults: 7\n"
"Group's tools: 94\n"
"Group's food: 103\n"
"Group's morale: 55\n"));
clan_map.at("GOT").makeFriend(clan_map.at("Marvel"));
// will trade with Lannister beacuse they are strongest and friend clan.
ASSERT_NO_EXCEPTION(r1->groupArrive("Traders", "Marvel", clan_map));
ASSERT_NO_EXCEPTION(os << *(clan_map.at("GOT").getGroup("Lannister")));
ASSERT_TRUE(VerifyOutput(os, "Group's name: Lannister\n"
"Group's clan: GOT\n"
"Group's children: 5\n"
"Group's adults: 7\n"
"Group's tools: 197\n"
"Group's food: 0\n"
"Group's morale: 55\n"));
ASSERT_NO_EXCEPTION(r1->groupLeave("Traders"));
ASSERT_EXCEPTION(r1->groupLeave("Traders"),AreaGroupNotFound);
ASSERT_NO_EXCEPTION(r1->groupArrive("Traders", "Marvel", clan_map));
ASSERT_EXCEPTION(r1->groupArrive("","",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(r1->groupArrive("NotFound","NotFound",clan_map)
,AreaClanNotFoundInMap);
ASSERT_EXCEPTION(r1->groupArrive("NotFound","GOT",clan_map)
,AreaGroupNotInClan);
ASSERT_EXCEPTION(r1->groupArrive("Traders","Marvel",clan_map)
,AreaGroupAlreadyIn);
return true ;
}
int main(){
RUN_TEST(testPlain);
RUN_TEST(testMountain);
RUN_TEST(testRiver);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef SECURITY_UNITE_H
#define SECURITY_UNITE_H
#ifdef WEBSERVER_SUPPORT
class OpSecurityManager_Unite
{
public:
OP_STATUS CheckUniteSecurity(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed);
protected:
static BOOL AllowUniteURL(const URL& target, const URL& source, BOOL is_top_document=FALSE);
/**< Unite URLs are URLs with administration rights for Unite service.
* Hence opening of them is severly restricted based upon who is trying
* to open it.
*
* The specification for what is allowed to open unite URLS is specified
* in the wiki at
* https://wiki.oslo.opera.com/developerwiki/Alien/User_Administration
*
* See also task CORE-19590
*
* \param target The URL to the unite service we're trying to open. MUST be
* of type URL_UNITE
* \param source The URL this service is being opened from. This will be
* the referer in DocumentManager::OpenURL.
*/
static BOOL AllowInterUniteConnection(const URL& target, const URL& source, BOOL is_top_document=FALSE);
/**< Unite services are only allowed to access Unite URLs from the same service.
*
* Exception if loding URL is top_document. Then the root service is
* allowed to access the default page of all Unite services, and all
* Unite services are allowed to access the default page of the root URL.
*
* \param target The URL to the unite service we're trying to open. MUST be
* of type URL_UNITE
* \param source The URL this service is being opened from. This will be
* the referer in DocumentManager::OpenURL.
* \param is_top_document TRUE if the source URL is the top document trying
* to load the URL (i.e. target will be the new top document)
*/
};
#endif // WEBSERVER_SUPPORT
#endif // SECURITY_UNITE_H
|
/**
* Copyright (c) 2023, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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 <future>
#include "log.annotate.hh"
#include "base/auto_fd.hh"
#include "base/auto_pid.hh"
#include "base/fs_util.hh"
#include "base/paths.hh"
#include "line_buffer.hh"
#include "lnav.hh"
#include "log_data_helper.hh"
#include "md4cpp.hh"
#include "readline_highlighters.hh"
#include "yajlpp/yajlpp.hh"
namespace lnav {
namespace log {
namespace annotate {
struct compiled_cond_expr {
auto_mem<sqlite3_stmt> cce_stmt{sqlite3_finalize};
bool cce_enabled{true};
};
struct expressions : public lnav_config_listener {
expressions() : lnav_config_listener(__FILE__) {}
void reload_config(error_reporter& reporter) override
{
auto& lnav_db = injector::get<auto_sqlite3&>();
if (lnav_db.in() == nullptr) {
log_warning("db not initialized yet!");
return;
}
const auto& cfg = injector::get<const config&>();
this->e_cond_exprs.clear();
for (const auto& pair : cfg.a_definitions) {
if (pair.second.a_handler.pp_value.empty()) {
auto um
= lnav::console::user_message::error(
"no handler specified for annotation")
.with_reason("Every annotation requires a handler");
reporter(&pair.second.a_handler, um);
continue;
}
auto stmt_str = fmt::format(FMT_STRING("SELECT 1 WHERE {}"),
pair.second.a_condition);
compiled_cond_expr cce;
log_info("preparing annotation condition expression: %s",
stmt_str.c_str());
auto retcode = sqlite3_prepare_v2(lnav_db,
stmt_str.c_str(),
stmt_str.size(),
cce.cce_stmt.out(),
nullptr);
if (retcode != SQLITE_OK) {
auto sql_al = attr_line_t(pair.second.a_condition)
.with_attr_for_all(SA_PREFORMATTED.value())
.with_attr_for_all(
VC_ROLE.value(role_t::VCR_QUOTED_CODE));
readline_sqlite_highlighter(sql_al, -1);
intern_string_t cond_expr_path = intern_string::lookup(
fmt::format(FMT_STRING("/log/annotations/{}/condition"),
pair.first));
auto snippet = lnav::console::snippet::from(
source_location(cond_expr_path), sql_al);
auto um = lnav::console::user_message::error(
"SQL expression is invalid")
.with_reason(sqlite3_errmsg(lnav_db))
.with_snippet(snippet);
reporter(&pair.second.a_condition, um);
continue;
}
this->e_cond_exprs.emplace(pair.first, std::move(cce));
}
}
void unload_config() override { this->e_cond_exprs.clear(); }
std::map<intern_string_t, compiled_cond_expr> e_cond_exprs;
};
static expressions exprs;
std::vector<intern_string_t>
applicable(vis_line_t vl)
{
std::vector<intern_string_t> retval;
auto& lss = lnav_data.ld_log_source;
auto cl = lss.at(vl);
auto ld = lss.find_data(cl);
log_data_helper ldh(lss);
ldh.parse_line(vl, true);
for (auto& expr : exprs.e_cond_exprs) {
if (!expr.second.cce_enabled) {
continue;
}
auto eval_res
= lss.eval_sql_filter(expr.second.cce_stmt.in(), ld, ldh.ldh_line);
if (eval_res.isErr()) {
log_error("eval failed: %s",
eval_res.unwrapErr().to_attr_line().get_string().c_str());
expr.second.cce_enabled = false;
} else {
if (eval_res.unwrap()) {
retval.emplace_back(expr.first);
}
}
}
return retval;
}
Result<void, lnav::console::user_message>
apply(vis_line_t vl, std::vector<intern_string_t> annos)
{
const auto& cfg = injector::get<const config&>();
auto& lss = lnav_data.ld_log_source;
auto cl = lss.at(vl);
auto ld = lss.find_data(cl);
auto lf = (*ld)->get_file();
logmsg_annotations la;
log_data_helper ldh(lss);
if (!ldh.parse_line(vl, true)) {
log_error("failed to parse line %d", vl);
return Err(lnav::console::user_message::error("Failed to parse line"));
}
auto line_number = content_line_t{ldh.ldh_line_index - ldh.ldh_y_offset};
lss.set_user_mark(&textview_curses::BM_META,
content_line_t{ldh.ldh_source_line - ldh.ldh_y_offset});
yajlpp_gen gen;
{
auto bm_opt = lss.find_bookmark_metadata(vl);
yajlpp_map root(gen);
root.gen("log_line");
root.gen((int64_t) vl);
root.gen("log_tags");
{
yajlpp_array tag_array(gen);
if (bm_opt) {
const auto& bm = *(bm_opt.value());
for (const auto& tag : bm.bm_tags) {
tag_array.gen(tag);
}
}
}
root.gen("log_path");
root.gen(lf->get_filename());
root.gen("log_format");
root.gen(lf->get_format_name());
root.gen("log_format_regex");
root.gen(lf->get_format()->get_pattern_name(line_number));
root.gen("log_msg");
root.gen(ldh.ldh_line_values.lvv_sbr.to_string_fragment());
for (const auto& val : ldh.ldh_line_values.lvv_values) {
root.gen(val.lv_meta.lvm_name);
switch (val.lv_meta.lvm_kind) {
case value_kind_t::VALUE_NULL:
root.gen();
break;
case value_kind_t::VALUE_INTEGER:
root.gen(val.lv_value.i);
break;
case value_kind_t::VALUE_FLOAT:
root.gen(val.lv_value.d);
break;
case value_kind_t::VALUE_BOOLEAN:
root.gen(val.lv_value.i ? true : false);
break;
default:
root.gen(val.to_string());
break;
}
}
}
for (const auto& anno : annos) {
auto iter = cfg.a_definitions.find(anno);
if (iter == cfg.a_definitions.end()) {
log_error("unknown annotation: %s", anno.c_str());
continue;
}
la.la_pairs[anno.to_string()] = "Loading...";
auto child_fds_res = auto_pipe::for_child_fds(
STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
if (child_fds_res.isErr()) {
auto um
= lnav::console::user_message::error("unable to create pipes")
.with_reason(child_fds_res.unwrapErr());
return Err(um);
}
auto child_res = lnav::pid::from_fork();
if (child_res.isErr()) {
auto um
= lnav::console::user_message::error("unable to fork() child")
.with_reason(child_res.unwrapErr());
return Err(um);
}
auto child_fds = child_fds_res.unwrap();
auto child = child_res.unwrap();
for (auto& child_fd : child_fds) {
child_fd.after_fork(child.in());
}
if (child.in_child()) {
const char* exec_args[] = {
getenv_opt("SHELL").value_or("bash"),
"-c",
iter->second.a_handler.pp_value.c_str(),
nullptr,
};
std::vector<ghc::filesystem::path> path_v;
auto src_path
= ghc::filesystem::path(
iter->second.a_handler.pp_location.sl_source.to_string())
.parent_path();
path_v.push_back(src_path);
path_v.push_back(lnav::paths::dotlnav() / "formats/default");
auto path_var = lnav::filesystem::build_path(path_v);
log_debug("annotate PATH: %s", path_var.c_str());
setenv("PATH", path_var.c_str(), 1);
execvp(exec_args[0], (char**) exec_args);
_exit(EXIT_FAILURE);
}
auto out_reader = std::async(
std::launch::async,
[out_fd = std::move(child_fds[1].read_end())]() mutable {
std::string retval;
file_range last_range;
line_buffer lb;
lb.set_fd(out_fd);
while (true) {
auto load_res = lb.load_next_line(last_range);
if (load_res.isErr()) {
log_error("unable to load next line: %s",
load_res.unwrapErr().c_str());
break;
}
auto li = load_res.unwrap();
if (li.li_file_range.empty()) {
break;
}
auto read_res = lb.read_range(li.li_file_range);
if (read_res.isErr()) {
log_error("unable to read next line: %s",
load_res.unwrapErr().c_str());
break;
}
auto sbr = read_res.unwrap();
retval.append(sbr.get_data(), sbr.length());
last_range = li.li_file_range;
}
return retval;
});
auto err_reader = std::async(
std::launch::async,
[err_fd = std::move(child_fds[2].read_end()),
handler = iter->second.a_handler.pp_value]() mutable {
std::string retval;
file_range last_range;
line_buffer lb;
lb.set_fd(err_fd);
while (true) {
auto load_res = lb.load_next_line(last_range);
if (load_res.isErr()) {
log_error("unable to load next line: %s",
load_res.unwrapErr().c_str());
break;
}
auto li = load_res.unwrap();
if (li.li_file_range.empty()) {
break;
}
auto read_res = lb.read_range(li.li_file_range);
if (read_res.isErr()) {
log_error("unable to read next line: %s",
load_res.unwrapErr().c_str());
break;
}
auto sbr = read_res.unwrap();
retval.append(sbr.get_data(), sbr.length());
sbr.rtrim(is_line_ending);
log_debug("%s: %.*s",
handler.c_str(),
sbr.length(),
sbr.get_data());
last_range = li.li_file_range;
}
return retval;
});
auto write_res
= child_fds[0].write_end().write_fully(gen.to_string_fragment());
if (write_res.isErr()) {
log_error("bah %s", write_res.unwrapErr().c_str());
}
child_fds[0].write_end().reset();
auto finalizer = [anno,
out_reader1 = out_reader.share(),
err_reader1 = err_reader.share(),
lf,
line_number,
handler = iter->second.a_handler.pp_value](
auto& fc,
auto_pid<process_state::finished>& child) mutable {
auto& line_anno
= lf->get_bookmark_metadata()[line_number].bm_annotations;
auto content = out_reader1.get();
if (!child.was_normal_exit()) {
content.append(fmt::format(
FMT_STRING(
"\n\n\u2718 annotation handler \u201c{}\u201d failed "
"with signal {}:\n\n<pre>\n{}\n</pre>\n"),
handler,
child.term_signal(),
err_reader1.get()));
} else if (child.exit_status() != 0) {
content.append(fmt::format(
FMT_STRING(
"\n\n<span "
"class=\"-lnav_log-level-styles_error\">"
"\u2718 annotation handler \u201c{}\u201d exited "
"with status {}:</span>\n\n<pre>{}</pre>"),
handler,
child.exit_status(),
md4cpp::escape_html(err_reader1.get())));
}
line_anno.la_pairs[anno.to_string()] = content;
lnav_data.ld_views[LNV_LOG].reload_data();
lnav_data.ld_views[LNV_LOG].set_needs_update();
};
lnav_data.ld_child_pollers.emplace_back(
(*ld)->get_file_ptr()->get_filename(),
std::move(child),
std::move(finalizer));
}
lf->get_bookmark_metadata()[line_number].bm_annotations = la;
return Ok();
}
} // namespace annotate
} // namespace log
} // namespace lnav
|
#ifndef __CocosProject__EnemyTank__
#define __CocosProject__EnemyTank__
#include "cocos2d.h"
#include "ui/cocosGUI.h"
#include <stdio.h>
class EnemyTank : public cocos2d::Node
{
public:
EnemyTank();
~EnemyTank();
virtual bool init() override;
static EnemyTank* create();
void update(float);
void reset();
bool hasCollidedWithAEnemyTank(cocos2d::Rect collisionBoxToCheck);
private:
cocos2d::Sprite* Enemy_Tank;
float startXPosition;
float startYPosition;
float currentSpeed;
};
#endif
|
// DisplayDeviceArmband.h: interface for the DisplayDeviceArmband class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_DISPLAYDEVICEARMBAND_H__809A67E4_0DFE_414D_B801_86B8A624097A__INCLUDED_)
#define AFX_DISPLAYDEVICEARMBAND_H__809A67E4_0DFE_414D_B801_86B8A624097A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "TactileArray.h"
#define ARMBAND_ARRAY_SIZE_X 3
#define ARMBAND_ARRAY_SIZE_Y 4
class DisplayDeviceArmband : public TactileArray
{
public:
DisplayDeviceArmband(int a_portNum);
virtual ~DisplayDeviceArmband();
int m_array[ARMBAND_ARRAY_SIZE_X][ARMBAND_ARRAY_SIZE_Y];
void setActReset()
{
setIntensityAll(0);
}
void setActForearm(double a_actX, double a_actY);
};
#endif // !defined(AFX_DISPLAYDEVICEARMBAND_H__809A67E4_0DFE_414D_B801_86B8A624097A__INCLUDED_)
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "S05_TestingGrounds.h"
#include "ActorPool.h"
// Sets default values for this component's properties
UActorPool::UActorPool()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
AActor * UActorPool::CheckOut()
{
if (Pool.Num() > 0)
{
auto mesh = Pool.Pop();
return mesh;
}
return nullptr;
}
void UActorPool::CheckIn(AActor * Actor)
{
if (Actor == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("Returning null actor to %s"), *this->GetName());
return;
}
Pool.Push(Actor);
}
void UActorPool::Add(AActor * Actor)
{
CheckIn(Actor);
}
|
#ifndef None_P_HPP
#define None_P_HPP
#include <QObject>
class NonePrivate : public QObject
{
Q_OBJECT
public:
NonePrivate();
~NonePrivate();
};
#endif
|
#include "SquareHelper.h"
void SquareHelper::changeLength(Square& square, double length)
{
square.length = length;
}
|
#include <iostream>
#include <string>
using namespace std;
#define MAX_MAP 5
int board[MAX_MAP][MAX_MAP];
int used[MAX_MAP][MAX_MAP]={0,};
int dx[8] = {-1, -1, -1, 1, 1, 1, 0, 0};
int dy[8] = {0, 0, 0, 0, 0, 0, 1, -1};
bool inRange(int y, int x) {
};
bool hasWord(int y,int x, const string& word) {
if ( !inRange(y,x) ) return false;
if ( board[y][x] != word[0] ) return false;
if ( word.size() == 1 ) return true;
for(int direction=0; direction<8; direction++) {
int ny = y + dy[direction];
int nx = x + dx[direction];
if ( hasWord(ny, nx, word.substr(1)) ) {
return true;
}
}
return false;
};
|
#include "Settings.h"
ofxXmlSettings Settings::myOfxXmlettings = ofxXmlSettings();
void Settings::save(vector<int> vals) {
if (vals.size() >= 4) {
myOfxXmlettings.clear();
myOfxXmlettings.setValue("settings:width", vals[0]);
myOfxXmlettings.setValue("settings:height", vals[1]);
myOfxXmlettings.setValue("settings:x_Pos", vals[2]);
myOfxXmlettings.setValue("settings:y_Pos", vals[3]);
myOfxXmlettings.saveFile("settings.xml");
}
}
vector<int> Settings::load() {
vector<int> vals;
if (myOfxXmlettings.loadFile("settings.xml")) {
vals.push_back(myOfxXmlettings.getValue("settings:width", 1280));
vals.push_back(myOfxXmlettings.getValue("settings:height", 720));
vals.push_back(myOfxXmlettings.getValue("settings:x_Pos", 200));
vals.push_back(myOfxXmlettings.getValue("settings:y_Pos", 200));
return vals;
}
else return vector<int>{1280, 720, 200, 200};
}
|
#pragma once
#include <list>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <random>
#include <iomanip>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include "string_format.h"
#include "tsc_x86.h"
#include <assert.h>
//Macros
#define CYCLES_REQUIRED_ 1e8 // Cache warmup
#define REP_ 50 // repetitions
#define NUM_RUNS_ 100 //number of runs within each repetition (avg)
#define WARMUP
typedef struct BenchControls {
long CYCLES_REQUIRED = CYCLES_REQUIRED_;
long REP = REP_;
long NUM_RUNS = NUM_RUNS_;
} BenchControls;
//headers
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, comp_func data_loader, BenchControls controls, Args&&... args);
//headers
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, BenchControls controls, Args&&... args);
template<typename comp_func>
double measure_cycles(comp_func f, BenchControls controls);
template<typename comp_func>
double measure_cycles(comp_func f);
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, Args&&... args);
//Main struct
template <typename comp_func>
struct Benchmark {
std::string name = "";
BenchControls controls; // To control repeats in benchmark!
// Optional function that takes the same input as comp_func, and resets the data.
// Malloc should be done outside this function, here we only set values (fill arrays).
// We do this for comparability of benchmarks where funcs overwrite the input.
comp_func data_loader = nullptr;
// comp_func work_compute = nullptr; //returns a vector that overwrites funcFlops, WIP
std::vector<comp_func> userFuncs;
std::vector<std::string> funcNames;
int numFuncs = 0;
std::vector<double> funcFlops; //Work W
std::vector<double> funcBytes; // Memory Moved Q [Bytes!]
std::vector<double> flops_sum; //Sum of Work W for each function over all runs
std::vector<double> bytes_sum; //Sum of Memory Moved Q for each function over all runs
std::vector<double> cycles; // Sum of runtimes over all runs T
std::vector<double> min_cycles; // Minimum t over all runs
std::vector<double> max_cycles; // Maximum t over all runs
std::vector<double> speedups; //Speedup S
std::vector<double> performances; //Performance P
std::vector<std::string> run_names;
std::vector<std::vector<double>> cycles_capture;
std::vector<std::vector<double>> flops_capture;
std::vector<std::vector<double>> bytes_capture;
int num_runs = 0;
std::string run_name = std::to_string(num_runs);
bool destructor_output = true;
std::ostream & fout = std::cout;
bool csv_output = true;
std::string csv_path = "benchmark.csv";
Benchmark(std::string title) {
name = title;
}
void add_function(comp_func f, std::string name, int flop){
double _nan = nan("1");
add_function(f, name, flop, _nan);
}
void add_function(comp_func f, std::string name, int flop, double bytes){
userFuncs.push_back(f);
funcNames.emplace_back(name);
funcFlops.push_back(flop);
funcBytes.push_back(bytes);
numFuncs++;
}
template <typename ... Args>
void run_benchmark(Args&&... args) {
run_names.push_back(run_name);
if (performances.empty()) {
performances.resize(numFuncs, 0.0);
cycles.resize(numFuncs, 0.0);
flops_sum.resize(numFuncs,0.0);
bytes_sum.resize(numFuncs,0.0);
cycles_capture.resize(numFuncs,{});
flops_capture.resize(numFuncs,{});
bytes_capture.resize(numFuncs,{});
speedups.resize(numFuncs, 0.0);
speedups[0] = 1.0 ; //Reference function at index 0
}
for (int i = 0; i < numFuncs; i++)
{
double t = measure_cycles(userFuncs[i], data_loader, controls,
std::forward<Args>(args)...);
double T = cycles[i] + t;
cycles_capture[i].push_back(t);
cycles[i] = T;
flops_capture[i].push_back(funcFlops[i]);
flops_sum[i] += funcFlops[i];
bytes_capture[i].push_back(funcBytes[i]);
bytes_sum[i] += funcBytes[i];
performances[i] = flops_sum[i] / T ;
if (i > 0) {
speedups[i] = cycles[0]/T;
}
}
num_runs++;
run_name = std::to_string(num_runs);
}
void run_benchmark() {
run_names.push_back(run_name);
if (performances.empty()) {
performances.resize(numFuncs, 0.0);
cycles.resize(numFuncs, 0.0);
flops_sum.resize(numFuncs,0.0);
bytes_sum.resize(numFuncs,0.0);
cycles_capture.resize(numFuncs,{});
flops_capture.resize(numFuncs,{});
bytes_capture.resize(numFuncs,{});
speedups.resize(numFuncs, 0.0);
speedups[0] = 1.0 ; //Reference function at index 0
}
for (int i = 0; i < numFuncs; i++)
{
if (data_loader) {
data_loader();
}
double t = measure_cycles(userFuncs[i], controls);
double T = cycles[i] + t;
cycles_capture[i].push_back(t);
cycles[i] = T;
flops_capture[i].push_back(funcFlops[i]);
flops_sum[i] += funcFlops[i];
bytes_capture[i].push_back(funcBytes[i]);
bytes_sum[i] += funcBytes[i];
performances[i] = flops_sum[i] / T ;
if (i > 0) {
speedups[i] = cycles[0]/T;
}
}
num_runs++;
run_name = std::to_string(num_runs);
}
// Summarized output
void summary(){
assert(!performances.empty());
fout<<name<<" ("<<num_runs<<" runs, avg):"<<std::endl;
const int cell_width = 17;
const char* separator = " | ";
const char* underline = "\033[4m";
const char* no_underline = "\033[0m";
fout<<underline<<separator<<right("i",2)
<<separator<<left("Name",40)
<<separator<<right("Work [flops]",cell_width)
<<separator<<right("Memory [bytes]",cell_width)
<<separator<<right("Time [cyc]",cell_width)
<<separator<<right("Perf. [flops/cyc]",cell_width)
<<separator<<right("Speedup [-]",cell_width)
<<separator<<std::endl;
for (int i = 0; i<numFuncs;i++){
fout<<no_underline<<separator<<prd(i, 0,2)
<<separator<<left(funcNames[i],40)
<<separator<<prd(flops_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(bytes_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(cycles[i] / num_runs, 4, cell_width)
<<separator<<prd(performances[i], 4, cell_width)
<<separator<<prd(speedups[i], 4, cell_width)
<<separator<<std::endl;
}
}
// Summarized output, but with some extra columns
void summary_long(){
assert(!performances.empty());
fout<<name<<" ("<<num_runs<<" runs, avg):"<<std::endl;
const int cell_width = 17;
const char* separator = " | ";
const char* underline = "\033[4m";
const char* no_underline = "\033[0m";
fout<<underline<<separator<<right("i",2)
<<separator<<left("Name",40)
<<separator<<right("Work [flops]",cell_width)
<<separator<<right("Memory [bytes]",cell_width)
<<separator<<right("Time [cyc]",cell_width)
<<separator<<right("min. t [cyc]",cell_width)
<<separator<<right("max. t [cyc]",cell_width)
<<separator<<right("Perf. [flops/cyc]",cell_width)
<<separator<<right("Speedup [-]",cell_width)
<<separator<<std::endl;
for (int i = 0; i<numFuncs;i++){
fout<<no_underline<<separator<<prd(i, 0,2)
<<separator<<left(funcNames[i],40)
<<separator<<prd(flops_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(bytes_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(cycles[i] / num_runs, 4, cell_width)
<<separator<<prd(*std::min_element(cycles_capture[i].begin(),
cycles_capture[i].end()), 4, cell_width)
<<separator<<prd(*std::max_element(cycles_capture[i].begin(),
cycles_capture[i].end()), 4, cell_width)
<<separator<<prd(performances[i], 4, cell_width)
<<separator<<prd(speedups[i], 4, cell_width)
<<separator<<std::endl;
}
}
// Outputs per func and run
void details() {
assert(!performances.empty());
int run_name_size = 3;
for (int j = 0; j<num_runs; j++) {
run_name_size = std::max((int)run_names[j].length(), run_name_size);
}
fout<<name<<" ("<<num_runs<<" runs, avg):"<<std::endl;
const int cell_width = 17;
const char* separator = " | ";
const char* underline = "\033[4m";
const char* no_underline = "\033[0m";
fout<<underline<<separator<<right("i",2)
<<separator<<left("Name",40)
<<separator<<right("Run",run_name_size)
<<separator<<right("Work [flops]",cell_width)
<<separator<<right("Memory [bytes]",cell_width)
<<separator<<right("Time [cyc]",cell_width)
<<separator<<right("Perf. [flops/cyc]",cell_width)
<<separator<<right("Gap [cyc/flop]",cell_width) //Cheat
<<separator<<right("Speedup [-]",cell_width)
<<separator<<std::endl;
for (int i = 0; i<numFuncs;i++){
for (int j = 0; j<num_runs; j++) {
double cyc = cycles_capture[i][j];
double flops = flops_capture[i][j];
double bytes = bytes_capture[i][j];
fout<<no_underline<<separator<<((j==0) ? prd(i, 0,2) : " ")
<<separator<<left((j==0) ? funcNames[i] : " ",40)
<<separator<<right(run_names[j],run_name_size)
<<separator<<prd(flops, 0, cell_width)
<<separator<<prd(bytes, 0, cell_width)
<<separator<<prd(cyc, 4, cell_width)
<<separator<<prd(flops/cyc, 4, cell_width)
<<separator<<prd(cyc/flops, 4, cell_width)
<<separator<<prd(cycles_capture[0][j]/cyc, 4, cell_width)
<<separator<<std::endl;
}
}
}
void write_csv() {
std::ofstream fstream;
fstream.open(csv_path, std::ios::out | std::ios::app);
const char* separator = ";";
const int cell_width = 0;
for (int i = 0; i<numFuncs;i++){
fstream<<name
<<separator<<left(funcNames[i], cell_width)
<<separator<<right("",cell_width)
<<separator<<prd(flops_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(bytes_sum[i] / num_runs, 0, cell_width)
<<separator<<prd(cycles[i] / num_runs, 4, cell_width)
<<separator<<prd(performances[i], 4, cell_width)
<<separator<<prd(speedups[i], 4, cell_width)
<<std::endl;
}
fstream.close();
}
void write_csv_details() {
std::ofstream fstream;
fstream.open(csv_path, std::ios::out | std::ios::app);
const char* separator = ";";
const int cell_width = 0;
for (int i = 0; i<numFuncs;i++){
for (int j = 0; j<num_runs; j++) {
double cyc = cycles_capture[i][j];
double flops = flops_capture[i][j];
double bytes = bytes_capture[i][j];
fstream<<name<<separator<<left(funcNames[i], cell_width)
<<separator<<right(run_names[j],cell_width)
<<separator<<prd(flops, 0, cell_width)
<<separator<<prd(bytes, 0, cell_width)
<<separator<<prd(cyc, 4, cell_width)
<<separator<<prd(flops/cyc, 4, cell_width)
<<separator<<prd(cycles_capture[0][j]/cyc, 4, cell_width)
<<std::endl;
}
}
fstream.close();
}
~Benchmark() {
if (destructor_output) {
summary();
}
if (csv_output) {
write_csv();
}
}
};
/* Global vars, used to keep track of student functions */
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, comp_func data_loader, BenchControls controls, Args&&... args) {
double cycles = 0.;
long num_runs = controls.NUM_RUNS;
double multiplier = 1;
myInt64 start, end;
if (data_loader) {
std::forward<comp_func>(data_loader)(std::forward<Args>(args)...);
}
// Warm-up phase: we determine a number of executions that allows
// the code to be executed for at least CYCLES_REQUIRED cycles.
// This helps excluding timing overhead when measuring small runtimes.
#ifdef WARMUP
do {
num_runs = num_runs * multiplier;
start = start_tsc();
for (size_t i = 0; i < num_runs; i++) {
std::forward<comp_func>(f)(std::forward<Args>(args)...);
}
end = stop_tsc(start);
cycles = (double)end;
multiplier = (controls.CYCLES_REQUIRED) / (cycles);
} while (multiplier > 2);
#endif
std::list<double> cyclesList;
// Actual performance measurements repeated REP times.
// We simply store all results and compute medians during post-processing.
double total_cycles = 0;
for (size_t j = 0; j < controls.REP; j++) {
if (data_loader) {
std::forward<comp_func>(data_loader)(std::forward<Args>(args)...);
}
start = start_tsc();
for (size_t i = 0; i < num_runs; ++i) {
std::forward<comp_func>(f)(std::forward<Args>(args)...);
}
end = stop_tsc(start);
cycles = ((double)end) / num_runs;
total_cycles += cycles;
cyclesList.push_back(cycles);
}
total_cycles /= controls.REP;
cyclesList.sort();
cycles = total_cycles;
return cycles;
}
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, BenchControls controls, Args&&... args) {
return measure_cycles(f, nullptr, controls, std::forward<Args>(args)...);
}
template<typename comp_func,
typename ... Args>
double measure_cycles(comp_func f, Args&&... args) {
BenchControls controls;
return measure_cycles(f, nullptr, controls, std::forward<Args>(args)...);
}
template<typename comp_func>
double measure_cycles(comp_func f) {
BenchControls controls;
return measure_cycles(f, controls);
}
template<typename comp_func>
double measure_cycles(comp_func f, BenchControls controls) {
double cycles = 0.;
long num_runs = controls.NUM_RUNS;
double multiplier = 1;
myInt64 start, end;
// Warm-up phase: we determine a number of executions that allows
// the code to be executed for at least CYCLES_REQUIRED cycles.
// This helps excluding timing overhead when measuring small runtimes.
#ifdef WARMUP
do {
num_runs = num_runs * multiplier;
start = start_tsc();
for (size_t i = 0; i < num_runs; i++) {
f();
}
end = stop_tsc(start);
cycles = (double)end;
multiplier = (controls.CYCLES_REQUIRED) / (cycles);
} while (multiplier > 2);
#endif
std::list<double> cyclesList;
// Actual performance measurements repeated REP times.
// We simply store all results and compute medians during post-processing.
double total_cycles = 0;
for (size_t j = 0; j < controls.REP; j++) {
start = start_tsc();
for (size_t i = 0; i < num_runs; ++i) {
f();
}
end = stop_tsc(start);
cycles = ((double)end) / num_runs;
total_cycles += cycles;
cyclesList.push_back(cycles);
}
total_cycles /= controls.REP;
cyclesList.sort();
cycles = total_cycles;
return cycles;
}
|
#include <iostream>
using namespace std;
void Arreglo (int arr[], int orden) {
for (int i=0;i<orden;i++) {
cout<<"Num "<<(i+1)<<": ";
cin>>arr[i];
}
cout<<endl;
}
void Mostrar (int arr[], int orden) {
for (int j=0;j<orden;j++) {
cout<<arr[j]<<" ";
}
cout<<endl;
}
void Buscar (int arr[], int orden, int n) {
int stop=0;
for (int i=0;i<orden;i++) {
if (arr[i]==n) {
if (stop==0){
for (int j=i;j<(orden-1);j++) {
arr[j]=arr[j+1];
}
arr[orden-1]=0;
stop++;
}
}
}
cout<<endl;
}
int main() {
int num,tam;
cout<<"Escriba un numero: ";
cin>>num;
cout<<"Tamaño del arreglo: ";
cin>>tam;
while (tam>15) {
cout<<"Debe ser menor a 15: ";
cin>>tam;
}
cout<<endl;
int arrDatos[tam];
Arreglo (arrDatos,tam);
Mostrar (arrDatos,tam);
cout<<"Eliminando el numero "<<num<<" del arreglo...";
Buscar (arrDatos,tam,num);
Mostrar (arrDatos,tam);
cout<<endl;
return 0;
}
|
/* -*- mode: c++; tab-width: 4; c-basic-offset: 4 -*- */
group "layout.text_align";
require init;
language c++;
include "modules/layout/content/content.h";
global
{
HTMLayoutProperties props;
}
test("Text alignment LTR non-overflow")
{
Line line;
line.SetWidth(LayoutCoord(100));
line.AllocateSpace(LayoutCoord(50), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_ltr;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props) == 50);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props) == 25);
}
test("Text alignment RTL non-overflow") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(100));
line.AllocateSpace(LayoutCoord(50), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_rtl;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props) == 50);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props) == 25);
}
test("Text alignment LTR overflow")
{
Line line;
line.SetWidth(LayoutCoord(50));
line.AllocateSpace(LayoutCoord(100), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_ltr;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props) == 0);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props) == 0);
}
test("Text alignment RTL overflow") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(50));
line.AllocateSpace(LayoutCoord(100), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_rtl;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props) == -50);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props) == -50);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props) == -50);
}
test("Text alignment LTR non-overflow, directional") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(100));
line.AllocateSpace(LayoutCoord(50), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_ltr;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 50);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 25);
}
test("Text alignment RTL non-overflow, directional") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(100));
line.AllocateSpace(LayoutCoord(50), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_rtl;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == -50);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == -25);
}
test("Text alignment LTR overflow, directional") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(50));
line.AllocateSpace(LayoutCoord(100), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_ltr;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
}
test("Text alignment RTL overflow, directional") require SUPPORT_TEXT_DIRECTION;
{
Line line;
line.SetWidth(LayoutCoord(50));
line.AllocateSpace(LayoutCoord(100), LayoutCoord(0), 1, LayoutCoord(0), LayoutCoord(0));
props.direction = CSS_VALUE_rtl;
props.text_align = CSS_VALUE_left;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_right;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
props.text_align = CSS_VALUE_center;
verify(line.GetTextAlignOffset(props, FALSE, TRUE) == 0);
}
|
#include "utils.hpp"
#include "rank_ptts.hpp"
namespace pc = proto::config;
namespace nora {
namespace config {
rank_reward_ptts& rank_reward_ptts_instance() {
static rank_reward_ptts inst;
return inst;
}
void rank_reward_ptts_set_funcs() {
rank_reward_ptts_instance().check_func_ = [] (const auto& ptt) {
if (ptt.rewards_size() == 0) {
CONFIG_ELOG << ptt.id() << " no rewards";
}
for (const auto& i : ptt.rewards()) {
check_events(i.events());
}
};
rank_reward_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.rewards()) {
verify_events(i.events());
}
};
}
rank_logic_ptts& rank_logic_ptts_instance() {
static rank_logic_ptts inst;
return inst;
}
void rank_logic_ptts_set_funcs() {
}
}
}
|
// Created on: 1991-06-24
// Created by: Didier PIFFAULT
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Intf_Interference_HeaderFile
#define _Intf_Interference_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Intf_SeqOfSectionPoint.hxx>
#include <Intf_SeqOfSectionLine.hxx>
#include <Intf_SeqOfTangentZone.hxx>
#include <Standard_Boolean.hxx>
class Intf_SectionPoint;
class Intf_SectionLine;
class Intf_TangentZone;
//! Describes the Interference computation result
//! between polygon2d or polygon3d or polyhedron
//! (as three sequences of points of intersection,
//! polylines of intersection and zones de tangence).
class Intf_Interference
{
public:
DEFINE_STANDARD_ALLOC
//! Gives the number of points of intersection in the
//! interference.
Standard_Integer NbSectionPoints() const;
//! Gives the point of intersection of address Index in
//! the interference.
const Intf_SectionPoint& PntValue (const Standard_Integer Index) const;
//! Gives the number of polylines of intersection in the
//! interference.
Standard_Integer NbSectionLines() const;
//! Gives the polyline of intersection at address <Index> in
//! the interference.
const Intf_SectionLine& LineValue (const Standard_Integer Index) const;
//! Gives the number of zones of tangence in the interference.
Standard_Integer NbTangentZones() const;
//! Gives the zone of tangence at address Index in the
//! interference.
const Intf_TangentZone& ZoneValue (const Standard_Integer Index) const;
//! Gives the tolerance used for the calculation.
Standard_Real GetTolerance() const;
//! Tests if the polylines of intersection or the zones of
//! tangence contain the point of intersection <ThePnt>.
Standard_EXPORT Standard_Boolean Contains (const Intf_SectionPoint& ThePnt) const;
//! Inserts a new zone of tangence in the current list of
//! tangent zones of the interference and returns True
//! when done.
Standard_EXPORT Standard_Boolean Insert (const Intf_TangentZone& TheZone);
//! Insert a new segment of intersection in the current list of
//! polylines of intersection of the interference.
Standard_EXPORT void Insert (const Intf_SectionPoint& pdeb, const Intf_SectionPoint& pfin);
Standard_EXPORT void Dump() const;
protected:
//! Empty constructor
Standard_EXPORT Intf_Interference(const Standard_Boolean Self);
//! Destructor is protected, for safer inheritance
~Intf_Interference () {}
//! Only one argument for the intersection.
Standard_EXPORT void SelfInterference (const Standard_Boolean Self);
Intf_SeqOfSectionPoint mySPoins;
Intf_SeqOfSectionLine mySLines;
Intf_SeqOfTangentZone myTZones;
Standard_Boolean SelfIntf;
Standard_Real Tolerance;
private:
};
#include <Intf_Interference.lxx>
#endif // _Intf_Interference_HeaderFile
|
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <algorithm>
using namespace std;
string envVar[50];
string commands[50];
pid_t back_pids[50];
string back_commands[50];
static int back_count;
void parseEnv(char* inp)
{
string input(inp);
string delimiter = ":";
size_t pos = 0;
int i=0;
while((pos=input.find(delimiter)) != string::npos){
envVar[i++] = input.substr(0,pos);
input.erase(0,pos+delimiter.length());
}
}
void addBackgroundProcess(pid_t pid, string command)
{
back_pids[back_count] = pid;
back_commands[back_count] = command;
back_count++;
}
void printBackgroundProcesses()
{
//cout << "count = " << back_count << endl;
if(back_count > 0)
{
cout << "Process ID\tCommand Line" << endl;
for(int i = 0; i < back_count; i++)
cout << back_pids[i] << "\t\t" << back_commands[i] << endl;
}
else
cout << "No background processes are running" << endl;
}
bool isBackgroundProcess(pid_t pid)
{
bool flag = false;
for(int i = 0; i < back_count; i++)
if(back_pids[i] == pid)
{
flag = true;
break;
}
return flag;
}
void killBackgroundProcesses()
{
for(int i = 0; i < back_count; i++)
kill(back_pids[i], SIGKILL);
}
void removeBackgroundProcess(pid_t pid)
{
int i = 0;
while(pid != back_pids[i++]);
for(i--;i < back_count - 1; i++)
{
back_pids[i] = back_pids[i+1];
back_commands[i] = back_commands[i+1];
}
back_pids[i] = 0;
back_commands[i] = "";
back_count--;
}
int getLength(string array[])
{
int i = 0;
while(array[i] != "")
i++;
return i;
}
int index(string val)
{
int length = getLength(commands);
for(int i = 0; i < length; i++)
if(commands[i] == val)
return i;
return -1;
}
void clearCommands()
{
for(int i=0; i < 50; i++)
commands[i] = "";
}
void printArray(char* array[])
{
int i =0;
while(array[i] != NULL)
{
cout << "value " << i+1 << ": " << array[i] << endl;
i++;
}
}
string findPath(string command)
{
if(access((command).c_str(), F_OK) == 0)
return command;
for(int i = 0; i < getLength(envVar); i++)
{
if(access((envVar[i] + "/" + command).c_str(), F_OK) == 0)
return envVar[i] + "/" + command;
}
return "";
}
string nextDelimiter(string input)
{
string delmtr = " ";
string nextDelmtr = "";
size_t pos2 = 0, pos1 = 0;
pos1 = input.find(delmtr);
nextDelmtr = delmtr;
delmtr = "<";
pos2 = input.find(delmtr);
if(pos1 > pos2)
{
pos1 = pos2;
nextDelmtr = delmtr;
}
delmtr = ">";
pos2 = input.find(delmtr);
if(pos1 > pos2)
{
pos1 = pos2;
nextDelmtr = delmtr;
}
delmtr = "|";
pos2 = input.find(delmtr);
if(pos1 > pos2)
{
pos1 = pos2;
nextDelmtr = delmtr;
}
delmtr = "&";
pos2 = input.find(delmtr);
if(pos1 > pos2)
{
pos1 = pos2;
nextDelmtr = delmtr;
}
delmtr = "\t";
pos2 = input.find(delmtr);
if(pos1 > pos2)
{
pos1 = pos2;
nextDelmtr = delmtr;
}
return nextDelmtr;
}
string getCommand(string input_line){
string delimiter;
string com;
size_t pos = 0;
//command
input_line.erase(input_line.begin(), std::find_if(input_line.begin(), input_line.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
delimiter = nextDelimiter(input_line);
pos=input_line.find(delimiter);
com = input_line.substr(0,pos);
return com;
}
void parseInput(string input_line)
{
string delimiter;
size_t pos = 0;
int i = 0;
//command
input_line.erase(input_line.begin(), std::find_if(input_line.begin(), input_line.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
delimiter = nextDelimiter(input_line);
while((pos = input_line.find(delimiter)) != string::npos){
if(delimiter != " " && delimiter != "" && pos == 0)
{
commands[i++] = delimiter;
input_line.erase(0,pos+delimiter.length());
input_line.erase(input_line.begin(), std::find_if(input_line.begin(), input_line.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
delimiter = nextDelimiter(input_line);
continue;
}
commands[i++] = input_line.substr(0,pos);
input_line.erase(0,pos+delimiter.length());
input_line.erase(input_line.begin(), std::find_if(input_line.begin(), input_line.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
//special characters
if(delimiter != " " && delimiter != "" && delimiter != "\t")
{
commands[i++] = delimiter;
}
delimiter = nextDelimiter(input_line);
}
if(input_line != "")
commands[i] = input_line;
}
int main()
{
string input_line;
parseEnv(getenv("PATH"));
back_count = 0;
while(1)
{
cout << "MyShell: ";
getline(cin, input_line);
string command = getCommand(input_line);
clearCommands();
parseInput(input_line);
//Built in commands
if(strcmp(command.c_str(), "exit") == 0)
{
killBackgroundProcesses();
break;
}
if(strcmp(command.c_str(), "cd") == 0)
{
chdir(commands[1].c_str());
continue;
}
if(strcmp(command.c_str(), "") == 0)
{
continue;
}
if(strcmp(command.c_str(), "processes") == 0)
{
//remove completed background processes
pid_t pid = fork();
if (pid == 0)
{
_exit(0);
}
pid_t apid;
while ((apid = wait(0)) != pid) {
if(isBackgroundProcess(apid)) {
removeBackgroundProcess(apid);
}
}
printBackgroundProcesses();
continue;
}
const char* path = findPath(command).c_str();
//generate argv
int length = getLength(commands);
bool isInputRedirect = false, isOutputRedirect = false, isInteractive = true, isPiped = false;
string file, pipe_commands;
char* argv[length+1];
int i;
for(i = 0; i < length; i++)
{
const char* temp = commands[i].c_str();
//cout << "arg " << i+1 << ": " << temp << endl;
if(commands[i] == ">" || commands[i] == "<" || commands[i] == "&" || commands[i] == "|")
{;
int ind;
if(index("&") != -1)
isInteractive = false;
if(index("|") != -1)
{
ind = index("|");
isPiped = true;
for(int j = ind+1; j < length; j++)
pipe_commands = pipe_commands + " " + commands[j];
}
if(commands[i] == "<")
{
isInputRedirect = true;
file = commands[i+1];
}
else if(commands[i] == ">")
{
isOutputRedirect = true;
file = commands[i+1];
}
break;
}
argv[i] = strdup(temp);
}
argv[i] = NULL;
//cout << "count = " << i << endl;
pid_t pid = fork();
path = findPath(command).c_str();
if(pid == 0)//child process
{
//input redirection
if(isInputRedirect)
{
int fd = open(file.c_str(), O_RDONLY);
close(0);
dup(fd);
close(fd);
}
//output redirection
if(isOutputRedirect)
{
int fd = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
close(1);
dup(fd);
close(fd);
}
if(isPiped)
{
int pd[2];
pipe(pd);
pid_t pipe_child = fork();
if(pipe_child == 0)
{
close(0);
dup(pd[0]);
close(pd[0]);
close(pd[1]);
clearCommands();
parseInput(pipe_commands);
const char* pipe_path = findPath(commands[0]).c_str();
int len = getLength(commands);
bool pipe_opRedirect = false;
string pipe_file;
char* pipe_argv[len+1];
int j;
for(j=0;j < len; j++)
{
if(commands[j] == "&")
break;
if(commands[j] == ">")
{
pipe_opRedirect = true;
pipe_file = commands[j+1];
break;
}
const char* temp = commands[j].c_str();
pipe_argv[j] = strdup(temp);
}
pipe_argv[j] = NULL;
//pipe output redirection
if(pipe_opRedirect)
{
//cout << "op pipe redirect" << endl;
int fd = open(pipe_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
close(1);
dup(fd);
close(fd);
}
const char* temp = strdup(pipe_path);
//cout << "pipe path= " << temp << " arg1 = " << pipe_argv[0] << endl;
execv(temp, pipe_argv);
perror("execv");
_exit(1);
}
else
{
close(1);
dup(pd[1]);
close(pd[1]);
close(pd[0]);
//cout << "pipe parent path= " << path << " arg1 = " << argv[0] << endl;
const char* temp = strdup(path);
execv(temp, argv);
perror("execv");
_exit(1);// failure
}
}
//cout << "reg path= " << path << " arg1 = " << argv[0] << endl;
const char* temp = strdup(path);
execv(temp, argv);
perror("execv");
_exit(1);// failure
}
else
{
if(isInteractive)
{
pid_t apid;
while ((apid = wait(0)) != pid) {
if(isBackgroundProcess(apid)) {
removeBackgroundProcess(apid);
}
}
}
else
{
addBackgroundProcess(pid, input_line);
}
}
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Allowed #if-ery: gcc/glibc version.
* Sort order: alphabetic among the simple, ad hoc for the conditional.
*/
#ifndef POSIX_SYS_CHOICE_GCC_H
#define POSIX_SYS_CHOICE_GCC_H __FILE__
/** \file choice_gcc.h system config relevant to gcc and glibc
*
* This file enables some SYSTEM_* defines that gcc and glibc ensure we do have
* available. It also ensures __GLIBC_PREREQ is defined, even when it's an
* anachronism, and implements work-arounds for some known historical bugs.
*/
#define SYSTEM_CONSTANT_DATA_IS_EXECUTABLE YES
#define SYSTEM_FORCE_INLINE YES
#define SYSTEM_INT64 YES
#define SYSTEM_INT64_LITERAL YES
#define SYSTEM_LOCAL_TYPE_AS_TEMPLATE_ARG NO
#define SYSTEM_LONGLONG YES
#define SYSTEM_MEMMEM POSIX_SYS_USE_NATIVE
#define SYSTEM_NAMESPACE YES
#define SYSTEM_NEWA_CHECKS_OVERFLOW NO
#define SYSTEM_TEMPLATE_ARG_DEDUCTION YES
#define SYSTEM_UINT64 YES
#define SYSTEM_UINT64_LITERAL YES
# ifdef __GLIBC__ /* known glibc bugs: see relevant man pages */
# ifdef __GNU_LIBRARY__
# if __GNU_LIBRARY__ < 5 /* __GLIBC__+5 == __GNU_LIBRARY__ when > 5. */
#undef __GLIBC_PREREQ
#define __GLIBC_PREREQ(maj, min) 0
# endif /* __GNU_LIBRARY__ was 1 in late libc 5, undefined early */
# endif
/* There's a known memmem bug (aside from the one worked round here) in glibc <
* 5.1; unfortunately, GNU libc < 5.1 didn't define even __GNU_LIBRARY__, let
* alone __GLIBC__, so we can't usefully test for it. Fortunately, it's now an
* antique which we can generally expect not to be using ! */
# if !__GLIBC_PREREQ(2, 2)
/* Mishanded empty "needle" */
#define memmem(h, hl, n, nl) ((nl) > 0 ? memmem(h, hl, n, nl) : (h))
# endif
# if !__GLIBC_PREREQ(2, 1)
/* glibc <= 2.0.6: wrong return when insufficient space. */
#undef SYSTEM_SNPRINTF
#undef SYSTEM_VSNPRINTF
#define SYSTEM_SNPRINTF NO
#define SYSTEM_VSNPRINTF NO
# endif /* glibc < 2.1 */
# ifndef va_copy /* <stdarg.h> C99 but not C89. */
/* Some systems may have __va_copy but not va_copy ... and this seemed to help
* with bug DSK-164341. */
# ifdef __va_copy
#define va_copy __va_copy
# endif
# endif /* va_copy */
# endif /* glibc bugs */
#endif /* POSIX_SYS_CHOICE_GCC_H */
|
#pragma once
#include <stdexcept>
#include <vector>
namespace replay
{
template <typename T> class rle_vector
{
public:
using backing_container = std::vector<std::pair<T, std::size_t>>;
using backing_iterator = typename backing_container::const_iterator;
using size_type = std::size_t;
using value_type = T;
class iterator
{
public:
using value_type = rle_vector::value_type;
using reference = value_type const&;
using pointer = value_type const*;
using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
iterator(backing_iterator backing, size_type index)
: backing_(backing)
, index_(index)
{
}
bool operator==(iterator const& rhs) const
{
return backing_ == rhs.backing_ && index_ == rhs.index_;
}
bool operator!=(iterator const& rhs) const
{
return backing_ != rhs.backing_ || index_ != rhs.index_;
}
iterator& operator++()
{
++index_;
if (index_ == backing_->second)
{
++backing_;
index_ = 0;
}
return *this;
}
iterator const operator++(int)
{
auto result = *this;
++(*this);
return result;
}
iterator& operator+=(size_type rhs)
{
auto new_index = index_ + rhs;
while (new_index > 0 && new_index >= backing_->second)
{
new_index -= backing_->second;
++backing_;
}
index_ = new_index;
return *this;
}
reference operator*() const
{
return backing_->first;
}
pointer operator->() const
{
return &backing_->first;
}
size_type repetition_count() const
{
return backing_->second - index_;
}
iterator operator+(size_type rhs) const
{
auto result = *this;
return result += rhs;
}
private:
backing_iterator backing_;
size_type index_;
};
rle_vector()
{
size_ = 0;
}
rle_vector(size_type count, T value)
: values_(1, std::make_pair(value, count))
, size_(count)
{
}
rle_vector(std::initializer_list<std::pair<T, std::size_t>> list)
: values_(list)
, size_(0)
{
for (auto const& each : values_)
size_ += each.second;
}
void push(T value, size_type count = 1)
{
if (count == 0)
{
throw std::invalid_argument("Cannot add element without repetitions");
}
values_.push_back(std::make_pair(value, count));
size_ += count;
}
iterator begin() const
{
return iterator(values_.begin(), 0);
}
iterator end() const
{
return iterator(values_.end(), 0);
}
size_type size() const
{
return size_;
}
bool empty() const
{
return values_.empty();
}
bool operator==(rle_vector const& rhs) const
{
return size_ == rhs.size_ && values_ == rhs.values_;
}
bool operator!=(rle_vector const& rhs) const
{
return !(*this == rhs);
}
typename backing_container::value_type const* data() const
{
return values_.data();
}
private:
backing_container values_;
size_type size_;
};
} // namespace replay
|
#include "H/sound.h"
char MasterVolume;
void PlaySound(uint32 nFrequence, char Volume) {
uint32 Div;
uint8 tmp;
if (Volume > 100){
char invert2[99];
for (char i = 100; i>0; i--) invert2[i] = i;
Volume = invert2[Volume];
float Volpercent = Volume / 100;
int volpercent2 = Volpercent*100;
nFrequence=nFrequence/volpercent2;
}
Div = 1193180 / nFrequence;
outb(0x43, 0xb6);
outb(0x42, (uint8) (Div) );
outb(0x42, (uint8) (Div >> 8));
tmp = inb(0x61);
if (tmp != (tmp | 3)) {
outb(0x61, tmp | 3);
}
}
void noSound(){
uint8 tmp = inb(0x61) & 0xFC;
outb(0x61, tmp);
}
void beep(){
PlaySound(1000,100);
noSound();
}
|
//×Ö·û´®Æ¥Å䣺KMPËã·¨
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
char a[1000000 + 10],b[10000 + 10];
int next[10000 + 10];
int main()
{
int n;
scanf("%d",&n);
a[0] = b[0] = '0';
while (n--)
{
scanf("%s",b+1);
scanf("%s",a+1);
int l1 = strlen(a),l2 = strlen(b);
next[0] = -1;next[1] = 0;
for (int i = 2;i < l2; i++)
{
int j = next[i-1];
while (j >= 0 && b[j+1] != b[i]) j = next[j];
next[i] = j+1;
}
int j = 0,ans = 0;
for (int i = 1;i < l1; i++)
{
while (j >= 0 && b[j+1] != a[i]) j = next[j];
++j;
if (j+1 == l2) ans++;
}
printf("%d\n",ans);
}
return 0;
}
|
#include <string>
#include "AllinProc.h"
#include "HallManager.h"
#include "Logger.h"
#include "Room.h"
#include "Configure.h"
#include "ErrorMsg.h"
#include "GameCmd.h"
#include "ProcessManager.h"
REGISTER_PROCESS(CLIENT_MSG_ALL_IN, AllinProc)
AllinProc::AllinProc()
{
this->name = "AllinProc" ;
}
AllinProc::~AllinProc()
{
}
int AllinProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket,Context* pt)
{
int cmd = pPacket->GetCmdType();
short seq = pPacket->GetSeqNum();
int uid = pPacket->GetUid();
int uid_b = pPacket->ReadInt();
int tid = pPacket->ReadInt();
short svid = tid >> 16;
short realTid = tid & 0x0000FFFF;
BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler);
if (uid != uid_b)
{
ULOGGER(E_LOG_ERROR, uid) << "fucking userid operator uid=" << uid_b;
return sendErrorMsg(clientHandler, cmd, uid, 4, _EMSG_(4), seq);
}
_LOG_DEBUG_("==>[AllinProc] [0x%04x] uid[%d]\n", cmd, uid);
_LOG_DEBUG_("[DATA Parse] tid=[%d] svid=[%d] reallTid[%d]\n", tid, svid, realTid);
Room* room = Room::getInstance();
Table* table = room->getTable(realTid);
if (table == NULL)
{
_LOG_ERROR_("[AllinProc] uid=[%d] tid=[%d] realTid=[%d] Table is NULL\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -2, _EMSG_(-2), seq);
}
Player* player = table->getPlayer(uid);
if (player == NULL)
{
_LOG_ERROR_("[AllinProc] uid=[%d] tid=[%d] realTid=[%d] Your not in This Table\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -1, _EMSG_(-1), seq);
}
if (!player->isActive())
{
_LOG_ERROR_("[AllinProc] uid=[%d] tid=[%d] realTid=[%d] tm_nStatus=[%d] is not active\n",uid, tid, realTid, table->m_nStatus);
return sendErrorMsg(clientHandler, cmd, uid, -11, _EMSG_(-11), seq);
}
if (table->m_nCurrBetUid != uid)
{
_LOG_ERROR_("[AllinProc] uid=[%d] tid=[%d] realTid=[%d] betUid[%d] is not this uid\n",uid, tid, realTid, table->m_nCurrBetUid);
return sendErrorMsg(clientHandler, cmd, uid, -12, _EMSG_(-12), seq);
}
if (player->m_lMoney <= 0 && player->m_AllinCoin > 0)
{
_LOG_ERROR_("[AllinProc] uid=[%d] tid=[%d] realTid=[%d] player->m_lMoney=[%ld] countmoney[%ld]\n",uid, tid, realTid, player->m_lMoney, player->m_lSumBetCoin);
return sendErrorMsg(clientHandler, cmd, uid, -4, _EMSG_(-4), seq);
}
if (table->m_bIsOverTimer)
{
_LOG_ERROR_("[AllinProc] table is IsOverTimer uid=[%d] tid=[%d] realTid=[%d] Table Status=[%d]\n",uid, tid, realTid, table->m_nStatus);
return sendErrorMsg(clientHandler, cmd, uid, 2, _EMSG_(2), seq);
}
int64_t betmoney = player->m_AllinCoin;//table->FormatValue(player->m_bCardStatus, player->m_AllinCoin, table->m_BetMaxCardStatus);
if (betmoney > table->m_lCurrBetMax)
{
table->m_lCurrBetMax = player->m_AllinCoin;
table->m_BetMaxCardStatus = player->m_bCardStatus;
table->NotifyUnknowCardMaxNum(NULL);
}
table->m_lHasAllInCoin = player->m_AllinCoin;
player->m_bAllin = true;
player->setActiveTime(time(NULL));
table->playerBetCoin(player, betmoney);
_LOG_INFO_("[AllinProc] Uid=[%d] GameID=[%s] AllinMoney=[%ld] BetCountMoney=[%ld] currRound=[%d]\n", player->id, table->getGameID(), betmoney, player->m_lSumBetCoin, table->m_bCurrRound);
player->recordAllIn(table->m_bCurrRound , betmoney);
//设置下一个应该下注的用户
Player* nextplayer = table->getNextBetPlayer(player, OP_ALLIN);
if(table->iscanGameOver())
nextplayer = NULL;
int i = 0;
for(i = 0; i < table->m_bMaxNum; ++i)
{
if(table->player_array[i])
{
sendAllinInfoToPlayers(table->player_array[i], table, player, betmoney , nextplayer,seq);
}
}
if(table->iscanGameOver())
return table->gameOver();
return 0;
}
int AllinProc::sendAllinInfoToPlayers(Player* player, Table* table, Player* allinplayer, int64_t betmoney,Player* nextplayer, short seq)
{
int svid = Configure::getInstance()->m_nServerId;
int tid = (svid << 16)|table->id;
OutputPacket response;
response.Begin(CLIENT_MSG_ALL_IN, player->id);
if(player->id == allinplayer->id)
response.SetSeqNum(seq);
response.WriteShort(0);
response.WriteString("");
response.WriteInt(player->id);
response.WriteShort(player->m_nStatus);
response.WriteInt(tid);
response.WriteShort(table->m_nStatus);
response.WriteByte(table->m_bCurrRound);
response.WriteInt(allinplayer->id);
response.WriteInt64(betmoney);
response.WriteInt64(allinplayer->m_lSumBetCoin);
response.WriteInt64(allinplayer->m_lMoney);
response.WriteInt64(table->m_lCurrBetMax);
response.WriteInt(nextplayer ? nextplayer->id : 0);
response.WriteInt64(player->m_lSumBetCoin);
response.WriteInt64(player->m_lMoney);
response.WriteShort(player->optype);
response.WriteInt64(table->m_lSumPool);
response.WriteInt64(player->m_AllinCoin);
response.WriteByte(player->m_bCardStatus);
response.End();
_LOG_DEBUG_("<==[AllinProc] Push [0x%04x] to uid=[%d]\n", CLIENT_MSG_ALL_IN, player->id);
_LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n");
_LOG_DEBUG_("[Data Response] uid=[%d]\n",player->id);
_LOG_DEBUG_("[Data Response] m_nStatus=[%d]\n",player->m_nStatus);
_LOG_DEBUG_("[Data Response] m_lCurrBetMax=[%d]\n", table->m_lCurrBetMax);
_LOG_DEBUG_("[Data Response] optype=[%d]\n", player->optype);
_LOG_DEBUG_("[Data Response] m_bCurrRound=[%d]\n", table->m_bCurrRound);
_LOG_DEBUG_("[Data Response] m_lMoney=[%d]\n", player->m_lMoney);
_LOG_DEBUG_("[Data Response] nextplayer=[%d]\n", nextplayer ? nextplayer->id : 0);
_LOG_DEBUG_("[Data Response] m_AllinCoin=[%d]\n", player->m_AllinCoin);
if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0)
_LOG_ERROR_("[AllinProc] Send To Uid[%d] Error!\n", player->id);
return 0;
}
int AllinProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt )
{
_NOTUSED(clientHandler);
_NOTUSED(inputPacket);
_NOTUSED(pt);
return 0;
}
|
#include "Object.hpp"
Object::Object(){
}
Object::~Object(){
}
void Object::update() {
}
|
// Copyright 2019 The WCT(Wisdom City Times) Authors. All rights reserved.
#ifndef CHROME_BROWSER_UI_VIEWS_TABS_BIG_POPUP_THUMBNAIL_H_
#define CHROME_BROWSER_UI_VIEWS_TABS_BIG_POPUP_THUMBNAIL_H_
#include <map>
#include <memory>
#include <vector>
#include "base/macros.h"
#include "chrome/browser/ui/views/tabs/popup_thumbnail.h"
#include "ui/gfx/animation/animation_delegate.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class ImageView;
class Label;
} // namespace views
class BigPopupThumbnail : public PopupThumbnail,
public views::WidgetDelegateView,
public gfx::AnimationDelegate,
public views::WidgetObserver,
public base::SupportsWeakPtr<BigPopupThumbnail> {
public:
BigPopupThumbnail(Browser* browser);
~BigPopupThumbnail() override;
// Overriden from PopupThumbnail.
bool IsShowing() override;
bool Show(const Tab* tab,
const gfx::Image& thumbnail,
const base::string16& title) override;
void UpdateThumbnail(const Tab* tab, const gfx::Image& thumbnail) override;
void UpdateTitle(const Tab* tab, const base::string16& title) override;
void TabRemoved(const Tab* tab) override;
void Hide() override;
void Close() override;
// Overriden from views::View.
void OnPaint(gfx::Canvas* canvas) override;
// Overriden from views::WidgetDelegate.
views::View* GetContentsView() override;
// Overriden from gfx::AnimationDelegate.
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
// Overriden from views::WidgetObserver.
void OnWidgetClosing(views::Widget* widget) override;
void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override;
private:
class TabState;
// If |adjust| is true, the coresponding |TabState| will be created if not
// exists and stored in the last of |tabs_showing_order_|.
TabState* GetTabState(const Tab* tab, bool adjust);
void RemoveTabState(const Tab* tab);
gfx::Rect CalculateWidgetBounds();
gfx::Rect CalculateThumbnailBounds();
// Convinient methods for TabState.
void SchedulePaintForTab();
void HideIfNothingToShow();
gfx::SlideAnimation animation_;
bool observing_;
std::map<const Tab*, std::unique_ptr<TabState>> tab_states_;
std::vector<const Tab*> tabs_showing_order_;
DISALLOW_COPY_AND_ASSIGN(BigPopupThumbnail);
};
#endif // CHROME_BROWSER_UI_VIEWS_TABS_BIG_POPUP_THUMBNAIL_H_
|
vector < vector < pii > > g ;
int n, m ;
void dijkstra(int s, vll& d, vi& p){
d.assign(n + 1, Inf) ;
p.assign(n + 1, -1) ;
priority_queue < pair < ll, int >, vector < pair < ll, int > > , greater< pair < ll, int > > > pq ;
d[s] = 0 ;
pq.push(make_pair(0, s)) ;
while(!pq.empty()){
int v = pq.top().second ;
ll dv = pq.top().first ;
pq.pop() ;
if(dv != d[v])continue ;
for(auto i : g[v]){
if(d[v] + i.ss < d[i.ff]){
d[i.ff] = d[v] + i.ss ;
pq.push(make_pair(d[i.ff], i.ff)) ;
p[i.ff] = v ;
}
}
}
}
|
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
//Lendo corrente
#define tensao 110
const int sensorIn = A0;
int mVperAmp = 100;
double Vpp = 0;
double Vp = 0;
double Vrms = 0;
double Irms = 0;
double consumo;
//Lendo corrente
//Conexão WiFi
const char* ssid = "TrocoSenhaPorCerveja";
const char* password = "renatobike";
//Conexão WiFi
ESP8266WebServer server(80);
const int led = 2;
// Atualiza Página
void handleRoot() {
digitalWrite(led, 1);
String textoHTML;
textoHTML = "<p>Ola!! Aqui é o <b>ESP8266</b> falando!</p> ";
textoHTML += "<p>Corente: "; textoHTML += getIrms(); textoHTML += "A. </p>";
textoHTML += "<p>Potência: "; textoHTML += (getIrms()*127); textoHTML += "W. </p>";
textoHTML += "<p>Consumo: "; textoHTML += (consumo_kWh()/1000); textoHTML += "kWh. </p>";
textoHTML += "<p>Consumo: "; textoHTML += consumo_kWh(); textoHTML += "kWh. </p>";
server.send(200, "text/html", textoHTML);
digitalWrite(led, 0);
}
// Atualiza Página
// Se não acha Página
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
// Se não acha Página
void setup(void){
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(11520);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
double getVPP()
{
double result;
int readValue;
int maxValue = 0;
int minValue = 1024;
uint32_t start_time = millis();
while((millis()-start_time) < 1000)
{
readValue = analogRead(sensorIn);
if(readValue > maxValue)
{
maxValue = readValue;
}
if(readValue < minValue)
{
minValue = readValue;
}
}
result = ((maxValue - minValue)* 5.0)/1024.0;
return result;
}
double getIrms()
{
Vpp = getVPP();
Vp = Vpp/2.0;
Vrms = Vp*0.707;
Irms = ((Vrms*1000)/mVperAmp) - 0.09;
if(Irms == 0.3)
{
return 0.0;
}
return Irms;
}
double consumo_kWh()
{
uint32_t start_time = millis();
if(millis()- start_time > 1000){
consumo += (getIrms()*tensao)/3600000; //CONSUMO PELA VARIAÇÃO DE UM SEGUNDO. CONVERSÃO PARA kWh
}
return consumo;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef CSS_ANIMATIONS_H
#define CSS_ANIMATIONS_H
#ifdef CSS_ANIMATIONS
#include "modules/logdoc/elementref.h"
#include "modules/util/OpHashTable.h"
class CSSCollection;
class HTML_Element;
class CSS_Properties;
class CSS_Animation;
class CSS_ElementAnimations;
class CSS_AnimationManager;
class LayoutProperties;
struct TransitionDescription;
/** Represents the list of animations applied to one single element.
Owned by the animation manager. */
class CSS_ElementAnimations : public ElementRef
{
public:
CSS_ElementAnimations(FramesDocument* doc, HTML_Element* element) : ElementRef(element), m_doc(doc) {}
~CSS_ElementAnimations() { m_animations.Clear(); }
/** Search this list of animations for an untraced animation
matching 'name'. If such an animation exists, that animation
is traced and returned. Used to "garbage-collect" animations
that should no longer apply. */
CSS_Animation* TraceAnimation(const uni_char* name);
/** Returns TRUE if one or more animations were removed */
BOOL Sweep();
/** Append an animation to the list for animation for this
element. */
void Append(CSS_Animation* animation);
/** Apply current state of animations for this element to cssprops
and the animation manager. */
void Apply(CSS_AnimationManager* animation_manager, double runtime_ms, CSS_Properties* cssprops, BOOL apply_partially);
/** An animation-delay has timed out for this element. Reload
style. */
void OnAnimationDelayTimeout();
/** Element removed from document, stop animations. */
virtual void OnRemove(FramesDocument* document);
/** Element deleted, stop animations and delete this. */
virtual void OnDelete(FramesDocument* document);
private:
List<CSS_Animation> m_animations;
/** The document of the animated element to which events are sent
to. */
FramesDocument* m_doc;
};
/** The animation manager is a prolonged part of a CSSCollection,
specifically responsible for the current set of animations within
that CSSCollection.
It owns one hash table that maps elements to animations, one set
of animations for each element.
It also owns a list of transition descriptions, populated by
animations when they request interpolation between two CSS
values. */
class CSS_AnimationManager
{
public:
CSS_AnimationManager(CSSCollection* css_collection) : m_css_collection(css_collection) {}
~CSS_AnimationManager() { m_animations.DeleteAll(); }
/** Retrieve the current document. */
FramesDocument* GetFramesDocument() const;
/** Apply the current state of all animations. Called from the css
collection when reloading CSS properties. */
void ApplyAnimations(HTML_Element* elm, double runtime_ms, CSS_Properties* cssprops, BOOL apply_partially);
/** Start and update animations according to what is defined by
the animation properties in 'cascade'. Called during property
reload, but after we have calculated computed style. */
OP_STATUS StartAnimations(LayoutProperties* cascade, double runtime_ms);
/** Register an property as currently animating. Called from the
individual animations. */
void RegisterAnimatedProperty(TransitionDescription* description);
/** Extract the current set of transitions, as created by the
current set of animations. This list may be used as input when
updating transitions. */
Head& CurrentTransitionList() { return m_current_transitions; }
/** Remove animations for a specific element. Used when cleaning
up after an element that has been removed from the tree. */
void RemoveAnimations(HTML_Element* element);
private:
CSS_ElementAnimations* GetAnimations(HTML_Element* element);
OP_STATUS SetupAnimation(HTML_Element* element, CSS_ElementAnimations*& animations);
OpPointerHashTable<const HTML_Element, CSS_ElementAnimations> m_animations;
List<TransitionDescription> m_current_transitions;
CSSCollection* m_css_collection;
};
#endif // CSS_ANIMATIONS
#endif // CSS_ANIMATIONS_H
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <sstream>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <numeric>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MOD 1000000007
#define BN 11111
#define MLEN 11
int n, m;
char s[111][111];
int next[BN][11], dep[BN], vn = 1, root = 0;
vector<int> q[BN];
int suf[BN], last[BN], p[BN], len[BN], go[BN][11];
LL f[111][BN][12];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
cerr << sizeof(f) << endl;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
cin >> s[i];
int v = root;
for (int j = 0; s[i][j]; j++) {
int ch = s[i][j] - 'a';
if (!next[v][ch]) last[vn] = ch, p[vn] = v, dep[vn] = j + 1, next[v][ch] = vn++;
v = next[v][ch];
}
len[v] = dep[v];
}
for (int i = 0; i < vn; ++i) q[dep[i]].push_back(i);
for (int i = 0; i < BN; i++)
for (int j = 0; j < q[i].size(); j++) {
int v = q[i][j];
if (v == root || p[v] == root)
suf[v] = root;
else
suf[v] = go[suf[p[v]]][last[v]];
for (int t = 0; t < 10; t++)
if (next[v][t])
go[v][t] = next[v][t];
else
go[v][t] = go[suf[v]][t];
len[v] = max(len[v], len[suf[v]]);
}
LL res = 0;
f[0][0][0] = 1;
for (int i = 0; i <= n; i++)
for (int j = 0; j < vn; j++)
for (int l = 0; l < MLEN; l++) {
int F = f[i][j][l];
if (F > 0) {
if (i == n) {
if (l == 0)
res = (res + F) % MOD;
} else {
for (int t = 0; t < 10; ++t) {
int v = go[j][t];
if (dep[v] < l + 1) continue;
int len1 = l + 1;
if (len[v] >= len1) len1 = 0;
f[i + 1][v][len1] = (f[i + 1][v][len1] + F) % MOD;
}
}
}
}
cout << res << endl;
return 0;
}
|
#include "cpptest.h"
CPPTEST_CONTEXT("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/ThreadPool/ThreadedWorker.cpp");
CPPTEST_TEST_SUITE_INCLUDED_TO("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/ThreadPool/ThreadedWorker.cpp");
class TestSuite_executeWorkItem_a2085ac9 : public CppTest_TestSuite
{
public:
CPPTEST_TEST_SUITE(TestSuite_executeWorkItem_a2085ac9);
CPPTEST_TEST(test_executeWorkItem_1);
CPPTEST_TEST_SUITE_END();
void setUp();
void tearDown();
void test_executeWorkItem_1();
};
CPPTEST_TEST_SUITE_REGISTRATION(TestSuite_executeWorkItem_a2085ac9);
void TestSuite_executeWorkItem_a2085ac9::setUp()
{
FUNCTION_ENTRY( "setUp" );
FUNCTION_EXIT;
}
void TestSuite_executeWorkItem_a2085ac9::tearDown()
{
FUNCTION_ENTRY( "tearDown" );
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_BEGIN test_executeWorkItem_1 */
/* CPPTEST_TEST_CASE_CONTEXT void TA_Base_Core::ThreadedWorker::executeWorkItem(TA_Base_Core::IWorkItemPtr) */
void TestSuite_executeWorkItem_a2085ac9::test_executeWorkItem_1()
{
FUNCTION_ENTRY( "test_executeWorkItem_1" );
///* Pre-condition initialization */
///* Initializing argument 0 (this) */
//::TA_Base_Core::ThreadedWorker _cpptest_TestObject ;
///* Initializing argument 1 (workItem) */
// /* Initializing constructor argument 1 (unknown) */
// Y * _arg1_0 = 0 ;
//::boost::shared_ptr< ::TA_Base_Core::IWorkItem> _workItem (_arg1_0);
///* Tested function call */
//_cpptest_TestObject.executeWorkItem(_workItem);
///* Post-condition check */
//CPPTEST_POST_CONDITION_BOOL("bool _cpptest_TestObject.m_threadRunning", ( _cpptest_TestObject.m_threadRunning ));
//CPPTEST_POST_CONDITION_BOOL("bool _cpptest_TestObject.m_threadWorkerBusy", ( _cpptest_TestObject.m_threadWorkerBusy ));
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_END test_executeWorkItem_1 */
|
#pragma once
#include <string>
#include <vector>
#include <stack>
class Calculator {
public:
static int Calculate(const std::string& expression);
private:
struct Token {
enum class TokenType {
kUnknown,
kConstant,
kUnaryMinus,
kAddition,
kMultiply,
kDivide,
kSubtraction,
kAbs,
kMod,
kOpeningBrace,
kClosingBrace,
};
int value;
TokenType token_type;
Token();
explicit Token(const std::string& str);
explicit Token(int number);
int Priority() const;
int CountOperands() const;
};
static std::vector<Token> StringToVectorOfToken(const std::string& str_expr);
static std::vector<Token> ConvertToPolishNotation
(const std::vector<Token>& tokens);
std::stack<int> stack_values_;
void Process(const Calculator::Token& token);
friend class CalculatorTester;
};
|
/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: index cell implementation for C++ libLAS
* Author: Gary Huber, gary@garyhuberart.com
*
******************************************************************************
*
* (C) Copyright Gary Huber 2010, gary@garyhuberart.com
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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 <liblas/detail/index/indexcell.hpp>
#include <cmath>
#include <limits>
using namespace std;
namespace liblas { namespace detail {
IndexCell::IndexCell() :
m_FileOffset(0),
m_NumPoints(0),
m_MinZ((std::numeric_limits<ElevExtrema>::max())),
m_MaxZ((std::numeric_limits<ElevExtrema>::min()))
{
} // IndexCell::IndexCell
void IndexCell::SetFileOffset(TempFileOffsetType fos)
{
m_FileOffset = fos;
} // IndexCell::SetFileOffset
void IndexCell::SetNumPoints(uint32_t nmp)
{
m_NumPoints = nmp;
} // IndexCell::SetNumPoints
TempFileOffsetType IndexCell::GetFileOffset(void) const
{
return(m_FileOffset);
} // IndexCell::GetFileOffset
uint32_t IndexCell::GetNumRecords(void) const
{
return((uint32_t)m_PtRecords.size());
} // IndexCell::GetNumRecords
uint32_t IndexCell::GetNumPoints(void) const
{
return(m_NumPoints);
} // IndexCell::GetNumPoints
uint32_t IndexCell::GetNumSubCellRecords(void) const
{
return((uint32_t)m_SubCellRecords.size());
} // IndexCell::GetNumSubCellRecords
uint32_t IndexCell::GetNumZCellRecords(void) const
{
return((uint32_t)m_ZCellRecords.size());
} // IndexCell::GetNumZCellRecords
bool IndexCell::RoomToAdd(uint32_t a)
{
return (m_PtRecords[a] < (std::numeric_limits<ConsecPtAccumulator>::max()));
} // IndexCell::RoomToAdd
void IndexCell::AddPointRecord(uint32_t a)
{
m_PtRecords[a] = 1;
++m_NumPoints;
} // IndexCell::AddPointRecord
void IndexCell::AddPointRecord(uint32_t a, uint8_t b)
{
m_PtRecords[a] = b;
m_NumPoints += b;
} // IndexCell::AddPointRecord
bool IndexCell::IncrementPointRecord(uint32_t a)
{
IndexCellData::iterator MyIT;
if ((MyIT = m_PtRecords.find(a)) != m_PtRecords.end())
{
if (MyIT->second < (std::numeric_limits<ConsecPtAccumulator>::max()))
{
++MyIT->second;
++m_NumPoints;
return true;
} // if
} // if
return false;
} // IndexCell::IncrementPointRecord
void IndexCell::RemoveMainRecords(void)
{
m_PtRecords.clear();
} // IndexCell::RemoveRecords
void IndexCell::RemoveAllRecords(void)
{
IndexSubCellData::iterator MyIT;
m_PtRecords.clear();
for (MyIT = m_ZCellRecords.begin(); MyIT != m_ZCellRecords.end(); ++MyIT)
{
MyIT->second.clear();
} // if
m_ZCellRecords.clear();
for (MyIT = m_SubCellRecords.begin(); MyIT != m_SubCellRecords.end(); ++MyIT)
{
MyIT->second.clear();
} // if
m_SubCellRecords.clear();
} // IndexCell::RemoveRecords
void IndexCell::UpdateZBounds(double TestZ)
{
if (TestZ > (std::numeric_limits<ElevExtrema>::max()))
m_MaxZ = (std::numeric_limits<ElevExtrema>::max());
else if (TestZ < (std::numeric_limits<ElevExtrema>::min()))
m_MinZ = (std::numeric_limits<ElevExtrema>::min());
else
{
if (TestZ > m_MaxZ)
m_MaxZ = static_cast<ElevExtrema>(ceil(TestZ));
if (TestZ < m_MinZ)
m_MinZ = static_cast<ElevExtrema>(floor(TestZ));
} // else
} // IndexCell::UpdateZBounds
ElevRange IndexCell::GetZRange(void) const
{
return (m_MaxZ > m_MinZ ? static_cast<ElevRange>(m_MaxZ - m_MinZ): 0);
} // IndexCell::GetZRange
void IndexCell::AddZCell(uint32_t a, uint32_t b)
{
IndexSubCellData::iterator MyIT;
if ((MyIT = m_ZCellRecords.find(a)) != m_ZCellRecords.end())
{
MyIT->second[b] = 1;
} // if
else
{
IndexCellData p;
p[b] = 1;
m_ZCellRecords[a] = p;
} // else
} // IndexCell::AddZCell
bool IndexCell::IncrementZCell(uint32_t a, uint32_t b)
{
IndexSubCellData::iterator MyIT;
IndexCellData::iterator YourIT;
if ((MyIT = m_ZCellRecords.find(a)) != m_ZCellRecords.end())
{
if ((YourIT = MyIT->second.find(b)) != MyIT->second.end())
{
if (YourIT->second < (std::numeric_limits<ConsecPtAccumulator>::max()))
{
++YourIT->second;
return true;
} // if
} // if
} // if
return false;
} // IndexCell::IncrementZCell
void IndexCell::AddSubCell(uint32_t a, uint32_t b)
{
IndexSubCellData::iterator MyIT;
if ((MyIT = m_SubCellRecords.find(a)) != m_SubCellRecords.end())
{
MyIT->second[b] = 1;
//MyIT->second.insert(b, 1);
} // if
else
{
IndexCellData p;
p[b] = 1;
m_SubCellRecords[a] = p;
} // else
} // IndexCell::AddSubCell
bool IndexCell::IncrementSubCell(uint32_t a, uint32_t b)
{
IndexSubCellData::iterator MyIT;
IndexCellData::iterator YourIT;
if ((MyIT = m_SubCellRecords.find(a)) != m_SubCellRecords.end())
{
if ((YourIT = MyIT->second.find(b)) != MyIT->second.end())
{
if (YourIT->second < (std::numeric_limits<ConsecPtAccumulator>::max()))
{
++YourIT->second;
return true;
} // if
} // if
} // if
return false;
} // IndexCell::IncrementSubCell
uint8_t IndexCell::GetPointRecordCount(uint32_t a)
{
return m_PtRecords[a];
} // IndexCell::GetPointRecordCount
const IndexCellData::iterator IndexCell::GetFirstRecord(void)
{
return (m_PtRecords.begin());
} // IndexCell::GetFirstRecord
const IndexCellData::iterator IndexCell::GetEnd(void)
{
return (m_PtRecords.end());
} // IndexCell::GetEnd
const IndexSubCellData::iterator IndexCell::GetFirstSubCellRecord(void)
{
return (m_SubCellRecords.begin());
} // IndexCell::GetFirstRecord
const IndexSubCellData::iterator IndexCell::GetEndSubCell(void)
{
return (m_SubCellRecords.end());
} // IndexCell::GetEnd
const IndexSubCellData::iterator IndexCell::GetFirstZCellRecord(void)
{
return (m_ZCellRecords.begin());
} // IndexCell::GetFirstRecord
const IndexSubCellData::iterator IndexCell::GetEndZCell(void)
{
return (m_ZCellRecords.end());
} // IndexCell::GetEnd
}} // namespace liblas detail
|
#include "game/GameModes.hpp"
HomeMode::HomeMode(){
gButtonSpriteSheetTexture = new LTexture();
background = new LTexture();
//Set sprites
for( int i = 0; i < BUTTON_SPRITE_TOTAL; ++i )
{
gSpriteClips[ i ].x = 0;
gSpriteClips[ i ].y = i * 200;
gSpriteClips[ i ].w = BUTTON_WIDTH;
gSpriteClips[ i ].h = BUTTON_HEIGHT;
}
gButtons[ 0 ] = new LButton(BUTTON_PRIM,gButtonSpriteSheetTexture,gSpriteClips);
gButtons[ 1 ] = new LButton(BUTTON_ALT,gButtonSpriteSheetTexture,gSpriteClips);
}
bool HomeMode::loadMediaHome(){
std::cout << "load media home" << std::endl;
bool success = true;
gButtons[0]->loadAudio();
gButtons[1]->loadAudio();
if( !gButtonSpriteSheetTexture->loadFromFile( "media/texture/sprites/menu_new.png" ) )
{
printf( "Failed to load button sprite texture!\n" );
success = false;
}
else
{
//Set buttons in corners
gButtons[ 0 ]->setPosition( 0, 0 );
gButtons[ 1 ]->setPosition( 0, BUTTON_HEIGHT +10);
}
if (!background->loadFromFile("media/texture/background.png")){
printf( "Failed to load background texture!\n" );
success = false;
}
return success;
}
void HomeMode::update(bool render){
background->renderBackground(NULL);
//Render buttons
for( int i = 0; i < TOTAL_BUTTONS; ++i )
{
gButtons[ i ]->render();
}
//Select mode
if (gButtons[0]->getMode()){
gButtons[0]->setMode(0);
gEngine->setGameMode(PLAY);
}
else if (gButtons[1]->getMode()){
gButtons[1]->setMode(0);
gEngine->setGameMode(QUIT);
}
}
void HomeMode::eventHandler(SDL_Event &e){
//Handle button events
for( int i = 0; i < TOTAL_BUTTONS; ++i )
{
gButtons[ i ]->handleEvent( &e );
}
}
void HomeMode::enterMode(){
if( !loadMediaHome() )
{
printf( "Failed to load media!\n" );
}
}
|
//
// Created by arnito on 4/06/17.
//
#ifndef BEAT_THE_BEAT_BALLOS1ACTOR_H
#define BEAT_THE_BEAT_BALLOS1ACTOR_H
#include "../Actor.h"
#include "../entities/Quote.h"
class Ballos1Actor : public Actor {
public:
Ballos1Actor(int playerId,Quote &q, Scene &s);
~Ballos1Actor();
void update(const sf::Time& deltatime);
void action(Inputs::Key key);
private:
Quote *_quote;
};
#endif //BEAT_THE_BEAT_BALLOS1ACTOR_H
|
#include <iostream>
#define mutqagrel_zangvac int array[5];
#define hashvel_zangvaci_mecaguyn_arjeq mutq(array);
#define tpel_zangvaci_mecaguyn_arjeq std::cout<<"Zangvaci mecguyn arjeqn e "<<maximum(array)<<"\n";
//Mutq funkcian mutqagrum e zangvaci elementnery
int mutq (int array[]) {
std::cout<<"Mutqagreq 5 chapanoc zangvaci elementnery ";
for (int i = 0; 5 > i; i++) {
std::cin>>array[i];
}
return array[5];
}
//maximum funkcian hashvum e muqagrvac zangvaci mecaguyn arjeqy
int maximum (int array [5]) {
int max = array[0];
for (int i = 1; 5 > i; i++){
if (array[i] > max){
max = array[i];
}
}
return max;
}
int main() {
mutqagrel_zangvac
hashvel_zangvaci_mecaguyn_arjeq
tpel_zangvaci_mecaguyn_arjeq
return 0;
}
|
#include "DynamicArray.h"
SeqStack* initStack(){
SeqStack* stack = (SeqStack*)malloc(sizeof(SeqStack));
for(int i=0; i<MAX_SIZE; i++){
stack->data[i] = NULL;
}
stack->size = 0;
return stack;
}
void pushStack(SeqStack* stack, void* data){
if(stack == NULL || data == NULL || stack->size == MAX_SIZE)
return;
stack->data[stack->size++] = data;
}
void popStack(SeqStack* stack){
if(stack == NULL || stack->size == 0)
return;
stack->data[stack->size--] == 0;
}
void* topStack(SeqStack* stack){
if(stack == NULL)
return NULL;
// printf("size: %d", stack->size);
return stack->data[stack->size-1];
}
int isEmpty(SeqStack* stack){
if(stack == NULL)
return 0;
if(stack->size == 0)
return SEQSTACK_TRUE;
return SEQSTACK_FALSE;
}
int sizeStack(SeqStack* stack){
return stack->size;
}
void clearStack(SeqStack* stack){
if(stack == NULL)
return;
for(int i=0; i<stack->size; i++)
stack->data[i] = NULL;
stack->size = 0;
}
void freeStack(SeqStack* stack){
if(stack==NULL)
return;
free(stack);
}
|
#include <iostream>
using namespace std;
int main() {
int i, j;
int *p1, *p2;
i = 2;
j = 5;
p1 = &i; // la valeur de p1 est l'adresse de i
cout << endl << "Contenu de p1 vaut : " << *p1 << endl; // Le contenu de p1 vaut 2
i = i + 1;
cout << "Contenu de p1 vaut : " << *p1 << endl; // Le contenu de p1 vaut 3
p2 = p1; // la valeur de p1 est la valeur de p1 (l'adresse de i)
*p2 = *p1 + j; // Le contenu de p2 (i) prend la valeur du contenu de p1(i) + j
cout << endl << "*p1 = " << *p1 << " *p2 = " << *p2 << endl; // *p1 = 8 et *p2 = 8
cout << "i = " << i << " j = " << j << endl; // i = 8 et j = 5
p1 = &j; // la valeur de p1 est maintenant l'adresse de j
*p1 = i + j; // Le contenu de p1 (j) prend la valeur de i+j
cout << endl << "*p1 = " << *p1 << " *p2 = " << *p2 << endl; // *p1 = 13 et *p2 = 8
cout << "i = " << i << " j = " << j << endl; // i = 8 et j = 13
return 0;
}
|
#include "pch.h"
#include "common.h"
#include <random>
using namespace std;
std::random_device dev;
std::mt19937 rng(dev());
uniform_real_distribution<float> rand_gen(-0.5f, 0.5f);
float rand_next() {
return rand_gen(rng);
}
float rand_next01() {
auto a = rand_gen(rng) + 0.5f;
if (a < 0.0f) return 0.0f;
if (a > 1.0f) return 1.0f;
return a;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 1000000000
int main()
{
int n, k;
cin >> n >> k;
vector<int> h(n);
vector<int> dp(n, INF);
for(int i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
//h.push_back(tmp); push_backは末尾に追加
h[i] = tmp;
}
dp[0] = 0;
for(int i = 0; i < n; i++)
{
for(int j = 1; j <= k && (i + j) < n; j++)
{
dp[i + j] = min(dp[i + j], dp[i] + abs(h[i] - h[i + j]));
//printf("%d %d %d\n", i,j,dp[i + j]);
}
}
cout << dp[n - 1] << endl;
}
|
#include<stdio.h>
#include<string>
#include<string.h>
using namespace std;
int main()
{
char s[200];
memset(s,0,sizeof(0));
scanf("%s",s);
int zero_d=0,dd=0;
int l=strlen(s), a , num[109] , b=0;
int e;//记录e的位置;
a=s[0]-'0';//a;
for(int i=2; i<l; i++)
{
if(s[i]=='e')
{
e=i;
break;
}
if(s[i]=='0')
zero_d++;//0的个数;
else
dd++;//不是0的个数;
}
int f=1;
for(int i=l-1; i>e; i--)
{
b+=(s[i]-'0')*f;//b
f*=10;
}
if(a==0&&b==0)//a,b都是0的情况;
{
if(zero_d==e-2)//d中全是0;
printf("0");
else
for(int i=0; i<e; i++)
printf("%c",s[i]);
}
else if(b==0&&a!=0)//b是0,a不是0;
{
if(zero_d==e-2)//d 全是0;
printf("%d",a);
else
{
for(int i=0; i<e; i++)
printf("%c",s[i]);
}
}
else if(a!=0&&b!=0)//同时不为0;
{
if(e-2<b)//b超过d的长度;
{
b-=e-2;//b代表的是此时d的长度;
printf("%d",a);
for(int i=2; i<e; i++)
printf("%c",s[i]);
for(int i=1; i<=b; i++)
printf("0");
}
else
{
printf("%d",a);
for(int i=2; i<=b+1; i++)
printf("%c",s[i]);
if(e-2!=b)//d的长度不等于b要求向后推的长度;
{
printf(".");
for(int i=b+2; i<e; i++)
printf("%c",s[i]);
}
}
}
return 0;
}
|
class 10Rnd_127x99_m107
{
weight = 1.5;
};
class 3rnd_Anzio_20x102mm
{
weight = 1.5;
};
class 5Rnd_762x51_M24
{
weight = 0.25;
};
class 5x_22_LR_17_HMR
{
weight = 0.25;
};
class 20Rnd_762x51_DMR
{
weight = 1;
};
class 5Rnd_17HMR
{
weight = 0.25;
};
class 5Rnd_127x108_KSVK
{
weight = 1.5;
};
class 10Rnd_762x54_SVD
{
weight = 0.5;
};
class 10Rnd_9x39_SP5_VSS
{
weight = 0.4;
};
class 20Rnd_9x39_SP5_VSS
{
weight = 0.8;
};
class 5Rnd_127x99_as50_CP
{
weight = 1.5;
};
class 5Rnd_127x99_as50
{
weight = 1.5;
};
class 5Rnd_86x70_L115A1
{
weight = 0.7;
};
class 10x_303
{
weight = 0.5;
};
class 10Rnd_762x51_CZ750
{
weight = 0.5;
};
class 7Rnd_86x70_MSR
{
weight = 1.3;
};
class 7Rnd_86x70_MSR_SD
{
weight = 1.3;
};
class 5Rnd_762x67_XM2010
{
weight = 1.5;
};
class 5Rnd_762x67_XM2010_SD
{
weight = 1.5;
};
class 5Rnd_408_CheyTac
{
weight = 1.5;
};
class 5Rnd_408_CheyTac_SD
{
weight = 1.5;
};
class 6Rnd_762x51_WA2000
{
weight = 1.5;
};
class 10Rnd_86x70_MRAD
{
weight = 1.5;
};
class 20Rnd_762x51_DMRSD
{
weight = 1;
};
class 20Rnd_762x51_RSASS
{
weight = 1;
};
class 20Rnd_762x51_RSASS_SD
{
weight = 1;
};
|
// Created on: 1995-12-01
// Created by: EXPRESS->CDL V0.2 Translator
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepVisual_PlanarExtent_HeaderFile
#define _StepVisual_PlanarExtent_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Real.hxx>
#include <StepGeom_GeometricRepresentationItem.hxx>
class TCollection_HAsciiString;
class StepVisual_PlanarExtent;
DEFINE_STANDARD_HANDLE(StepVisual_PlanarExtent, StepGeom_GeometricRepresentationItem)
class StepVisual_PlanarExtent : public StepGeom_GeometricRepresentationItem
{
public:
//! Returns a PlanarExtent
Standard_EXPORT StepVisual_PlanarExtent();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Standard_Real aSizeInX, const Standard_Real aSizeInY);
Standard_EXPORT void SetSizeInX (const Standard_Real aSizeInX);
Standard_EXPORT Standard_Real SizeInX() const;
Standard_EXPORT void SetSizeInY (const Standard_Real aSizeInY);
Standard_EXPORT Standard_Real SizeInY() const;
DEFINE_STANDARD_RTTIEXT(StepVisual_PlanarExtent,StepGeom_GeometricRepresentationItem)
protected:
private:
Standard_Real sizeInX;
Standard_Real sizeInY;
};
#endif // _StepVisual_PlanarExtent_HeaderFile
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 1995-2011
*/
#include "core/pch.h"
#ifdef ES_PERSISTENT_SUPPORT
#include "modules/ecmascript/structured/es_persistent.h"
#include "modules/ecmascript/ecmascript.h"
enum ES_PersistentTag
{
ES_PTAG_OBJECT_ARRAYBUFFER = 0x7fffffed,
ES_PTAG_OBJECT_TYPEDARRAY = 0x7fffffee,
ES_PTAG_NUMBER = 0x7fffffef,
ES_PTAG_NULL = 0x7ffffff0,
ES_PTAG_UNDEFINED = 0x7ffffff1,
ES_PTAG_BOOLEAN = 0x7ffffff2,
ES_PTAG_STRING = 0x7ffffff3,
ES_PTAG_STRING_AGAIN = 0x7ffffff4,
ES_PTAG_OBJECT = 0x7ffffff5,
ES_PTAG_OBJECT_BOOLEAN = 0x7ffffff6,
ES_PTAG_OBJECT_NUMBER = 0x7ffffff7,
ES_PTAG_OBJECT_STRING = 0x7ffffff8,
ES_PTAG_OBJECT_ARRAY = 0x7ffffff9,
ES_PTAG_OBJECT_REGEXP = 0x7ffffffa,
ES_PTAG_OBJECT_DATE = 0x7ffffffb,
ES_PTAG_OBJECT_AGAIN = 0x7ffffffc,
ES_PTAG_PROPERTY = 0x7ffffffd,
ES_PTAG_HOST_OBJECT = 0x7ffffffe,
ES_PTAG_STOP = 0x7fffffff
};
#define GROW(n) do { if (buffer_used + (n) > buffer_size) GrowBufferL(n); } while (0)
#define PUT(x) buffer[buffer_used++] = (x)
#define PUT2(tag, value) do { PUT(tag); PUT(value); } while (0)
#define BUFFER() &(buffer[buffer_used])
#define ADVANCE(x) buffer_used += x
ES_CloneToPersistent::ES_CloneToPersistent(unsigned size_limit)
: size_limit(size_limit),
buffer(NULL),
buffer_used(0),
buffer_size(0)
{
}
/* virtual */
ES_CloneToPersistent::~ES_CloneToPersistent()
{
OP_DELETEA(buffer);
/* Items will be left in the vector only if the clone was aborted.
GetResultL() clears it as it transfers the items to the
ES_PersistentValue object. */
items.DeleteAll();
}
/* virtual */ void
ES_CloneToPersistent::PushNullL()
{
GROW(1);
PUT(ES_PTAG_NULL);
}
/* virtual */ void
ES_CloneToPersistent::PushUndefinedL()
{
GROW(1);
PUT(ES_PTAG_UNDEFINED);
}
/* virtual */ void
ES_CloneToPersistent::PushBooleanL(BOOL value)
{
GROW(2);
PUT2(ES_PTAG_BOOLEAN, value);
}
/* virtual */ void
ES_CloneToPersistent::PushNumberL(double value)
{
GROW(2);
if (op_isnan(value))
PUT2(ES_PTAG_NUMBER, 0);
else
PUT2(op_double_high(value), op_double_low(value));
}
/* virtual */ void
ES_CloneToPersistent::PushStringL(const uni_char *value, unsigned length)
{
GROW(2 + (length + 1) / 2);
PUT(ES_PTAG_STRING);
PUT(length);
for (unsigned index = 0, stop = length & ~1u; index != stop; index += 2)
#ifdef OPERA_BIG_ENDIAN
PUT(value[index + 1] | (static_cast<unsigned>(value[index]) << 16));
#else
PUT(value[index] | (static_cast<unsigned>(value[index + 1]) << 16));
#endif // OPERA_BIG_ENDIAN
if (length & 1u)
#ifdef OPERA_BIG_ENDIAN
PUT(static_cast<unsigned>(value[length - 1]) << 16);
#else
PUT(value[length - 1]);
#endif // OPERA_BIG_ENDIAN
}
/* virtual */ void
ES_CloneToPersistent::PushStringL(unsigned index)
{
GROW(2);
PUT2(ES_PTAG_STRING_AGAIN, index);
}
/* virtual */ void
ES_CloneToPersistent::PushObjectL(unsigned index)
{
GROW(2);
PUT2(ES_PTAG_OBJECT_AGAIN, index);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectL()
{
GROW(1);
PUT(ES_PTAG_OBJECT);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectBooleanL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_BOOLEAN);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectNumberL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_NUMBER);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectStringL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_STRING);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectArrayL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_ARRAY);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectRegExpL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_REGEXP);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectDateL()
{
GROW(1);
PUT(ES_PTAG_OBJECT_DATE);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectArrayBufferL(const unsigned char *value, unsigned length)
{
GROW(2 + (length + 3) / 4);
PUT(ES_PTAG_OBJECT_ARRAYBUFFER);
PUT(length);
op_memcpy(BUFFER(), value, length);
ADVANCE((length + 3) / 4);
}
/* virtual */ void
ES_CloneToPersistent::StartObjectTypedArrayL(unsigned kind, unsigned offset, unsigned size)
{
GROW(4);
PUT(ES_PTAG_OBJECT_TYPEDARRAY);
PUT(kind);
PUT(offset);
PUT(size);
}
/* virtual */ void
ES_CloneToPersistent::AddPropertyL(int attributes)
{
GROW(2);
PUT2(ES_PTAG_PROPERTY, attributes);
}
/* virtual */ BOOL
ES_CloneToPersistent::HostObjectL(EcmaScript_Object *source_object)
{
ES_HostObjectCloneHandler *handler = g_ecmaManager->GetFirstHostObjectCloneHandler();
while (handler)
{
ES_PersistentItem *target_item;
OP_STATUS status = handler->Clone(source_object, target_item);
if (status == OpStatus::OK)
{
PUT2(ES_PTAG_HOST_OBJECT, items.GetCount());
if (OpStatus::IsMemoryError(items.Add(target_item)))
{
OP_DELETE(target_item);
LEAVE(OpStatus::ERR_NO_MEMORY);
}
return TRUE;
}
else if (status != OpStatus::ERR)
LEAVE(status);
handler = g_ecmaManager->GetNextHostObjectCloneHandler(handler);
}
return FALSE;
}
/* virtual */ BOOL
ES_CloneToPersistent::HostObjectL(ES_PersistentItem *source_item)
{
/* ES_HostObjectCloneHandler doesn't support persistent->persistent, and
there's really no reason to. */
return FALSE;
}
#undef GROW
#undef PUT
#undef PUT2
ES_PersistentValue *
ES_CloneToPersistent::GetResultL()
{
ES_PersistentValue *value = OP_NEW_L(ES_PersistentValue, ());
value->data = OP_NEWA(unsigned, buffer_used);
if (!value->data)
{
OP_DELETE(value);
LEAVE(OpStatus::ERR_NO_MEMORY);
}
op_memcpy(value->data, buffer, buffer_used * sizeof *buffer);
value->length = buffer_used;
unsigned items_count = items.GetCount();
if (items_count != 0)
{
value->items = OP_NEWA(ES_PersistentItem *, items_count);
if (!value->items)
{
OP_DELETE(value);
LEAVE(OpStatus::ERR_NO_MEMORY);
}
for (unsigned index = 0; index < items_count; ++index)
value->items[index] = items.Get(index);
value->items_count = items_count;
items.Clear();
}
return value;
}
void
ES_CloneToPersistent::GrowBufferL(unsigned n)
{
if (size_limit != 0 && (buffer_used + n) * sizeof *buffer > size_limit)
LEAVE(OpStatus::ERR);
unsigned new_buffer_size;
if (buffer_size == 0)
new_buffer_size = 64;
else
new_buffer_size = buffer_size * 2;
while (buffer_used + n > new_buffer_size)
new_buffer_size += new_buffer_size;
if (size_limit != 0 && new_buffer_size * sizeof *buffer > size_limit)
new_buffer_size = (size_limit + sizeof *buffer - 1) / sizeof *buffer;
unsigned *new_buffer = OP_NEWA_L(unsigned, new_buffer_size);
if (buffer)
{
op_memcpy(new_buffer, buffer, buffer_used * sizeof *buffer);
OP_DELETEA(buffer);
}
buffer = new_buffer;
buffer_size = new_buffer_size;
}
ES_CloneFromPersistent::ES_CloneFromPersistent(ES_PersistentValue *value)
: value(value)
{
}
/* virtual */ void
ES_CloneFromPersistent::CloneL(ES_CloneBackend *target)
{
const unsigned *ptr = value->data, *stop = ptr + value->length;
while (ptr != stop)
{
unsigned tag = *ptr++;
switch (tag)
{
case ES_PTAG_NULL:
target->PushNullL();
break;
case ES_PTAG_UNDEFINED:
target->PushUndefinedL();
break;
case ES_PTAG_BOOLEAN:
target->PushBooleanL(*ptr++ != 0);
break;
case ES_PTAG_STRING:
{
unsigned length = *ptr++;
target->PushStringL(reinterpret_cast<const uni_char *>(ptr), length);
ptr += (length + 1) / 2;
}
break;
case ES_PTAG_STRING_AGAIN:
target->PushStringL(*ptr++);
break;
case ES_PTAG_OBJECT:
target->StartObjectL();
break;
case ES_PTAG_OBJECT_BOOLEAN:
target->StartObjectBooleanL();
break;
case ES_PTAG_OBJECT_NUMBER:
target->StartObjectNumberL();
break;
case ES_PTAG_OBJECT_STRING:
target->StartObjectStringL();
break;
case ES_PTAG_OBJECT_ARRAY:
target->StartObjectArrayL();
break;
case ES_PTAG_OBJECT_REGEXP:
target->StartObjectRegExpL();
break;
case ES_PTAG_OBJECT_DATE:
target->StartObjectDateL();
break;
case ES_PTAG_OBJECT_AGAIN:
target->PushObjectL(*ptr++);
break;
case ES_PTAG_PROPERTY:
target->AddPropertyL(*ptr++);
break;
case ES_PTAG_HOST_OBJECT:
target->HostObjectL(value->items[*ptr++]);
break;
case ES_PTAG_OBJECT_ARRAYBUFFER:
{
unsigned length = *ptr++;
target->StartObjectArrayBufferL(reinterpret_cast<const unsigned char *>(ptr), length);
ptr += (length + 3) / 4;
}
break;
case ES_PTAG_OBJECT_TYPEDARRAY:
{
unsigned kind = *ptr++;
unsigned offset = *ptr++;
unsigned size = *ptr++;
target->StartObjectTypedArrayL(kind, offset, size);
}
break;
default:
target->PushNumberL(op_implode_double(tag, *ptr++));
break;
}
}
}
#endif // ES_PERSISTENT_SUPPORT
|
//===========================================================================
//! @file model_mqo.cpp
//! @brief MQOモデル
//===========================================================================
//---------------------------------------------------------------------------
//! MQOソート用
//---------------------------------------------------------------------------
int sortFunc(const void* a, const void* b)
{
int m1 = ((ModelMQO::Face*)a)->material_;
int m2 = ((ModelMQO::Face*)b)->material_;
if(m1 < m2)
return -1;
if(m1 > m2)
return +1;
return 0;
}
//---------------------------------------------------------------------------
//! コンストラクタ
//---------------------------------------------------------------------------
ModelMQO::ModelMQO()
{
}
//---------------------------------------------------------------------------
//! デストラクタ
//---------------------------------------------------------------------------
ModelMQO::~ModelMQO()
{
for(auto& o : objects_) {
delete o;
o = nullptr;
}
for(auto& m : materials_) {
delete m.texture_;
}
}
//---------------------------------------------------------------------------
//! 読み込み
//---------------------------------------------------------------------------
bool ModelMQO::load(char* fileName, f32 scale)
{
//=============================================================
// ファイルを開く
//=============================================================
FILE* fp;
if(fopen_s(&fp, fileName, "rt") != 0) {
return false;
}
//=============================================================
// 一行ずつファイル終端まで解析していく
//=============================================================
enum class State
{
Root,
Object,
Vertex,
Face,
Material,
};
State state = State::Root; // 状態の初期値
Object* object = nullptr;
char str[1024];
while(fgets(str, sizeof(str), fp)) {
switch(state) {
case State::Root: //---- ルート解析中
if(strncmp(str, "Object ", 7) == 0) {
object = new Object();
// オブジェクト名を取り出す Object "name"
char* p = strchr(str, '\"');
p += 1; // 区切り記号をスキップ
char* name = p; // 名前先頭
p = strchr(p, '\"');
*p = 0; // 文字終端
object->name_ = name;
state = State::Object;
break;
}
if(strncmp(str, "Material", 8) == 0) {
state = State::Material;
break;
}
break;
case State::Object: //---- オブジェクト解析中
if(strncmp(str, "}", 1) == 0) {
// 最適化
object->optimize();
// オブジェクトリストにつなぐ
objects_.push_back(object);
object = nullptr;
state = State::Root;
break;
}
if(strstr(str, "color ") != nullptr) {
Vector4 color;
sscanf_s(str, " color %f %f %f", &color.r_, &color.g_, &color.b_);
color.a_ = 1.0f;
object->color_ = color;
break;
}
if(strstr(str, "vertex ") != nullptr) {
state = State::Vertex;
break;
}
if(strstr(str, "facet ") != nullptr) {
f32 facet;
sscanf_s(str, " facet %f", &facet);
object->facet_ = facet;
break;
}
if(strstr(str, "face ") != nullptr) {
state = State::Face;
break;
}
break;
case State::Vertex: //---- 頂点解析中
if(strstr(str, "}") != nullptr) {
state = State::Object;
break;
}
f32 x;
f32 y;
f32 z;
sscanf_s(str, " %f %f %f", &x, &y, &z);
x *= scale;
y *= scale;
z *= scale;
object->vertices_.push_back(Vector3(x, y, z));
break;
case State::Face: //---- フェイス解析中
{
if(strstr(str, "}") != nullptr) {
state = State::Object;
break;
}
// 三角形か四角形かをチェック
s32 vertexCount; // 3 or 4
sscanf_s(str, " %d", &vertexCount);
if(vertexCount <= 2) { // 不正な値の場合はスキップ
break;
}
Face f;
// マテリアル番号を取得
f.material_ = -1;
{
char* p = strstr(str, "M(");
if(p != nullptr) {
sscanf_s(p, "M(%d)", &f.material_);
}
}
if(vertexCount == 3) {
// 三角形の場合
char* p = strstr(str, "V(");
s32 index[3];
sscanf_s(p, "V(%d %d %d)", &index[0], &index[1], &index[2]);
f32 u[3]{};
f32 v[3]{};
p = strstr(str, "UV(");
if(p) {
sscanf_s(p, "UV(%f %f %f %f %f %f)", &u[0], &v[0], &u[1], &v[1], &u[2], &v[2]);
}
f.vertexIndex_[0] = index[0];
f.vertexIndex_[1] = index[1];
f.vertexIndex_[2] = index[2];
const auto& v1 = object->vertices_[index[0]];
const auto& v2 = object->vertices_[index[1]];
const auto& v3 = object->vertices_[index[2]];
Vector3 faceNormal = Vector3::cross(v3 - v1, v2 - v1).normalize();
f.normal_[0] = faceNormal;
f.normal_[1] = faceNormal;
f.normal_[2] = faceNormal;
f.u_[0] = u[0];
f.u_[1] = u[1];
f.u_[2] = u[2];
f.v_[0] = v[0];
f.v_[1] = v[1];
f.v_[2] = v[2];
// 三角形の登録
object->faces_.push_back(f);
}
else {
// 四角形の場合
char* p = strstr(str, "V(");
s32 index[4];
sscanf_s(p, "V(%d %d %d %d)", &index[0], &index[1], &index[2], &index[3]);
f32 u[4]{};
f32 v[4]{};
p = strstr(str, "UV(");
if(p) {
sscanf_s(p, "UV(%f %f %f %f %f %f %f %f)", &u[0], &v[0], &u[1], &v[1], &u[2], &v[2], &u[3], &v[3]);
}
f.vertexIndex_[0] = index[0];
f.vertexIndex_[1] = index[1];
f.vertexIndex_[2] = index[2];
const auto& v1 = object->vertices_[index[0]];
const auto& v2 = object->vertices_[index[1]];
const auto& v3 = object->vertices_[index[2]];
Vector3 faceNormal = Vector3::cross(v3 - v1, v2 - v1).normalize();
f.normal_[0] = faceNormal;
f.normal_[1] = faceNormal;
f.normal_[2] = faceNormal;
f.normal_[3] = faceNormal;
f.u_[0] = u[0];
f.u_[1] = u[1];
f.u_[2] = u[2];
f.v_[0] = v[0];
f.v_[1] = v[1];
f.v_[2] = v[2];
object->faces_.push_back(f);
f.vertexIndex_[0] = index[2];
f.vertexIndex_[1] = index[3];
f.vertexIndex_[2] = index[0];
f.u_[0] = u[2];
f.u_[1] = u[3];
f.u_[2] = u[0];
f.v_[0] = v[2];
f.v_[1] = v[3];
f.v_[2] = v[0];
object->faces_.push_back(f);
}
break;
}
case State::Material: {
if(str[0] == '}') {
state = State::Root;
break;
}
// col()構文を検出
Vector4 color(1, 1, 1, 1);
{
char* p = strstr(str, "col(");
if(p) {
sscanf_s(p, "col(%f %f %f %f)", &color.r_, &color.g_, &color.b_, &color.a_);
}
}
gpu::Texture* texture = nullptr;
// tex("")構文を検出
char* p = strstr(str, "tex(");
if(p != nullptr) {
// tex(" の5文字分進める
p += 5;
// テクスチャ名を抽出
char* textureName = p; // 先頭を保存
while(*p != '\"') {
p++;
}
*p = 0;
// テクスチャを読み込み
// MQOファイルのパス指定箇所のパス名のみ抽出
char drive[MAX_PATH];
char path[MAX_PATH];
char file[MAX_PATH];
char ext[MAX_PATH];
_splitpath_s(fileName, drive, path, file, ext);
char textureFullPath[MAX_PATH];
strcpy_s(textureFullPath, drive);
strcat_s(textureFullPath, path);
strcat_s(textureFullPath, textureName);
texture = gpu::createTexture(textureFullPath);
if(!texture) {
MessageBox(nullptr, textureFullPath, "テクスチャ読み込みに失敗しました.", MB_OK);
delete texture;
texture = nullptr;
}
}
// マテリアルを登録
Material m;
m.texture_ = texture;
m.color_ = color;
materials_.push_back(m);
break;
}
}
// MessageBox(nullptr, str, "読み込み", MB_OK);
}
//-------------------------------------------------------------------------------
// ファイルを閉じる
//-------------------------------------------------------------------------------
fclose(fp);
return true;
}
//---------------------------------------------------------------------------
//! 描画
//---------------------------------------------------------------------------
void ModelMQO::render()
{
//----------------------------------------------------------------------------------
// 点群の描画
//----------------------------------------------------------------------------------
#if 0
glPointSize(3.0f);
glColor3ub(255, 255, 255);
glBegin(GL_POINTS);
// 全てのオブジェクト部品
for (auto& o : _objects) {
// オブジェクト内のすべての頂点
for (auto& v : o->_vertices) {
glVertex3fv((GLfloat*)& v);
}
}
glEnd();
glPointSize(1.0f);
#endif
//=============================================================
// ワイヤーフレームの描画
//=============================================================
#if 0
glColor3ub(255, 255, 255);
glBegin(GL_LINES);
// 全てのオブジェクト部品
for (auto& o : _objects) {
auto& v = o->_vertices; // 頂点配列
// 全てのフェイス
for (auto& face : o->_faces) {
glVertex3fv((GLfloat*)& v[face._vertexIndex[0]]);
glVertex3fv((GLfloat*)& v[face._vertexIndex[1]]);
glVertex3fv((GLfloat*)& v[face._vertexIndex[1]]);
glVertex3fv((GLfloat*)& v[face._vertexIndex[2]]);
glVertex3fv((GLfloat*)& v[face._vertexIndex[2]]);
glVertex3fv((GLfloat*)& v[face._vertexIndex[0]]);
}
}
glEnd();
glColor3ub(128, 128, 128);
#endif
//=============================================================
// 三角形の描画
//=============================================================
s32 material = -1; // 現在のマテリアル番号
dxTexture(Asset::getSystemTexture(SYSTEM_TEXTURE_NULL_WHITE).get());
gpu::setShader("vsNormal.fx", "psNormal.fx"); // シェーダー
u32 triangleCount = 0;
// ポリゴンオフセット機能でデプスをずらす
// glEnable(GL_POLYGON_OFFSET_FILL);
// glPolygonOffset(1.0f, 1.0f);
// アルファテスト有効化
// glEnable(GL_ALPHA_TEST);
// glAlphaFunc(GL_GREATER, 0.5f); // 比較条件 A > 0.5のときに描画する
dxBegin(PT_TRIANGLES);
// 全てのオブジェクト部品
for(auto& o : objects_) {
auto& v = o->vertices_; // 頂点配列
// オブジェクトカラー
dxColor4f(o->color_.r_, o->color_.g_, o->color_.b_, o->color_.a_);
// 全てのフェイス
for(auto& face : o->faces_) {
// マテリアルの変更
if(material != face.material_ ||
triangleCount > 65536
) {
dxEnd(); //--- いったん描画コマンドを閉じる
// テクスチャの設定
gpu::Texture* texture = nullptr;
if(face.material_ != -1) {
// テクスチャあり
texture = materials_[face.material_].texture_;
// マテリアルカラー
dxColor4f(materials_[face.material_].color_.r_,
materials_[face.material_].color_.g_,
materials_[face.material_].color_.b_,
materials_[face.material_].color_.a_);
}
else {
// オブジェクトカラー
dxColor4f(o->color_.r_, o->color_.g_, o->color_.b_, o->color_.a_);
}
dxTexture(texture ? texture : Asset::getSystemTexture(SYSTEM_TEXTURE_NULL_WHITE).get());
//gpu::setShader("vsNormal.fx", "psNormal.fx"); // シェーダー // シェーダー
dxBegin(PT_TRIANGLES); //--- 再度開きなおす
// 現在の番号を更新
material = face.material_;
triangleCount = 0;
}
const auto& v1 = v[face.vertexIndex_[0]];
const auto& v2 = v[face.vertexIndex_[1]];
const auto& v3 = v[face.vertexIndex_[2]];
dxTexCoord2f(face.u_[0], face.v_[0]);
dxNormal3fv(face.normal_[0]);
dxVertex3fv(v1);
dxTexCoord2f(face.u_[1], face.v_[1]);
dxNormal3fv(face.normal_[1]);
dxVertex3fv(v2);
dxTexCoord2f(face.u_[2], face.v_[2]);
dxNormal3fv(face.normal_[2]);
dxVertex3fv(v3);
triangleCount++;
}
}
dxEnd();
// アルファテスト無効化
// glDisable(GL_ALPHA_TEST);
// ポリゴンオフセット無効化
// glDisable(GL_POLYGON_OFFSET_FILL);
// テクスチャをもとに戻す
dxTexture(nullptr);
}
//---------------------------------------------------------------------------
//! 最適化
//---------------------------------------------------------------------------
void ModelMQO::Object::optimize()
{
// マテリアル単位でソート
std::qsort(faces_.data(), faces_.size(), sizeof(ModelMQO::Face), &sortFunc);
//=============================================================
// 法線平滑化
//=============================================================
struct Point
{
Vector3 vertex_ = Vector3(0, 0, 0);
Vector3 normal_ = Vector3(0, 0, 0);
u32 count_ = 0;
};
std::vector<Point> points;
std::vector<u32> pointIndices;
for(auto& f : faces_) {
for(u32 i = 0; i < 3; ++i) {
bool found = false;
for(u32 index = 0; index < points.size(); ++index) {
auto& p = points[index];
if((p.vertex_ - vertices_[f.vertexIndex_[i]]).lengthSq() > 0.01f) {
continue;
}
// 法線の一致度チェック
if(Vector3::dot(p.normal_.normalize(), f.normal_[i]) < cosf(facet_ * (3.1415f / 180.0f))) {
continue;
}
// すでに共有頂点があったらマージ
p.normal_ += f.normal_[i];
p.count_++;
pointIndices.emplace_back(index); // インデックス番号
found = true;
break;
}
// 新規登録
if(!found) {
pointIndices.emplace_back(points.size()); // インデックス番号
Point p;
p.vertex_ = vertices_[f.vertexIndex_[i]];
p.normal_ = f.normal_[i];
p.count_ = 1;
points.emplace_back(std::move(p));
}
}
}
// 平均化
for(auto& p : points) {
p.normal_ /= f32(p.count_);
}
// 共有法線を書き戻し
{
u32 index = 0;
for(auto& f : faces_) {
//bool found = false;
f.normal_[0] = points[pointIndices[index++]].normal_;
f.normal_[1] = points[pointIndices[index++]].normal_;
f.normal_[2] = points[pointIndices[index++]].normal_;
}
}
}
//---------------------------------------------------------------------------
//! Objectの個数を取得
//---------------------------------------------------------------------------
size_t ModelMQO::getObjectCount() const
{
return objects_.size();
}
|
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdlib>
#include <vector>
using namespace std;
int N = 1000000;
int N_bins = 1024;
int rng()
{
int a = 1103515245;
int c = 12345;
int m = (int)1024;
static int x = 0;
x = (a*x+c) % m;
return x;
}
vector<unsigned int> histogram(vector<double> dane, unsigned int N, int x_min = 0, int x_max = 1)
{
vector<unsigned int> v(N,0);
double dx = (double)(x_max-x_min)/(double)N;
unsigned int N_dane = dane.size();
for (unsigned int i=0; i<N_dane; i++)
{
int dana_bin = (int)(dane.at(i)/dx);
v.at(dana_bin)++;
}
return v;
}
int main()
{
vector<double> dane;
for (int i=0; i<N; i++)
{
dane.push_back(random()/(double)RAND_MAX);
}
vector<unsigned int> hist = histogram(dane, N_bins);
for (auto val: hist)
{
cout << val << endl;
}
}
|
#include "Player.h"
const int WARRIOR_HP = 200;
const int WARRIOR_MP = 0;
class Warrior : public Player
{
private:
std::string characterClass{ "warrior" };
public:
Warrior(std::string name, Race race) : Player(name, race, WARRIOR, WARRIOR_HP,
WARRIOR_MP)
{
}
std::string attack()
{
return "I will destroy you with my sword, foul demon!";
}
};
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <condition_variable>
#include <mutex>
#include <fizz/crypto/test/TestUtil.h>
#include <fizz/protocol/clock/test/Mocks.h>
#include <fizz/protocol/test/Mocks.h>
#include <fizz/server/Actions.h>
#include <fizz/server/test/Mocks.h>
#include <folly/io/async/SSLContext.h>
#include <folly/io/async/ScopedEventBaseThread.h>
#include <folly/io/async/test/MockAsyncTransport.h>
#include <folly/ssl/Init.h>
#include <quic/client/handshake/ClientTransportParametersExtension.h>
#include <quic/client/state/ClientStateMachine.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/client/handshake/FizzClientHandshake.h>
#include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h>
#include <quic/fizz/client/handshake/test/MockQuicPskCache.h>
#include <quic/fizz/handshake/FizzBridge.h>
#include <quic/fizz/handshake/QuicFizzFactory.h>
#include <quic/state/QuicStreamFunctions.h>
#include <quic/state/StateData.h>
using namespace testing;
namespace quic {
namespace test {
class ClientHandshakeTest : public Test, public boost::static_visitor<> {
public:
~ClientHandshakeTest() override = default;
ClientHandshakeTest() {}
virtual void setupClientAndServerContext() {
clientCtx = std::make_shared<fizz::client::FizzClientContext>();
clientCtx->setClock(std::make_shared<fizz::test::MockClock>());
}
QuicVersion getVersion() {
return QuicVersion::MVFST;
}
virtual void connect() {
handshake->connect(
hostname,
std::make_shared<ClientTransportParametersExtension>(
QuicVersion::MVFST,
folly::to<uint32_t>(kDefaultConnectionFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultMaxStreamsBidirectional),
folly::to<uint32_t>(kDefaultMaxStreamsUnidirectional),
kDefaultIdleTimeout,
kDefaultAckDelayExponent,
kDefaultUDPSendPacketLen,
kDefaultActiveConnectionIdLimit,
ConnectionId(std::vector<uint8_t>())));
}
void SetUp() override {
folly::ssl::init();
dg.reset(new DelayedHolder());
serverCtx = ::quic::test::createServerCtx();
serverCtx->setOmitEarlyRecordLayer(true);
serverCtx->setClock(std::make_shared<fizz::test::MockClock>());
// Fizz is the name of the identity for our server certificate.
hostname = "Fizz";
setupClientAndServerContext();
verifier = std::make_shared<fizz::test::MockCertificateVerifier>();
auto handshakeFactory = FizzClientQuicHandshakeContext::Builder()
.setFizzClientContext(clientCtx)
.setCertificateVerifier(verifier)
.setPskCache(getPskCache())
.build();
conn.reset(new QuicClientConnectionState(handshakeFactory));
conn->readCodec = std::make_unique<QuicReadCodec>(QuicNodeType::Client);
cryptoState = conn->cryptoState.get();
handshake = conn->clientHandshakeLayer;
conn->transportSettings.attemptEarlyData = true;
std::vector<QuicVersion> supportedVersions = {getVersion()};
auto serverTransportParameters =
std::make_shared<ServerTransportParametersExtension>(
getVersion(),
folly::to<uint32_t>(kDefaultConnectionFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max(),
/*disableMigration=*/true,
kDefaultIdleTimeout,
kDefaultAckDelayExponent,
kDefaultUDPSendPacketLen,
generateStatelessResetToken(),
ConnectionId(std::vector<uint8_t>{0xff, 0xfe, 0xfd, 0xfc}),
ConnectionId(std::vector<uint8_t>()));
fizzServer.reset(
new fizz::server::
FizzServer<ClientHandshakeTest, fizz::server::ServerStateMachine>(
serverState, serverReadBuf, readAeadOptions, *this, dg.get()));
connect();
processHandshake();
fizzServer->accept(&evb, serverCtx, serverTransportParameters);
}
virtual std::shared_ptr<QuicPskCache> getPskCache() {
return nullptr;
}
void clientServerRound() {
auto writableBytes = getHandshakeWriteBytes();
serverReadBuf.append(std::move(writableBytes));
fizzServer->newTransportData();
evb.loop();
}
void serverClientRound() {
// Fake that the transport has set the version and initial params.
conn->version = QuicVersion::MVFST;
conn->serverInitialParamsSet_ = true;
evb.loop();
for (auto& write : serverOutput) {
for (auto& content : write.contents) {
auto encryptionLevel =
getEncryptionLevelFromFizz(content.encryptionLevel);
handshake->doHandshake(std::move(content.data), encryptionLevel);
}
}
processHandshake();
}
void processHandshake() {
auto oneRttWriteCipherTmp = std::move(conn->oneRttWriteCipher);
auto oneRttReadCipherTmp = conn->readCodec->getOneRttReadCipher();
auto zeroRttWriteCipherTmp = std::move(conn->zeroRttWriteCipher);
auto handshakeWriteCipherTmp = std::move(conn->handshakeWriteCipher);
auto handshakeReadCipherTmp = conn->readCodec->getHandshakeReadCipher();
if (oneRttWriteCipherTmp) {
oneRttWriteCipher = std::move(oneRttWriteCipherTmp);
}
if (oneRttReadCipherTmp) {
oneRttReadCipher = oneRttReadCipherTmp;
}
if (zeroRttWriteCipherTmp) {
zeroRttWriteCipher = std::move(zeroRttWriteCipherTmp);
}
if (handshakeWriteCipherTmp) {
handshakeWriteCipher = std::move(handshakeWriteCipherTmp);
}
if (handshakeReadCipherTmp) {
handshakeReadCipher = handshakeReadCipherTmp;
}
auto rejected = handshake->getZeroRttRejected();
if (rejected) {
zeroRttRejected = std::move(rejected);
}
}
void expectHandshakeCipher(bool expected) {
EXPECT_EQ(handshakeReadCipher != nullptr, expected);
EXPECT_EQ(handshakeWriteCipher != nullptr, expected);
}
void expectOneRttCipher(bool expected, bool oneRttOnly = false) {
if (expected) {
EXPECT_NE(oneRttReadCipher, nullptr);
EXPECT_NE(oneRttWriteCipher.get(), nullptr);
} else {
EXPECT_EQ(oneRttReadCipher, nullptr);
EXPECT_EQ(oneRttWriteCipher.get(), nullptr);
}
if (!oneRttOnly) {
EXPECT_EQ(zeroRttWriteCipher.get(), nullptr);
}
}
void expectZeroRttCipher(bool expected, bool expectOneRtt) {
if (expected) {
EXPECT_NE(zeroRttWriteCipher.get(), nullptr);
} else {
EXPECT_EQ(zeroRttWriteCipher.get(), nullptr);
}
expectOneRttCipher(expectOneRtt, true);
}
Buf getHandshakeWriteBytes() {
auto buf = folly::IOBuf::create(0);
if (!cryptoState->initialStream.writeBuffer.empty()) {
buf->prependChain(cryptoState->initialStream.writeBuffer.move());
}
if (!cryptoState->handshakeStream.writeBuffer.empty()) {
buf->prependChain(cryptoState->handshakeStream.writeBuffer.move());
}
if (!cryptoState->oneRttStream.writeBuffer.empty()) {
buf->prependChain(cryptoState->oneRttStream.writeBuffer.move());
}
return buf;
}
void operator()(fizz::DeliverAppData&) {
// do nothing here.
}
void operator()(fizz::WriteToSocket& write) {
serverOutput.push_back(std::move(write));
}
void operator()(fizz::server::ReportEarlyHandshakeSuccess&) {
earlyHandshakeSuccess = true;
}
void operator()(fizz::server::ReportHandshakeSuccess&) {
handshakeSuccess = true;
}
void operator()(fizz::ReportError& error) {
handshakeError = std::move(error);
}
void operator()(fizz::WaitForData&) {
fizzServer->waitForData();
}
void operator()(fizz::server::MutateState& mutator) {
mutator(serverState);
}
void operator()(fizz::server::AttemptVersionFallback&) {}
void operator()(fizz::SecretAvailable&) {}
void operator()(fizz::EndOfData&) {}
class DelayedHolder : public folly::DelayedDestruction {};
folly::EventBase evb;
std::unique_ptr<
QuicClientConnectionState,
folly::DelayedDestruction::Destructor>
conn{nullptr};
ClientHandshake* handshake;
QuicCryptoState* cryptoState;
std::string hostname;
fizz::server::ServerStateMachine machine;
fizz::server::State serverState;
std::unique_ptr<fizz::server::FizzServer<
ClientHandshakeTest,
fizz::server::ServerStateMachine>>
fizzServer;
std::vector<fizz::WriteToSocket> serverOutput;
bool handshakeSuccess{false};
bool earlyHandshakeSuccess{false};
folly::Optional<fizz::ReportError> handshakeError;
folly::IOBufQueue serverReadBuf{folly::IOBufQueue::cacheChainLength()};
std::unique_ptr<DelayedHolder, folly::DelayedDestruction::Destructor> dg;
fizz::Aead::AeadOptions readAeadOptions;
std::unique_ptr<Aead> handshakeWriteCipher;
const Aead* handshakeReadCipher = nullptr;
std::unique_ptr<Aead> oneRttWriteCipher;
const Aead* oneRttReadCipher = nullptr;
std::unique_ptr<Aead> zeroRttWriteCipher;
folly::Optional<bool> zeroRttRejected;
std::shared_ptr<fizz::test::MockCertificateVerifier> verifier;
std::shared_ptr<fizz::client::FizzClientContext> clientCtx;
std::shared_ptr<fizz::server::FizzServerContext> serverCtx;
};
TEST_F(ClientHandshakeTest, TestHandshakeSuccess) {
EXPECT_CALL(*verifier, verify(_));
clientServerRound();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Initial);
expectHandshakeCipher(false);
serverClientRound();
expectHandshakeCipher(true);
EXPECT_FALSE(zeroRttRejected.has_value());
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
clientServerRound();
expectOneRttCipher(true);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
handshake->handshakeConfirmed();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Established);
EXPECT_FALSE(zeroRttRejected.has_value());
EXPECT_TRUE(handshakeSuccess);
}
TEST_F(ClientHandshakeTest, TestRetryIntegrityVerification) {
// Example obtained from Appendix-A.4 of the QUIC-TLS draft v29.
auto version = static_cast<QuicVersion>(0xff00001d);
uint8_t initialByte = 0xff;
std::vector<uint8_t> dcidVec = {};
ConnectionId dcid(dcidVec);
std::vector<uint8_t> scidVec = {
0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5};
ConnectionId scid(scidVec);
std::string retryToken = R"(token)";
LongHeader header(
LongHeader::Types::Retry, scid, dcid, 0, version, retryToken);
std::string integrityTag =
"\xd1\x69\x26\xd8\x1f\x6f\x9c\xa2\x95\x3a\x8a\xa4\x57\x5e\x1e\x49";
RetryPacket retryPacket(
std::move(header), folly::IOBuf::copyBuffer(integrityTag), initialByte);
std::vector<uint8_t> odcidVec = {
0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08};
ConnectionId odcid(odcidVec);
EXPECT_TRUE(handshake->verifyRetryIntegrityTag(odcid, retryPacket));
}
TEST_F(ClientHandshakeTest, TestNoErrorAfterAppClose) {
EXPECT_CALL(*verifier, verify(_));
clientServerRound();
serverClientRound();
clientServerRound();
fizzServer->appClose();
evb.loop();
// RTT 1/2 server -> client
EXPECT_NO_THROW(serverClientRound());
expectOneRttCipher(true);
EXPECT_FALSE(zeroRttRejected.has_value());
EXPECT_TRUE(handshakeSuccess);
}
TEST_F(ClientHandshakeTest, TestAppBytesInterpretedAsHandshake) {
EXPECT_CALL(*verifier, verify(_));
clientServerRound();
serverClientRound();
clientServerRound();
fizz::AppWrite w;
w.data = folly::IOBuf::copyBuffer("hey");
fizzServer->appWrite(std::move(w));
evb.loop();
// RTT 1/2 server -> client
serverClientRound();
expectOneRttCipher(true);
EXPECT_FALSE(zeroRttRejected.has_value());
EXPECT_TRUE(handshakeSuccess);
}
class ClientHandshakeCallbackTest : public ClientHandshakeTest {
public:
void setupClientAndServerContext() override {
clientCtx = std::make_shared<fizz::client::FizzClientContext>();
clientCtx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3});
serverCtx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3});
clientCtx->setClock(std::make_shared<fizz::test::MockClock>());
setupZeroRttOnServerCtx(*serverCtx, psk_);
}
void connect() override {
handshake->connect(
hostname,
std::make_shared<ClientTransportParametersExtension>(
QuicVersion::MVFST,
folly::to<uint32_t>(kDefaultConnectionFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultMaxStreamsBidirectional),
folly::to<uint32_t>(kDefaultMaxStreamsUnidirectional),
kDefaultIdleTimeout,
kDefaultAckDelayExponent,
kDefaultUDPSendPacketLen,
kDefaultActiveConnectionIdLimit,
ConnectionId(std::vector<uint8_t>())));
}
protected:
QuicCachedPsk psk_;
};
TEST_F(ClientHandshakeCallbackTest, TestHandshakeSuccess) {
clientServerRound();
serverClientRound();
clientServerRound();
bool gotEarlyDataParams = false;
conn->earlyDataAppParamsGetter = [&]() -> Buf {
gotEarlyDataParams = true;
return {};
};
serverClientRound();
EXPECT_TRUE(gotEarlyDataParams);
}
class ClientHandshakeHRRTest : public ClientHandshakeTest {
public:
~ClientHandshakeHRRTest() override = default;
void setupClientAndServerContext() override {
clientCtx = std::make_shared<fizz::client::FizzClientContext>();
clientCtx->setSupportedGroups(
{fizz::NamedGroup::secp256r1, fizz::NamedGroup::x25519});
clientCtx->setDefaultShares({fizz::NamedGroup::secp256r1});
clientCtx->setClock(std::make_shared<fizz::test::MockClock>());
serverCtx = std::make_shared<fizz::server::FizzServerContext>();
serverCtx->setFactory(std::make_shared<QuicFizzFactory>());
serverCtx->setSupportedGroups({fizz::NamedGroup::x25519});
serverCtx->setClock(std::make_shared<fizz::test::MockClock>());
setupCtxWithTestCert(*serverCtx);
}
};
TEST_F(ClientHandshakeHRRTest, TestFullHRR) {
EXPECT_CALL(*verifier, verify(_));
clientServerRound();
expectHandshakeCipher(false);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Initial);
serverClientRound();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Handshake);
clientServerRound();
expectOneRttCipher(false);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Handshake);
serverClientRound();
expectHandshakeCipher(true);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
clientServerRound();
expectOneRttCipher(true);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
EXPECT_FALSE(zeroRttRejected.has_value());
EXPECT_TRUE(handshakeSuccess);
}
TEST_F(ClientHandshakeHRRTest, TestHRROnlyOneRound) {
EXPECT_CALL(*verifier, verify(_)).Times(0);
clientServerRound();
serverClientRound();
clientServerRound();
expectOneRttCipher(false);
EXPECT_FALSE(handshakeSuccess);
}
class ClientHandshakeZeroRttTest : public ClientHandshakeTest {
public:
~ClientHandshakeZeroRttTest() override = default;
void setupClientAndServerContext() override {
clientCtx = std::make_shared<fizz::client::FizzClientContext>();
clientCtx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3});
clientCtx->setSupportedAlpns({"h3", "hq"});
clientCtx->setClock(std::make_shared<fizz::test::MockClock>());
serverCtx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3});
serverCtx->setSupportedAlpns({"h3"});
serverCtx->setClock(std::make_shared<fizz::test::MockClock>());
setupCtxWithTestCert(*serverCtx);
psk = setupZeroRttOnClientCtx(*clientCtx, hostname);
setupZeroRttServer();
}
std::shared_ptr<QuicPskCache> getPskCache() override {
auto pskCache = std::make_shared<BasicQuicPskCache>();
pskCache->putPsk(hostname, psk);
return pskCache;
}
void connect() override {
handshake->connect(
hostname,
std::make_shared<ClientTransportParametersExtension>(
QuicVersion::MVFST,
folly::to<uint32_t>(kDefaultConnectionFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultStreamFlowControlWindow),
folly::to<uint32_t>(kDefaultMaxStreamsBidirectional),
folly::to<uint32_t>(kDefaultMaxStreamsUnidirectional),
kDefaultIdleTimeout,
kDefaultAckDelayExponent,
kDefaultUDPSendPacketLen,
kDefaultActiveConnectionIdLimit,
ConnectionId(std::vector<uint8_t>())));
}
virtual void setupZeroRttServer() {
setupZeroRttOnServerCtx(*serverCtx, psk);
}
QuicCachedPsk psk;
};
TEST_F(ClientHandshakeZeroRttTest, TestZeroRttSuccess) {
clientServerRound();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Initial);
expectZeroRttCipher(true, false);
expectHandshakeCipher(false);
serverClientRound();
expectHandshakeCipher(true);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
EXPECT_TRUE(zeroRttRejected.has_value());
EXPECT_FALSE(*zeroRttRejected);
expectZeroRttCipher(true, true);
clientServerRound();
handshake->handshakeConfirmed();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Established);
EXPECT_EQ(handshake->getApplicationProtocol(), "h3");
}
class ClientHandshakeZeroRttReject : public ClientHandshakeZeroRttTest {
public:
~ClientHandshakeZeroRttReject() override = default;
void setupZeroRttServer() override {}
};
TEST_F(ClientHandshakeZeroRttReject, TestZeroRttRejection) {
clientServerRound();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Initial);
expectZeroRttCipher(true, false);
expectHandshakeCipher(false);
serverClientRound();
expectHandshakeCipher(true);
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::OneRttKeysDerived);
EXPECT_TRUE(zeroRttRejected.value_or(false));
// We will still keep the zero rtt key lying around.
expectZeroRttCipher(true, true);
clientServerRound();
handshake->handshakeConfirmed();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Established);
}
class ClientHandshakeZeroRttRejectFail : public ClientHandshakeZeroRttTest {
public:
~ClientHandshakeZeroRttRejectFail() override = default;
void setupClientAndServerContext() override {
// set it up so that the identity will not match.
hostname = "foobar";
ClientHandshakeZeroRttTest::setupClientAndServerContext();
}
void setupZeroRttServer() override {}
};
TEST_F(ClientHandshakeZeroRttRejectFail, TestZeroRttRejectionParamsDontMatch) {
clientServerRound();
EXPECT_EQ(handshake->getPhase(), ClientHandshake::Phase::Initial);
expectHandshakeCipher(false);
expectZeroRttCipher(true, false);
EXPECT_THROW(serverClientRound(), QuicInternalException);
}
} // namespace test
} // namespace quic
|
// Copyright 2015 Intelligent Robotics Group, NASA ARC
#include <robust_filter/robust_filter.h>
namespace robust_filter_node {
RobustFilter::RobustFilter(ros::NodeHandle* nh, ros::NodeHandle* private_nh) {
srand (time(NULL));
std::cout<<std::fixed;
std::cout.precision(8);
int width, height;
double tmp_fx, tmp_fy, tmp_threshold_A_, tmp_RANSAC_threshold_;
std::string feature_topic, inlier_topic, imu_topic;
// Camera intrinsic parameters
private_nh->param("cam_width", width, 1000);
private_nh->param("cam_height", height, 1000);
private_nh->param("cam_fx", tmp_fx, 595.88);
private_nh->param("cam_fy", tmp_fy, 595.88);
// Estimation parameters
private_nh->param("max_frame_cnt", max_frame_cnt_, 10);
private_nh->param("threshold_A", tmp_threshold_A_, 0.0005);
private_nh->param("RANSAC_iteration", RANSAC_iteration_, 50);
private_nh->param("RANSAC_threshold", tmp_RANSAC_threshold_, 0.001);
// Topic names
private_nh->param<std::string>("feature_topic", feature_topic, "/lk_node/features");
private_nh->param<std::string>("inlier_topic", inlier_topic, "/inliers");
private_nh->param<std::string>("imu_topic", imu_topic, "/raw_imu");
// Display inliers
private_nh->param("show_true_inliers", show_true_inliers_, false);
float fx = static_cast<float>(tmp_fx);
float fy = static_cast<float>(tmp_fy);
float cx = static_cast<float>(width / 2);
float cy = static_cast<float>(height / 2);
threshold_A_ = static_cast<float>(tmp_threshold_A_);
RANSAC_threshold_ = static_cast<float>(tmp_RANSAC_threshold_);
// Intrinsic matrix
K_ << fx, 0, cx,
0, fy, cy,
0, 0, 1;
K_inv_ = K_.inverse();
frame_cnt_ = 0;
features1_.feature_array.clear();
features2_.feature_array.clear();
prev_x_rot_vel_ = 0;
prev_y_rot_vel_ = 0;
prev_z_rot_vel_ = 0;
prev_time_ = ros::Time::now();
inlier_pub_ = nh->advertise<ff_msgs::Feature2dArray>(inlier_topic, 1);
feature_sub_ = nh->subscribe(feature_topic, 1, &RobustFilter::FilterCallback, this);
imu_sub_ = nh->subscribe(imu_topic, 1, &RobustFilter::ImuCallback, this);
GetCamRot();
GetSimTF();
}
RobustFilter::~RobustFilter() {}
bool RobustFilter::CheckZeroTrans(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2, const Eigen::Matrix3f& R,
std::vector<unsigned int>* inliers) {
Eigen::RowVector3f A;
size_t A_cnt = 0;
size_t A_cnt_max = X1.cols() / 3; // One third of As are less than threshold! Assume zero translation
std::vector<unsigned int> tmp_inliers;
for (size_t i = 0; i < X1.cols(); ++i) {
A = GetRow(X1.col(i), X2.col(i), R);
if (A.norm() < threshold_A_) {
tmp_inliers.push_back(i);
++A_cnt;
}
}
if (A_cnt > A_cnt_max) {
*inliers = tmp_inliers;
//Disp("zero translation!!");
return true;
}
return false;
}
void RobustFilter::FilterCallback(const ff_msgs::Feature2dArray& features) {
if (frame_cnt_ < max_frame_cnt_)
++frame_cnt_;
else {
frame_cnt_ = 0;
features2_ = features;
GetSimTF();
size_t num_match = GetMatchingFeatures();
Eigen::Matrix3Xf X1 = Eigen::Matrix3Xf::Zero(3, num_match);
Eigen::Matrix3Xf X2 = Eigen::Matrix3Xf::Zero(3, num_match);
GetNormalizedFeatures(&X1, &X2);
std::vector<unsigned int> inliers;
Eigen::Vector3f C_trans = Eigen::Vector3f::Zero();
Eigen::Matrix3f R_rot = Eigen::Matrix3f::Identity();
if (show_true_inliers_) {
// True inliers
GetSimGroundTruthHomo(&R_rot, &C_trans);
GetSimGroundTruthInliers(X1, X2, R_rot, C_trans, &inliers);
} else {
// Esti inliers
GetImuRotation(&R_rot);
GetRansacInliers(X1, X2, R_rot, &C_trans, &inliers);
}
PublishInliers(inliers);
// Update prev vals
features1_ = features2_;
R_prev_ = R_curr_;
T_prev_ = T_curr_;
}
}
void RobustFilter::GetA(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2,
const Eigen::Matrix3f& R, Eigen::MatrixX3f* A) {
for (size_t i = 0; i < X1.cols(); ++i)
A->row(i) = GetRow(X1.col(i), X2.col(i), R);
}
void RobustFilter::GetCamRot() {
float phi_half = 1.57079632679;
R_cam_ = Eigen::AngleAxisf(-phi_half, Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(0, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(-phi_half, Eigen::Vector3f::UnitX());
H_cam_ << R_cam_.row(0), 0,
R_cam_.row(1), 0,
R_cam_.row(2), 0,
0, 0, 0 , 1;
H_cam_inv_ = H_cam_.inverse();
}
void RobustFilter::GetSimGroundTruthInliers(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2, const Eigen::Matrix3f& R,
const Eigen::Vector3f& C_trans, std::vector<unsigned int>* inliers) {
Eigen::Matrix3f R_inv = R.inverse();
if (C_trans.norm() == 0)
CheckZeroTrans(X1, X2, R_inv, inliers);
else
GetInliers(X1, X2, C_trans, R_inv, inliers);
}
void RobustFilter::GetImuRotation(Eigen::Matrix3f* R) {
ros::Time curr_time = ros::Time::now();
float time_diff = (curr_time - prev_time_).toSec();
if (time_diff < 0.000001)
Disp("IMU time is uncertain");
prev_time_ = curr_time;
float x_rot = (imu_msg_.angular_velocity.x + prev_x_rot_vel_) * time_diff * 0.5;
float y_rot = (imu_msg_.angular_velocity.y + prev_y_rot_vel_) * time_diff * 0.5;
float z_rot = (imu_msg_.angular_velocity.z + prev_z_rot_vel_) * time_diff * 0.5;
prev_x_rot_vel_ = imu_msg_.angular_velocity.x;
prev_y_rot_vel_ = imu_msg_.angular_velocity.y;
prev_z_rot_vel_ = imu_msg_.angular_velocity.z;
Eigen::Matrix3f M;
M = Eigen::AngleAxisf(z_rot, Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(y_rot, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(x_rot, Eigen::Vector3f::UnitX());
*R = R_cam_.inverse() * M * R_cam_;
}
void RobustFilter::GetInliers(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2, const Eigen::Vector3f& esti_trans,
const Eigen::Matrix3f& R, std::vector<unsigned int>* inliers) {
std::vector<unsigned int> tmp_inliers;
Eigen::RowVector3f A_row;
for (size_t i = 0; i < X1.cols(); ++i) {
A_row = GetRow(X1.col(i), X2.col(i), R);
if ((A_row * esti_trans).norm() < RANSAC_threshold_)
tmp_inliers.push_back(i);
}
if (tmp_inliers.size() > inliers->size())
*inliers = tmp_inliers;
}
size_t RobustFilter::GetMatchingFeatures() {
size_t cnt = 0;
size_t k = 0;
for (size_t i = 0; i < features1_.feature_array.size(); ++i) {
for (size_t j = k; j < features2_.feature_array.size(); ++j) {
if (features1_.feature_array[i].id == features2_.feature_array[j].id) {
features1_.feature_array[cnt] = features1_.feature_array[i];
features2_.feature_array[cnt] = features2_.feature_array[j];
++cnt;
k = j + 1;
break;
} else if (features1_.feature_array[i].id < features2_.feature_array[j].id)
break;
else
k = j;
}
}
return cnt;
}
void RobustFilter::GetNormalizedFeatures(Eigen::Matrix3Xf* X1, Eigen::Matrix3Xf* X2) {
for (size_t i = 0; i < X1->cols(); ++i) {
(*X1)(0, i) = features1_.feature_array[i].x;
(*X1)(1, i) = features1_.feature_array[i].y;
(*X1)(2, i) = 1;
(*X2)(0, i) = features2_.feature_array[i].x;
(*X2)(1, i) = features2_.feature_array[i].y;
(*X2)(2, i) = 1;
}
*X1 = K_inv_ * (*X1);
*X2 = K_inv_ * (*X2);
}
void RobustFilter::GetRansacInliers(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2, const Eigen::Matrix3f& R,
Eigen::Vector3f* C_ransac, std::vector<unsigned int>* inliers) {
Eigen::Matrix3f R_inv = R.inverse();
size_t num_match = X1.cols();
if (num_match < 2)
Disp("At least two correspondances are required");
else {
*C_ransac = Eigen::Vector3f::Zero();
bool zero_pos = CheckZeroTrans(X1, X2, R_inv, inliers);
if (!zero_pos){
Eigen::MatrixX3f A, ATA;
Eigen::Matrix3Xf X1_samples(3, 2), X2_samples(3, 2);
unsigned int r1, r2, seed1, seed2;
for (size_t i = 0; i < RANSAC_iteration_; ++i) {
r1 = rand_r(&seed1) % num_match;
do {
r2 = rand_r(&seed2) % num_match;
} while (r1 == r2);
X1_samples << X1.col(r1), X1.col(r2);
X2_samples << X2.col(r1), X2.col(r2);
// Solve t using eigendecomposition of A'A
A.resize(X1_samples.cols(), 3);
GetA(X1_samples, X2_samples, R_inv, &A);
ATA = A.transpose() * A;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(ATA);
GetInliers(X1, X2, eigensolver.eigenvectors().col(0), R_inv, inliers);
}
A.resize(inliers->size(), 3);
for (size_t i = 0; i < inliers->size(); ++i)
A.row(i) = GetRow(X1.col((*inliers)[i]), X2.col((*inliers)[i]), R_inv);
ATA = A.transpose() * A;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(ATA);
*C_ransac = eigensolver.eigenvectors().col(0);
}
}
}
Eigen::RowVector3f RobustFilter::GetRow(const Eigen::Vector3f& fst, const Eigen::Vector3f& scd, const Eigen::Matrix3f& R) {
Eigen::RowVector3f V1 = R.row(1) - scd(1) * R.row(2);
Eigen::RowVector3f V2 = R.row(0) - scd(0) * R.row(2);
Eigen::RowVector3f V = V1 * fst * V2 - V2 * fst * V1;
return V;
}
void RobustFilter::GetSimGroundTruthHomo(Eigen::Matrix3f* R_true, Eigen::Vector3f* C_true) {
Eigen::Matrix4f H_prev, H_curr, H_diff;
H_prev << R_prev_.row(0), T_prev_(0),
R_prev_.row(1), T_prev_(1),
R_prev_.row(2), T_prev_(2),
0, 0, 0 , 1;
H_curr << R_curr_.row(0), T_curr_(0),
R_curr_.row(1), T_curr_(1),
R_curr_.row(2), T_curr_(2),
0, 0, 0 , 1;
H_diff = H_cam_inv_ * H_prev.inverse() * H_curr * H_cam_;
*R_true << H_diff(0, 0), H_diff(0, 1), H_diff(0, 2),
H_diff(1, 0), H_diff(1, 1), H_diff(1, 2),
H_diff(2, 0), H_diff(2, 1), H_diff(2, 2);
*C_true << H_diff(0, 3), H_diff(1, 3), H_diff(2, 3);
float cd_norm = C_true->norm();
if (cd_norm > 0)
*C_true /= cd_norm;
else {
//Disp("C_true is zero");
*C_true = Eigen::Vector3f::Zero();
}
}
void RobustFilter::GetSimTF() {
try {
listener_.waitForTransform("/odom", "/camera_link", ros::Time(0), ros::Duration(10.0));
listener_.lookupTransform("/odom", "/camera_link", ros::Time(0), curr_camera_tf_);
tf::Quaternion quat = curr_camera_tf_.getRotation();
tf::Matrix3x3 R2;
R2.setRotation(quat);
R_curr_ << R2[0][0], R2[0][1], R2[0][2],
R2[1][0], R2[1][1], R2[1][2],
R2[2][0], R2[2][1], R2[2][2];
T_curr_ << curr_camera_tf_.getOrigin().x(), curr_camera_tf_.getOrigin().y(), curr_camera_tf_.getOrigin().z();
} catch (tf::TransformException ex) {
ROS_WARN("%s",ex.what());
}
/* This does not work since robot_state_publisher still publishes tf style broadcasting
tf2_ros::Buffer tf2_buffer;
tf2_ros::TransformListener tf2_camera(tf2_buffer);
//geometry_msgs::TransformStamped curr_camera_tf;
try {
curr_camera_tf_ = tf2_buffer.lookupTransform("/odom", "/camera_link", ros::Time(0));
tf2::Quaternion quat = tf2::Quaternion(curr_camera_tf_.transform.rotation.x,
curr_camera_tf_.transform.rotation.y,
curr_camera_tf_.transform.rotation.z,
curr_camera_tf_.transform.rotation.w);
tf2::Matrix3x3 R2(quat);
R_curr_ << R2[0][0], R2[0][1], R2[0][2],
R2[1][0], R2[1][1], R2[1][2],
R2[2][0], R2[2][1], R2[2][2];
T_curr_ << curr_camera_tf_.transform.translation.x,
curr_camera_tf_.transform.translation.y,
curr_camera_tf_.transform.translation.z;
} catch(tf2::TransformException &ex) {
ROS_WARN("%s",ex.what());
ros::Duration(1.0).sleep();
}
*/
}
void RobustFilter::ImuCallback(const sensor_msgs::Imu& imu_msg) {
imu_msg_ = imu_msg;
}
void RobustFilter::PublishInliers(const std::vector<unsigned int>& inliers) {
ff_msgs::Feature2dArray features;
ff_msgs::Feature2d tmp_feature;
for (size_t i = 0; i < inliers.size(); ++i) {
tmp_feature.id = features2_.feature_array[inliers[i]].id;
tmp_feature.x = features2_.feature_array[inliers[i]].x;
tmp_feature.y = features2_.feature_array[inliers[i]].y;
features.feature_array.push_back(tmp_feature);
}
inlier_pub_.publish(features);
}
void RobustFilter::Disp(const std::string& str) {
std::cout<< str <<std::endl;
}
void RobustFilter::Dispfloat(const std::string& str, const float& val) {
std::cout<< str << val << std::endl;
}
void RobustFilter::DispResidualC(const Eigen::Matrix3Xf& X1, const Eigen::Matrix3Xf& X2,
const Eigen::Vector3f& C_true, const Eigen::Matrix3f& R) {
Disp("================");
DispVector3f("C_true = ", C_true);
Eigen::RowVector3f A_row;
Eigen::Matrix3f R_inv = R.inverse();
for (size_t i = 0; i < X1.cols(); ++i) {
A_row = GetRow(X1.col(i), X2.col(i), R_inv);
std::cout<<"ID: "<<features1_.feature_array[i].id << " resi = " << (A_row * C_true).norm() << std::endl;
DispVector3f("A = ", A_row);
}
}
void RobustFilter::DispInt(const std::string& str, const int& val) {
std::cout<< str << val << std::endl;
}
void RobustFilter::DispVector3f(const std::string& str, const Eigen::Vector3f& v) {
std::cout<< str << v(0) << "/" << v(1) <<"/" << v(2) << std::endl;
}
} // end namespace robust_filter_node
|
#pragma once
#include "VdmaOut.h"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#define HPD_GPIO_ADDRESS 0x41200000
class Hdmi
{
private:
Hdmi();
static Hdmi *_instance;
VDMA vdmaOut;
PDWORD hdmiHpdGpio;
public:
static Hdmi* GetInstance();
void TurnOnVideoCapture();
void TurnOffVideoCapture();
void Display(cv::Mat);
cv::Mat Capture();
};
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (1e15);
const int INF = (1<<27);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class OneRegister {
public:
set<long long> used;
string getProgram(int s, int t) {
used.clear();
queue<long long> Q;
queue<string> QS;
Q.push(s);
QS.push("");
while (!Q.empty()) {
long long k = Q.front();
string l = QS.front();
Q.pop() , QS.pop();
if (k == t)
return l;
if (k*k <= 1000000000 && used.find(k*k) == used.end()) {
Q.push(k*k);
QS.push(l+"*");
used.insert(k*k);
}
if (2*k <= 1000000000 && used.find(2*k) == used.end()) {
Q.push(2*k);
QS.push(l+"+");
used.insert(2*k);
}
if (used.find(1) == used.end()) {
Q.push(1);
QS.push(l+'/');
used.insert(1);
}
}
return ":-(";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 7; int Arg1 = 392; string Arg2 = "+*+"; verify_case(0, Arg2, getProgram(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 7; int Arg1 = 256; string Arg2 = "/+***"; verify_case(1, Arg2, getProgram(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 4; int Arg1 = 256; string Arg2 = "**"; verify_case(2, Arg2, getProgram(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 7; int Arg1 = 7; string Arg2 = ""; verify_case(3, Arg2, getProgram(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 7; int Arg1 = 9; string Arg2 = ":-("; verify_case(4, Arg2, getProgram(Arg0, Arg1)); }
void test_case_5() { int Arg0 = 10; int Arg1 = 1; string Arg2 = "/"; verify_case(5, Arg2, getProgram(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
OneRegister ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#pragma once
#include <boost/variant/static_visitor.hpp>
#include <iostream>
#include <string>
class print_visitor : public boost::static_visitor<>
{
protected:
static constexpr unsigned int INDENT_SPACES = 2;
public:
print_visitor()
: _indent( 0 )
{
}
print_visitor( unsigned int indent )
: _indent( indent )
, _indent_string( indent, ' ' )
{
}
protected:
std::ostream& indent() const
{
return std::cout << _indent_string << "* ";
}
const unsigned int _indent;
const std::string _indent_string;
};
|
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_data[] = {
________,________,
____XXXX,XX______,
__XXX___,_XXX____,
__XX_XXX,X_XXX___,
_XX_XX__,___XX___,
_XX_XX__,___XX___,
_XX_XX__,___XX___,
_XX_XX__,___XX___,
_XX__XXX,X__XX___,
__XX____,__XXX___,
__XXX___,_XXX____,
____XXXX,XX______,
________,________,
________,________,
________,________,
________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_otbl[] = {
0, //< Offset for symbol 0x000000A9 '©'
14 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_bmp = {
// size
{14, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9 = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_bmp, //< data (glyphs bitmap)
0xA9, //< chFirst
0xA9, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xA9_0xA9_otbl //< glyphsMap
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_data[] = {
__XXXXX_,________,
_XX___XX,________,
_X_XXXXX,________,
_X_X__XX,________,
_X_X_XXX,________,
_X_X_X_X,________,
_XX___XX,________,
__XXXXX_,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_otbl[] = {
0, //< Offset for symbol 0x000000AE '®'
9 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_bmp = {
// size
{9, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_bmp, //< data (glyphs bitmap)
0xAE, //< chFirst
0xAE, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xAE_0xAE_otbl //< glyphsMap
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_data[] = {
__XX____,________,________,________,
_X__X___,_______X,XXXX_XXX,XX______,
__XX____,_XX_____,__XX____,XX______,
________,_XX_____,__XX_XXX,XX______,
________,_XX_____,XXX_____,_X______,
______XX,XXXXXX_X,XX______,_X______,
________,_XX____X,XXXX_XXX,XX______,
________,_XX_____,________,________,
________,_XX_____,________,________,
________,________,________,________,
______XX,XXXXXX__,________,________,
________,________,________,________,
________,________,________,________,
________,________,________,________,
________,________,________,________,
________,________,________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_otbl[] = {
0, //< Offset for symbol 0x000000B0 '°'
5, //< Offset for symbol 0x000000B1 '±'
14, //< Offset for symbol 0x000000B2 '?'
21, //< Offset for symbol 0x000000B3 '?'
27 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_bmp = {
// size
{27, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3 = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_bmp, //< data (glyphs bitmap)
0xB0, //< chFirst
0xB3, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xB0_0xB3_otbl //< glyphsMap
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_data[] = {
________,________,
________,________,
________,________,
________,________,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XXX__XX,X_______,
_XX_XX_X,X_______,
_XX_____,________,
_XX_____,________,
_XX_____,________,
________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_otbl[] = {
0, //< Offset for symbol 0x000000B5 'µ'
10 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_bmp = {
// size
{10, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5 = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_bmp, //< data (glyphs bitmap)
0xB5, //< chFirst
0xB5, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xB5_0xB5_otbl //< glyphsMap
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_data[] = {
________,________,
XX____XX,X_______,
_X___X__,_X______,
_X___X__,_X______,
_X___X__,_X______,
_X____XX,X_______,
_X______,________,
_____XXX,XX______,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_otbl[] = {
0, //< Offset for symbol 0x000000B9 '?'
4, //< Offset for symbol 0x000000BA '?'
11 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_bmp = {
// size
{11, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_bmp, //< data (glyphs bitmap)
0xB9, //< chFirst
0xBA, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xB9_0xBA_otbl //< glyphsMap
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7' definition
//
// Bitmap data
static const esU8 sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_data[] = {
________,________,
________,________,
________,________,
________,________,
__XX__XX,________,
__XXXXXX,________,
___XXXX_,________,
___XXXX_,________,
__XXXXXX,________,
__XX__XX,________,
________,________,
________,________,
________,________,
________,________,
________,________,
________,________,
};
// Font block 'magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7' glyphs offsets data
static const esU16 sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_otbl[] = {
0, //< Offset for symbol 0x000000D7 '?'
9 //< Last offset item
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7' block glyphs bitmap
static const ESGUI_BITMAP sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_bmp = {
// size
{9, 16},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_data
};
// Font 'magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7' block data
const ESGUI_FONT_DATA c_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7 = {
&sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_bmp, //< data (glyphs bitmap)
0xD7, //< chFirst
0xD7, //< chLast
4, //< spaceWidth
10, //< nullWidth
sc_magistraltt16_latin_1_supplement_1bpp_0xD7_0xD7_otbl //< glyphsMap
};
|
#include "rdtsc_benchmark.h"
#include "ut.hpp"
#include <random>
#include <algorithm>
#include <math.h>
#include <functional>
#include <vector>
#include "particle.h"
#include "fastslam1_utils.h"
#include "configfile.h"
#include "linalg.h"
#include "trigonometry.h"
#include "fastrand.h"
#include "predict_update.h"
using namespace boost::ut; // provides `expect`, `""_test`, etc
using namespace boost::ut::bdd; // provides `given`, `when`, `then`
void data_loader(double* wp, size_t N_waypoints, double V, double* Q, double dt,
size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) {
srand(0);
uint64_t init_state[8] = {1,1,1,1,1,1,1,1};
uint64_t init_seq[8] = {1,2,3,4,5,6,7,8};
pcg32_srand(1,1);
avx2_pcg32_srand(init_state, init_seq);
avx_xorshift128plus_init(1,1);
xtrue[0]= 1.0;
xtrue[1]= 2.0;
xtrue[2]= 0.0;
*iwp=1;
*G = 0.0;
for (int i = 0; i< N; i++) {
particles[i].xv[0] = xtrue[0];
particles[i].xv[1] = xtrue[1];
particles[i].xv[2] = xtrue[2];
}
}
void init_particles(Particle* particle, double* xv, double* Pv, const size_t N) {
for (int i = 0; i<N; i++) {
initParticle(particle+i, 0, xv+3*i);
}
}
void init_particles_contigous(Particle* particle, double* xv, double* Pv, const size_t N) {
for (int i = 0; i<N; i++) {
particle[i].xv = xv+3*i;
particle[i].Pv = Pv+9*i;
initParticle_prealloc(particle+i, 0, xv+3*i);
}
}
// I will try to add this as smooth as possible to the benchmark, but for now do this
void set_work(Benchmark<decltype(&predict_update)>& bench,
double* wp, size_t N_waypoints, double V, double* Q, double dt,
size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) {
data_loader(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
bench.funcFlops[0] = predict_update_base_flops(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
data_loader(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
bench.funcBytes[0] = 8 * predict_update_base_memory(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
data_loader(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
for (int i = 1; i < bench.numFuncs; i++) {
bench.funcFlops[i] = predict_update_active_flops(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
data_loader(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
bench.funcBytes[i] = 8* predict_update_active_memory(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
data_loader(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles);
}
}
void cleanup_members(Particle* particles, int N) {
for(int i = 0; i<N; i++) {
delParticleMembers_prealloc(particles+i);
}
}
int main() {
//init_sin();
//init_sin2();
SWITCH_PREDICT_NOISE=1;
SWITCH_CONTROL_NOISE=1;
const int N = 100;
double minD = 0.1;
double rateG = 1.0;
double maxG = 1.5;
double dt = 1.0;
double V = 3.0;
setup_initial_Q_R(); // Remove this soon!!!
int N_waypoints = 3;
double wp[6] = {0,0,1,1,2,2};
double xv[3*N] __attribute__ ((aligned(32)));
double Pv[9*N] __attribute__ ((aligned(32)));
fill(xv, 2*N, 0.0);
Particle particles[N];
init_particles_contigous(particles, xv, Pv, N);
int iwp = 1;
double G = 0.0;
Vector3d xtrue;
data_loader(wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles);
predict_update_fast_normal_rand(wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G, particles);
double xv_exact[3*N] __attribute__ ((aligned(32)));
double Pv_exact[9*N] __attribute__ ((aligned(32)));
fill(xv_exact, 2*N, 0.0);
Particle particles_exact[N];
init_particles_contigous(particles_exact, xv_exact, Pv_exact, N);
int iwp_exact = 1;
double G_exact = 0.0;
Vector3d xtrue_exact;
data_loader(wp, N_waypoints, V, *Q, dt, N, xtrue_exact, &iwp_exact, &G_exact, particles_exact);
predict_update_base(wp, N_waypoints, V, *Q, dt, N, xtrue_exact, &iwp_exact, &G_exact, particles_exact);
expect(that % fabs(G - G_exact) < 1.0e-10) << "G";
expect(that % (iwp - iwp_exact) == 0 ) << "iwp";
for (int i=0; i<N; i++) {
expect(that % fabs(particles[i].xv[0] - particles_exact[i].xv[0]) < 1.0e-6) <<particles[i].xv[0] << "x"<< i <<particles_exact[i].xv[0];
expect(that % fabs(particles[i].xv[1] - particles_exact[i].xv[1]) < 1.0e-6) <<particles[i].xv[1] << "y"<< i <<particles_exact[i].xv[1];
expect(that % fabs(particles[i].xv[2] - particles_exact[i].xv[2]) < 1.0e-6);
}
expect(that % fabs(xtrue[0] - xtrue_exact[0]) < 1.0e-10);
expect(that % fabs(xtrue[1] - xtrue_exact[1]) < 1.0e-10);
expect(that % fabs(xtrue[2] - xtrue_exact[2]) < 1.0e-10);
// Initialize the benchmark struct by declaring the type of the function you want to benchmark
Benchmark<decltype(&predict_update_base)> bench("predict_update Benchmark");
bench.data_loader = data_loader;
// Add your functions to the struct, give it a name (Should describe improvements there) and yield the flops this function has to do (=work)
// First function should always be the base case you want to benchmark against!
bench.add_function(&predict_update_base, "base", 0.0);
bench.add_function(&predict_update_old, "functions inplace", 0.0);
bench.add_function(&predict_update_sine, "sine approximation", 0.0);
bench.add_function(&predict_update_simd, "basic simd", 0.0);
bench.add_function(&predict_update_fast_scalar_pipi, "simd + scalar pi_to_pi", 0.0);
bench.add_function(&predict_update_fast_normal_rand, "simd opt. normal rand", 0.0);
bench.add_function(&predict_update_fast_plain, "simd opt. fast rand", 0.0);
bench.add_function(&predict_update_fast, "fastest", 0.0);
//Run the benchmark: give the inputs of your function in the same order as they are defined.
set_work(bench, wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles) ;
bench.run_benchmark(wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles);
G = M_PI;
//Run the benchmark: give the inputs of your function in the same order as they are defined.
set_work(bench, wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles) ;
bench.run_benchmark(wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles);
minD = 5.0;
//Run the benchmark: give the inputs of your function in the same order as they are defined.
set_work(bench, wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles) ;
bench.run_benchmark(wp, N_waypoints, V, *Q, dt, N, xtrue, &iwp, &G,particles);
//bench.destructor_output = false;
bench.details();
Benchmark<decltype(&predict_update_base)> bench_scale("predict_update with Particles");
bench_scale.add_function(&predict_update_base, "base", 0.0);
bench_scale.add_function(&predict_update_old, "functions inplace", 0.0);
bench_scale.add_function(&predict_update_sine, "sine approximation", 0.0);
bench_scale.add_function(&predict_update_simd, "basic simd", 0.0);
bench_scale.add_function(&predict_update_fast_scalar_pipi, "simd + scalar pi_to_pi", 0.0);
bench_scale.add_function(&predict_update_fast_normal_rand, "simd opt. normal rand", 0.0);
bench_scale.add_function(&predict_update_fast_plain, "simd opt. fast rand", 0.0);
bench_scale.add_function(&predict_update_fast, "fastest", 0.0);
bench_scale.add_function(&predict_update_fast, "fast", 0.0);
bench_scale.data_loader = data_loader;
bench_scale.csv_path = "predict_update_scale_particles.csv";
bench_scale.csv_output = false;
int Np = 100;
for (int i = 0; i< 9; i++) {
const int Npi = std::pow(2,i) * Np;
Particle* ps = (Particle*) aligned_alloc(32, Npi * sizeof(Particle));
double xvi[3*Npi] __attribute__ ((aligned(32)));
double Pvi[9*Npi] __attribute__ ((aligned(32)));
fill(xvi, 2*Npi, 0.0);
init_particles_contigous(ps, xvi, Pvi, Npi);
set_work(bench_scale, wp, N_waypoints, V, *Q, dt, Npi, xtrue, &iwp, &G,ps);
bench_scale.run_name = std::to_string(Npi);
bench_scale.run_benchmark(wp, N_waypoints, V, *Q, dt, Npi, xtrue, &iwp, &G,ps);
cleanup_members(ps, Npi);
free(ps);
}
bench_scale.details();
bench_scale.write_csv_details();
return 0;
}
|
// Copyright (C) 2012 - 2013 Mihai Preda
#include "Pepper.h"
#include "GC.h"
#include "Parser.h"
#include "VM.h"
#include "Array.h"
#include "Map.h"
#include "SymbolTable.h"
#include "String.h"
#include "CFunc.h"
#include "Type.h"
#include "builtin.h"
#include <assert.h>
#include <stdlib.h>
Pepper::Pepper(void *context) :
_gc(new GC()),
vm(new VM(this)),
types(new Types(vm)),
_syms(SymbolTable::alloc(_gc)),
_regs(Array::alloc(_gc))
{
vm->types = types;
assert(sizeof(Array) == 2 * sizeof(long));
_gc->addRoot((Object *) _syms);
_gc->addRoot((Object *) _regs);
_regs->push(CFunc::value(_gc, builtinParseFunc)); // 0
_regs->push(CFunc::value(_gc, builtinParseBlock)); // 1
_regs->push(CFunc::value(_gc, builtinFileRead)); // 2
_regs->push(CFunc::value(_gc, javaClass)); // 3
_syms->add(_gc, _regs, "type", CFunc::value(_gc, builtinType)); // 4
_syms->add(_gc, _regs, "print", CFunc::value(_gc, builtinPrint)); // 5
_syms->add(_gc, _regs, "parse", VNIL); // 6
_syms->add(_gc, _regs, "file", VNIL); // 7
_syms->add(_gc, _regs, "java", VNIL); // 8
Func *f = parseStatList("\
imports := {}\
return fn(name) {\
if !imports[name] {\
data := file.read(name + '.pep')\
if data { imports[name] = parse.block(data)() }\
}\
return imports[name]\
}");
Value import = run(f, 0, 0);
_syms->add(_gc, _regs, "import", import); // 9
}
Pepper::~Pepper() {
delete vm;
vm = 0;
delete types;
types = 0;
delete _gc;
_gc = 0;
_syms = 0; // garbage collected
}
Value *Pepper::regs() {
return _regs->vect.buf();
}
Value Pepper::run(Func *f, int nArg, Value *args) {
return vm->run(VAL_OBJ(f), nArg, args);
}
Func *Pepper::parseFunc(const char *text) {
return Parser::parseInEnv(this, text, true);
}
Func *Pepper::parseStatList(const char *text) {
return Parser::parseInEnv(this, text, false);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2008-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file CryptoHash_impl.cpp
*
* This file implements the libcrypto hash algorithms towards the
* openssl crypto library(modules/libopeay)
*/
#include "core/pch.h"
#include "modules/libcrypto/src/openssl_impl/CryptoHash_impl.h"
#include "modules/libcrypto/src/openssl_impl/openssl_util.h"
#include "modules/util/cleanse.h"
#ifdef CRYPTO_API_SUPPORT
/* static */ CryptoHash* CryptoHash::Create(CryptoHashAlgorithm algorithm)
{
switch (algorithm)
{
#ifdef CRYPTO_HASH_MD5_SUPPORT
case CRYPTO_HASH_TYPE_MD5: return CreateMD5();
#endif
#ifdef CRYPTO_HASH_SHA1_SUPPORT
case CRYPTO_HASH_TYPE_SHA1: return CreateSHA1();
#endif
#ifdef CRYPTO_HASH_SHA256_SUPPORT
case CRYPTO_HASH_TYPE_SHA256: return CreateSHA256();
#endif
}
return NULL;
}
#endif // CRYPTO_API_SUPPORT
#ifdef CRYPTO_HASH_MD5_USE_CORE_IMPLEMENTATION
/* static */ CryptoHash * CryptoHash::CreateMD5()
{
return OP_NEW(CryptoHashMD5, ());
}
CryptoHashMD5::~CryptoHashMD5()
{
OPERA_cleanse(&m_md5_state, sizeof(MD5_CTX));
}
OP_STATUS CryptoHashMD5::InitHash()
{
MD5_Init(&m_md5_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
return OpStatus::OK;
}
void CryptoHashMD5::CalculateHash(const UINT8 *source, int len)
{
OP_ASSERT(source && len >= 0);
MD5_Update(&m_md5_state, source, len);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashMD5::CalculateHash(const char *source)
{
OP_ASSERT(source);
MD5_Update(&m_md5_state, source, op_strlen(source));
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashMD5::ExtractHash(UINT8 *result)
{
OP_ASSERT(result);
MD5_Final(result, &m_md5_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
#endif // CRYPTO_HASH_MD5_USE_CORE_IMPLEMENTATION
#ifdef CRYPTO_HASH_SHA1_USE_CORE_IMPLEMENTATION
CryptoHash *CryptoHash::CreateSHA1()
{
return OP_NEW(CryptoHashSHA1, ());
}
CryptoHashSHA1::~CryptoHashSHA1()
{
OPERA_cleanse(&m_sha1_state, sizeof(SHA_CTX));
}
OP_STATUS CryptoHashSHA1::InitHash()
{
SHA1_Init(&m_sha1_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
return OpStatus::OK;
}
void CryptoHashSHA1::CalculateHash(const UINT8 *source, int len)
{
OP_ASSERT(source && len >= 0);
SHA1_Update(&m_sha1_state, source, len);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashSHA1::CalculateHash(const char *source)
{
OP_ASSERT(source);
SHA1_Update(&m_sha1_state, source, op_strlen(source));
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashSHA1::ExtractHash(UINT8 *result)
{
OP_ASSERT(result);
SHA1_Final(result, &m_sha1_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
#endif // CRYPTO_HASH_SHA1_USE_CORE_IMPLEMENTATION
#ifdef CRYPTO_HASH_SHA256_USE_CORE_IMPLEMENTATION
CryptoHash *CryptoHash::CreateSHA256()
{
return OP_NEW(CryptoHashSHA256, ());
}
CryptoHashSHA256::~CryptoHashSHA256()
{
OPERA_cleanse(&m_sha256_state, sizeof(SHA256_CTX));
}
OP_STATUS CryptoHashSHA256::InitHash()
{
SHA256_Init(&m_sha256_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
return OpStatus::OK;
}
void CryptoHashSHA256::CalculateHash(const UINT8 *source, int len)
{
OP_ASSERT(source && len >= 0);
SHA256_Update(&m_sha256_state, source, len);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashSHA256::CalculateHash(const char *source)
{
OP_ASSERT(source);
SHA256_Update(&m_sha256_state, source, op_strlen(source));
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
void CryptoHashSHA256::ExtractHash(UINT8 *result)
{
OP_ASSERT(result);
SHA256_Final(result, &m_sha256_state);
// The function just called doesn't add errors to OpenSSL error queue.
OP_ASSERT(ERR_peek_error() == 0);
}
#endif // CRYPTO_HASH_SHA256_USE_CORE_IMPLEMENTATION
|
#pragma once
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "Ability.hh"
#include "CppCommons.hh"
#include "DBManager.hh"
#include "Hero.hh"
#include "Town.hh"
#include "Unit.hh"
namespace dbmanager_test {
using namespace CCC;
using namespace HotaSim;
static const char* DB_PATH = "resources/HotaSim.db";
class DBManagerMock : public DBManager {
public:
DBManagerMock()
: DBManager() {}
};
class DBManagerTest : public ::testing::Test {
protected:
void SetUp() override {
testing::internal::CaptureStdout();
try { dbmgr.loadDB(DB_PATH); }
catch( const std::exception& ) {}
testing::internal::GetCapturedStdout();
}
DBManagerMock dbmgr;
};
// DBManager.createObject
TEST_F(DBManagerTest, shouldThrowWhenCreatingFromNonExistingTemplate) {
ASSERT_THROW(dbmgr.createObject<Ability>(0), std::exception);
ASSERT_THROW(dbmgr.createObject<Hero>(0), std::exception);
ASSERT_THROW(dbmgr.createObject<Unit>(0), std::exception);
}
TEST_F(DBManagerTest, shouldCreateAbilityFromTemplateIdOne) {
std::shared_ptr<Ability> ability;
ASSERT_NO_THROW(ability = dbmgr.createObject<Ability>(1));
ASSERT_TRUE(ability->getName() == "Sorcery_Basic");
ASSERT_TRUE(compareFloats(ability->getActivationChance(), 1.0f));
ASSERT_TRUE(ability->getTarget() == AbilityTarget::friendly_hero);
ASSERT_TRUE(ability->getActivation() == AbilityActivation::before_battle);
ASSERT_TRUE(ability->getEffects().empty());
}
TEST_F(DBManagerTest, shouldCreateHeroFromTemplateIdOne) {
std::shared_ptr<Hero> hero;
ASSERT_NO_THROW(hero = dbmgr.createObject<Hero>(1));
ASSERT_TRUE(hero->getName() == "Calh");
ASSERT_TRUE(hero->getTown()->getName() == "Inferno");
ASSERT_TRUE(hero->getAbilities().size() == 3);
ASSERT_TRUE(hero->getSpells().empty());
ASSERT_TRUE(hero->getUnits().size() == 3);
}
TEST_F(DBManagerTest, shouldCreateUnitFromTemplateIdOne) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.createObject<Unit>(1));
ASSERT_TRUE(unit->getName() == "Imp");
ASSERT_TRUE(unit->getTown()->getName() == "Inferno");
ASSERT_TRUE(unit->getAbilities().empty());
ASSERT_TRUE(unit->getBaseAttributes() == unit->getAttributes());
auto imp_attr = UnitAttributes{ 4, 2, 3, 5, 0, 1, 2, 1 };
ASSERT_TRUE(unit->getBaseAttributes() == imp_attr);
}
TEST_F(DBManagerTest, shouldReturnNewInstanceFromSameTemplateWhenCreate) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.createObject<Unit>(1));
std::shared_ptr<Unit> unit2;
ASSERT_NO_THROW(unit2 = dbmgr.createObject<Unit>(1));
ASSERT_FALSE(unit == unit2);
}
TEST_F(DBManagerTest, shouldReturnDifferentObjectsFromDifferentsTemplatesWhenCreate) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.createObject<Unit>(1));
std::shared_ptr<Unit> unit2;
ASSERT_NO_THROW(unit2 = dbmgr.createObject<Unit>(2));
ASSERT_FALSE(unit == unit2);
}
// DBManager.shareObject
TEST_F(DBManagerTest, shouldThrowWhenSharingFromNonExistingTemplate) {
ASSERT_THROW(dbmgr.shareObject<Ability>(0), std::exception);
ASSERT_THROW(dbmgr.shareObject<Hero>(0), std::exception);
ASSERT_THROW(dbmgr.shareObject<Unit>(0), std::exception);
}
TEST_F(DBManagerTest, shouldShareAbilityFromTemplateIdOne) {
std::shared_ptr<Ability> ability;
ASSERT_NO_THROW(ability = dbmgr.shareObject<Ability>(1));
ASSERT_TRUE(ability->getName() == "Sorcery_Basic");
ASSERT_TRUE(compareFloats(ability->getActivationChance(), 1.0f));
ASSERT_TRUE(ability->getTarget() == AbilityTarget::friendly_hero);
ASSERT_TRUE(ability->getActivation() == AbilityActivation::before_battle);
ASSERT_TRUE(ability->getEffects().empty());
}
TEST_F(DBManagerTest, shouldShareHeroFromTemplateIdOne) {
std::shared_ptr<Hero> hero;
ASSERT_NO_THROW(hero = dbmgr.shareObject<Hero>(1));
ASSERT_TRUE(hero->getName() == "Calh");
ASSERT_TRUE(hero->getTown()->getName() == "Inferno");
ASSERT_TRUE(hero->getAbilities().size() == 3);
ASSERT_TRUE(hero->getSpells().empty());
ASSERT_TRUE(hero->getUnits().size() == 3);
}
TEST_F(DBManagerTest, shouldShareUnitFromTemplateIdOne) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.shareObject<Unit>(1));
ASSERT_TRUE(unit->getName() == "Imp");
ASSERT_TRUE(unit->getTown()->getName() == "Inferno");
ASSERT_TRUE(unit->getAbilities().empty());
ASSERT_TRUE(unit->getBaseAttributes() == unit->getAttributes());
auto imp_attr = UnitAttributes{ 4, 2, 3, 5, 0, 1, 2, 1 };
ASSERT_TRUE(unit->getBaseAttributes() == imp_attr);
}
TEST_F(DBManagerTest, shouldReturnSameInstanceFromSameTemplateWhenShare) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.shareObject<Unit>(1));
std::shared_ptr<Unit> unit2;
ASSERT_NO_THROW(unit2 = dbmgr.shareObject<Unit>(1));
ASSERT_TRUE(unit == unit2);
}
TEST_F(DBManagerTest, shouldReturnDifferentObjectsFromDifferentsTemplatesWhenShare) {
std::shared_ptr<Unit> unit;
ASSERT_NO_THROW(unit = dbmgr.createObject<Unit>(1));
std::shared_ptr<Unit> unit2;
ASSERT_NO_THROW(unit2 = dbmgr.createObject<Unit>(2));
ASSERT_FALSE(unit == unit2);
}
}
|
#pragma once
#include <QWidget>
#include <memory>
#include <vector>
using std::unique_ptr;
struct impl_drag_widget;
class drag_widget : public QWidget
{
Q_OBJECT
signals:
void button_triggered (const QString&);
public:
static unique_ptr<drag_widget> make (std::vector<QString> labels = {},
std::vector<QString> buttons = {},
QWidget* parent = nullptr);
void reset_status ();
QString status ();
virtual ~drag_widget () override;
protected:
explicit drag_widget(std::vector<QString> labels, std::vector<QString> buttons, QWidget *parent = 0);
bool init ();
private:
void mousePressEvent(QMouseEvent* event) override;
void hideEvent (QHideEvent* event) override;
void on_button_pressed ();
private:
unique_ptr<impl_drag_widget> imp;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.