hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
281874f0f50215f6ddae0de843f105fd9460a5dc | 906 | hpp | C++ | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | 2 | 2021-11-15T19:27:32.000Z | 2021-12-10T20:51:37.000Z | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | null | null | null | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | null | null | null | #pragma once
#include "unit/unit.hpp"
class Knight : public Unit {
public:
Knight(int hp = 80, int dmg = 15, int df = 5) {
health = hp;
maxHealth = hp;
damage = dmg;
defense = df;
graphics = 'k';
}
~Knight() {}
virtual bool attack(Unit&) override;
virtual Knight* duplicate() override;
virtual void setHealth(int h) override { health = h; }
virtual int getHealth() override { return health; }
virtual void setDefense(int d) override { defense = d; }
virtual int getDefense() override { return defense; }
virtual void setDamage(int d) override { damage = d; }
virtual int getDamage() override { return damage; }
virtual void setGraphics(char g) override { graphics = g; }
virtual char getGraphics() override { return graphics; }
};
| 29.225806 | 67 | 0.572848 |
2819887ad608e023490df95aa9871e8f846b53bd | 151 | cpp | C++ | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | //
// Created by kdahi on 2020-09-29.
//
#include "Layer.h"
Layer::Layer(std::string name) : m_DebugName(std::move(name)) {
}
Layer::~Layer() {
} | 10.785714 | 63 | 0.609272 |
281a91c72bf7f47480b2a52e92ab2773f3aac8da | 3,011 | cpp | C++ | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | #include "DataSystem.h"
DataSystem* DataSystem::Instance = nullptr;
DataSystem::DataSystem()
{
Instance = this;
}
DataSystem::~DataSystem()
{
Instance = nullptr;
RemoveShaders();
}
void DataSystem::LoadShaders()
{
try
{
std::filesystem::path shaderpath = Path::Relative("shaders\\");
for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath))
{
if (dir.is_directory())
continue;
if (dir.path().extension() == ".hlsl")
{
AddShaderFromPath(dir.path());
}
}
}
catch (const std::filesystem::filesystem_error& e)
{
WARN("Could not load shaders" + e.what());
}
catch (const std::exception& e)
{
WARN("Error" + e.what());
}
}
void DataSystem::LoadModels()
{
std::filesystem::path shaderpath = Path::Relative("meshes\\");
for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath))
{
if (dir.is_directory())
continue;
if (dir.path().extension() == ".dae" || dir.path().extension() == ".gltf" || dir.path().extension() == ".fbx")
{
AddModel(dir.path(), dir.path().parent_path());
}
}
}
//void DataSystem::ReloadShaders()
//{
// OnShadersReloadedEvent.Invoke();
// RemoveShaders();
// LoadShaders();
// ShadersReloadedEvent.Invoke();
//}
void DataSystem::AddShaderFromPath(const std::filesystem::path& filepath)
{
Microsoft::WRL::ComPtr<ID3DBlob> blob = HLSLCompiler::LoadFromFile(filepath);
std::filesystem::path filename = filepath.filename();
std::string ext = filename.replace_extension().extension().string();
filename.replace_extension();
ext.erase(0, 1);
AddShader(filename.string(), ext, blob);
}
void DataSystem::AddModel(const std::filesystem::path& filepath, const std::filesystem::path& dir)
{
std::shared_ptr<Model> model;
std::shared_ptr<AnimModel> animmodel;
ModelLoader::LoadFromFile(filepath,dir, &model, &animmodel);
if (model)
{
Models[model->name] = model;
}
}
void DataSystem::AddShader(const std::string& name, const std::string& ext, const Microsoft::WRL::ComPtr<ID3DBlob>& blob)
{
if (ext == "vs")
{
VertexShader vs = VertexShader(name, blob);
vs.Compile();
VertexShaders[name] = vs;
}
else if (ext == "hs")
{
HullShader hs = HullShader(name, blob);
hs.Compile();
HullShaders[name] = hs;
}
else if (ext == "ds")
{
DomainShader ds = DomainShader(name, blob);
ds.Compile();
DomainShaders[name] = ds;
}
else if (ext == "gs")
{
GeometryShader gs = GeometryShader(name, blob);
gs.Compile();
GeometryShaders[name] = gs;
}
else if (ext == "ps")
{
PixelShader ps = PixelShader(name, blob);
ps.Compile();
PixelShaders[name] = ps;
}
else if (ext == "cs")
{
ComputeShader cs = ComputeShader(name, blob);
cs.Compile();
ComputeShaders[name] = cs;
}
else
{
WARN("Unrecognized shader extension \"" + ext + "\" for shader \"" + name + "\"");
}
}
void DataSystem::RemoveShaders()
{
VertexShaders.clear();
HullShaders.clear();
DomainShaders.clear();
GeometryShaders.clear();
PixelShaders.clear();
ComputeShaders.clear();
}
| 20.909722 | 121 | 0.663235 |
281c3004a31fa9001737787f07cd19fc22402ae9 | 4,920 | cpp | C++ | Other OJs/SPOJ/MSUBSTR.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2019-11-12T15:08:16.000Z | 2019-11-12T15:08:16.000Z | Other OJs/SPOJ/MSUBSTR.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | null | null | null | Other OJs/SPOJ/MSUBSTR.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2021-05-05T01:16:28.000Z | 2021-05-05T01:16:28.000Z | #include <bits/stdc++.h>
using namespace std;
#define TemplateVersion "3.4.1"
// Useful Marcos
//====================START=====================
// Compile use C++11 and above
#ifdef LOCAL
#define debug(args...) \
{ \
string _s = #args; \
replace(_s.begin(), _s.end(), ',', ' '); \
stringstream _ss(_s); \
istream_iterator<string> _it(_ss); \
err(_it, args); \
}
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
#define MSG cout << "Finished" << endl
#else
#define debug(args...)
#define MSG
#endif
#if __cplusplus >= 201703L
template <typename... Args>
void readln(Args&... args) {
((cin >> args), ...);
}
template <typename... Args>
void writeln(Args... args) {
((cout << args << " "), ...);
cout << endl;
}
#elif __cplusplus >= 201103L
void readln() {}
template <typename T, typename... Args>
void readln(T& a, Args&... args) {
cin >> a;
readln(args...);
}
void writeln() { cout << endl; }
template <typename T, typename... Args>
void writeln(T a, Args... args) {
cout << a << " ";
writeln(args...);
}
#endif
#if __cplusplus >= 201103L
#define FOR(_i, _begin, _end) for (auto _i = _begin; _i < _end; _i++)
#define FORR(_i, _begin, _end) for (auto _i = _begin; _i > _end; _i--)
#else
#define FOR(_i, _begin, _end) for (int _i = (int)_begin; _i < (int)_end; _i++)
#define FORR(_i, _begin, _end) for (int _i = (int)_begin; _i > (int)_end; _i--)
#define nullptr NULL
#endif
#if __cplusplus >= 201103L
#define VIS(_kind, _name, _size) \
vector<_kind> _name(_size); \
for (auto& i : _name) cin >> i;
#else
#define VIS(_kind, _name, _size) \
vector<_kind> _name; \
_name.resize(_size); \
for (int i = 0; i < _size; i++) cin >> _name[i];
#endif
// alias
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define all(x) (x).begin(), (x).end()
#define tcase() \
int T; \
cin >> T; \
FOR(kase, 1, T + 1)
// Swap max/min
template <typename T>
bool smax(T& a, const T& b) {
if (a > b) return false;
a = b;
return true;
}
template <typename T>
bool smin(T& a, const T& b) {
if (a < b) return false;
a = b;
return true;
}
// ceil divide
template <typename T>
T cd(T a, T b) {
return (a + b - 1) / b;
}
// min exchange
template <typename T>
bool se(T& a, T& b) {
if (a < b) return false;
swap(a, b);
return true;
}
// A better MAX choice
const int INF = 0x3f3f3f3f;
const long long INFLL = 0x3f3f3f3f3f3f3f3fLL;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef set<int> si;
typedef vector<string> cb;
//====================END=====================
// Constants here
const int CHAR_SIZE = 26;
const char CHAR_START = 'a';
const int SIZE = 1e5 + 10; // String size
map<int, int, greater<int>> m;
struct PAM {
int node[SIZE][CHAR_SIZE];
int fail[SIZE];
int cnt[SIZE]; // distinct palindromes at node i
int num[SIZE]; // the number of palindroms which end with the end of longest
// palindrome at node i
int len[SIZE]; // length of the palindrome at node i
int s[SIZE];
int last; // the longest palindrome's node
int n; // count of character
int p; // count of nodes
int new_node(int le) {
for (int i = 0; i < CHAR_SIZE; i++) node[p][i] = 0;
cnt[p] = 0;
num[p] = 0;
len[p] = le;
return p++;
}
void init() {
p = 0;
new_node(0);
new_node(-1);
last = n = 0;
s[0] = -1;
fail[0] = 1;
}
int get_fail(int x) {
while (s[n - len[x] - 1] != s[n]) x = fail[x];
return x;
}
void add(char ch) {
int c = ch - CHAR_START;
s[++n] = c;
int cur = get_fail(last);
if (!node[cur][c]) {
int now = new_node(len[cur] + 2);
fail[now] = node[get_fail(fail[cur])][c];
node[cur][c] = now;
num[now] = num[fail[now]] + 1;
}
last = node[cur][c];
cnt[last]++;
}
void get_cnt() {
for (int i = p - 1; i >= 0; i--) {
cnt[fail[i]] += cnt[i];
m[len[i]] += cnt[i];
}
}
int get_num() { return num[n]; }
} pam;
// Pre-Build Function
inline void build() {}
// Actual Solver
inline void solve() {
tcase() {
pam.init();
m.clear();
string s;
cin >> s;
for (auto i : s) pam.add(i);
pam.get_cnt();
writeln(m.begin()->first, m.begin()->second);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
#ifdef LOCAL
clock_t _begin = clock();
#endif
build();
solve();
#ifdef LOCAL
cerr << "Time elapsed: " << (double)(clock() - _begin) * 1000 / CLOCKS_PER_SEC << "ms." << endl;
#endif
return 0;
} | 22.568807 | 98 | 0.552439 |
281c5f3d12b95787c73b64e42ee2bd5cf0a020d3 | 1,376 | cc | C++ | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 2 | 2019-09-30T09:22:06.000Z | 2019-09-30T14:40:11.000Z | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 8 | 2019-09-05T05:18:45.000Z | 2021-07-11T11:45:30.000Z | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 3 | 2020-05-25T09:49:25.000Z | 2020-06-29T18:34:47.000Z | #include "ft_ee_ua_size_op.h"
Napi::Object FtEeUaSize::Init(Napi::Env env, Napi::Object exports)
{
exports.Set("eeUaSizeSync", Napi::Function::New(env, FtEeUaSize::InvokeSync));
exports.Set("eeUaSize", Napi::Function::New(env, FtEeUaSize::Invoke));
return exports;
}
Napi::Object FtEeUaSize::InvokeSync(const Napi::CallbackInfo &info)
{
FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data();
DWORD uaSize;
FT_STATUS ftStatus = FT_EE_UASize(ftHandle, &uaSize);
return CreateResult(info.Env(), ftStatus, uaSize);
}
Napi::Promise FtEeUaSize::Invoke(const Napi::CallbackInfo &info)
{
FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data();
auto *operation = new FtEeUaSize(info.Env(), ftHandle);
operation->Queue();
return operation->Promise();
}
FtEeUaSize::FtEeUaSize(Napi::Env env, FT_HANDLE ftHandle)
: FtBaseOp(env),
ftHandle(ftHandle)
{
}
void FtEeUaSize::Execute()
{
ftStatus = FT_EE_UASize(ftHandle, &uaSize);
}
void FtEeUaSize::OnOK()
{
Napi::HandleScope scope(Env());
deferred.Resolve(CreateResult(Env(), ftStatus, uaSize));
}
Napi::Object FtEeUaSize::CreateResult(Napi::Env env, FT_STATUS ftStatus, DWORD uaSize)
{
Napi::Object result = Napi::Object::New(env);
result.Set("ftStatus", ftStatus);
result.Set("uaSize", uaSize);
return result;
} | 28.081633 | 86 | 0.695494 |
281cef6cd6f9e35263ab4bd3be968217ab81112d | 5,880 | cpp | C++ | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-14T20:59:58.000Z | 2021-12-16T16:41:31.000Z | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 2 | 2021-11-29T14:41:23.000Z | 2021-11-30T13:13:51.000Z | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-21T12:41:55.000Z | 2021-12-22T16:17:52.000Z | /*
* Copyright (c) 2009-2011 Hazard (hazard_x@gmx.net / twitter.com/HazardX)
*
* 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 "stdafx.h"
#include "NetThread.h"
#include "ScriptThread.h"
#include "RemoteScriptDomain.h"
#include "Script.h"
namespace GTA {
#ifdef USE_NETTHREAD
ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType) {
#else
ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType)
:IngameThread(true) {
#endif
//SetName("CustomFiberThread");
//GTA::NetHook::LoadScripts();
this->domain = domain;
this->scriptFile = scriptFile;
this->scriptType = scriptType;
}
//ScriptThread::~ScriptThread() {
// this->!ScriptThread();
//}
//ScriptThread::!ScriptThread() {
// if isNotNULL(scriptType) {
// LogFin(scriptType->ToString());
// //delete scriptType;
// scriptType = nullptr;
// }
// if isNotNULL(script) {
// //delete script;
// script = nullptr;
// }
//}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
bool ScriptThread::LoadScriptNow() {
//if (!Game::isModdingAllowed) {
// GTA::NetHook::Log(String::Concat( "Rejected start of script '", scriptType->FullName, "' in this multiplayer gamemode!" ));
// //GTA::NetHook::DisplayText(String::Concat( "DO NOT USE MODS/SCRIPTS IN RANKED MULTIPLAYER GAMES!" ), 10000 );
// //Abort();
// return false ;
//}
currentlyLoading = this;
if (VERBOSE) GTA::NetHook::Log(String::Concat( "Constructing script '", scriptType->FullName, "'..." ));
try {
if isNULL(scriptType) return false;
// IMPORTANT: Constructor runs here already
System::Object^ o = System::Activator::CreateInstance(scriptType);
if isNULL(o) return false;
script = static_cast<GTA::Script^>(o); //domain->LoadScript(scriptType);
if isNotNULL(script) {
script->Initialize(this);
//if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...successfully constructed script '", script->Name, "'!" ));
return true;
} else {
//bError = true;
return false;
}
} catch (System::InvalidOperationException^) {
//Object::ReferenceEquals(ex,nullptr); // just a dummy to get rid of the warning
//bError = true;
return false;
} catch (System::Reflection::TargetInvocationException^ ex) {
try {
if ( isNULL(ex) || isNULL(ex->InnerException) ) {
throw gcnew Exception();
return false;
}
throw ex->InnerException;
//} catch (System::MissingMethodException^ ex) {
// if (ex->ToString()->Contains("GTA.value.ScriptSettings GTA.Script.get_Settings()")) continue;
} catchErrors ("Error in constructor of script '"+scriptType->FullName+"'", )
return false;
} catchErrors ("Error during construction of script '"+scriptType->FullName+"'", ) //bError = true;
return false;
}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
void ScriptThread::OnStartup() {
bool bError = false;
//lock(syncroot) {
bError = !LoadScriptNow();
//bError = isNULL(script);
if (!bError) {
//if (!GTA::NetHook::RunScript(script)) bError = true;
try {
//if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...starting script '", script->Name, "'..." ));
domain->SetCurrentScript(script); // we have to set it here again, because script was still Nothing at startup
script->DoStartup();
domain->AddRunningScript(script);
GTA::NetHook::Log(String::Concat( " ...successfully started script '", script->Name, "'!" ));
} catchScriptErrors (script, "Startup", bError = true; )
}
if (bError) {
GTA::NetHook::DisplayText( String::Concat("Error in script '", scriptType->FullName, "'!"), 5000 );
if isNotNULL(script) script->myThread = nullptr;
Abort();
}
//} unlock(syncroot);
//script = GTA::NetHook::RunScript(scriptType);
//if(script != nullptr) {
// script->myThread = this;
//} else {
// Abort();
//}
}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
void ScriptThread::OnTick() {
//lock(syncroot) {
if ( isNULL(script) || (!script->isRunning) ) {
//Abort();
return;
}
try {
script->DoTick();
} catch (System::Threading::ThreadAbortException^ taex) {
throw taex;
} catchScriptErrors (script, "Tick", if isNotNULL(script) script->Abort(); )
//} unlock(syncroot);
}
void ScriptThread::OnThreadContinue() {
domain->SetCurrentScript(script);
}
void ScriptThread::OnThreadHalt() {
//RemoteScriptDomain::Instance->RaiseEventInLocalScriptDomain("ThreadHalt",nullptr);
domain->SetCurrentScript(nullptr);
}
void ScriptThread::OnEnd() {
if isNotNULL(script) {
if (VERBOSE) NetHook::Log("Script ended: " + script->Name);
domain->RemoveRunningScript(script);
}
}
} | 31.44385 | 129 | 0.680442 |
281fc5b4ad418631e464c9fb6bb424d4a7a74785 | 3,589 | cpp | C++ | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2020-10-28T06:11:30.000Z | 2020-10-28T06:11:30.000Z | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2019-05-05T11:10:31.000Z | 2019-05-05T11:10:31.000Z | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 4 | 2019-05-03T18:43:19.000Z | 2020-12-17T04:06:59.000Z | /*
* Authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2008-2018
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this 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 <gecode/search.hh>
using namespace Gecode;
class SimpleSearchTracer : public SearchTracer {
protected:
static const char* t2s(EngineType et) {
switch (et) {
case EngineType::DFS: return "DFS";
case EngineType::BAB: return "BAB";
case EngineType::LDS: return "LDS";
case EngineType::RBS: return "RBS";
case EngineType::PBS: return "PBS";
case EngineType::AOE: return "AOE";
}
}
public:
SimpleSearchTracer(void) {}
// init
virtual void init(void) {
std::cout << "trace<Search>::init()" << std::endl;
for (unsigned int e=0U; e<engines(); e++) {
std::cout << "\t" << e << ": "
<< t2s(engine(e).type());
if (engine(e).meta()) {
// init for meta engines
std::cout << ", engines: {";
for (unsigned int i=engine(e).efst(); i<engine(e).elst(); i++) {
std::cout << i; if (i+1 < engine(e).elst()) std::cout << ",";
}
} else {
// init for engines
std::cout << ", workers: {";
for (unsigned int i=engine(e).wfst(); i<engine(e).wlst(); i++) {
std::cout << i; if (i+1 < engine(e).wlst()) std::cout << ",";
}
}
std::cout << "}" << std::endl;
}
}
// node
virtual void node(const EdgeInfo& ei, const NodeInfo& ni) {
std::cout << "trace<Search>::node(";
switch (ni.type()) {
case NodeType::FAILED:
std::cout << "FAILED";
break;
case NodeType::SOLVED:
std::cout << "SOLVED";
break;
case NodeType::BRANCH:
std::cout << "BRANCH(" << ni.choice().alternatives() << ")";
break;
}
std::cout << ',' << "w:" << ni.wid() << ','
<< "n:" << ni.nid() << ')';
if (ei) {
if (ei.wid() != ni.wid())
std::cout << " [stolen from w:" << ei.wid() << "]";
std::cout << std::endl << '\t' << ei.string()
<< std::endl;
} else {
std::cout << std::endl;
}
}
// round
virtual void round(unsigned int eid) {
std::cout << "trace<Search>::round(e:" << eid << ")" << std::endl;
}
// skip
virtual void skip(const EdgeInfo& ei) {
std::cout << "trace<Search>Search::skip(w:" << ei.wid()
<< ",n:" << ei.nid()
<< ",a:" << ei.alternative() << ")" << std::endl;
}
// done
virtual void done(void) {
std::cout << "trace<Search>::done()" << std::endl;
}
virtual ~SimpleSearchTracer(void) {}
};
| 33.231481 | 77 | 0.574255 |
2823be59b9693fbcbfdda47c7ba0ad5356c647bf | 3,005 | cpp | C++ | 05_Hello_Amazon/src/main.cpp | RawMatter/IoT_Message_Box_Workshop_Solutions | a6e1690e5476b2b9117f769e7ccd92a7462c436c | [
"Unlicense"
] | null | null | null | 05_Hello_Amazon/src/main.cpp | RawMatter/IoT_Message_Box_Workshop_Solutions | a6e1690e5476b2b9117f769e7ccd92a7462c436c | [
"Unlicense"
] | null | null | null | 05_Hello_Amazon/src/main.cpp | RawMatter/IoT_Message_Box_Workshop_Solutions | a6e1690e5476b2b9117f769e7ccd92a7462c436c | [
"Unlicense"
] | null | null | null | #include <Arduino.h>
#include <TFT_eSPI.h>
#include <WiFi.h>
// Add the secure WiFi and MQTT libraries
#include <WiFiClientSecure.h>
#include <MQTTClient.h>
#include <ArduinoJson.h>
// WiFi Parameters are define in the "secrets" header file
#include "secrets.h"
// Button definitions
const char BUTTON_0 = 0;
const char BUTTON_1 = 35;
// display library instance
TFT_eSPI tft = TFT_eSPI();
char buff[512];
// Secure WiFi and MQTT client instances
WiFiClientSecure net = WiFiClientSecure();
MQTTClient client = MQTTClient(1024);
void setup() {
Serial.begin(115200);
Serial.println("Hello World");
pinMode(BUTTON_0, INPUT_PULLUP);
pinMode(BUTTON_1, INPUT_PULLUP);
Serial.println("Initialise LCD");
tft.init();
tft.setRotation(3);
tft.fillScreen(TFT_WHITE);
tft.setCursor(0, 0, 2);
tft.setTextSize(2);
tft.setTextColor(TFT_RED);
tft.println(" Hello Amazon ");
Serial.println("Connecting to WiFi");
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(200);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi Connected!");
tft.print(WiFi.localIP());
Serial.println("Connecting to AWS");
// Configure WiFiClientSecure to use the AWS IoT device credentials
net.setCACert(AWS_CERT_CA);
net.setCertificate(AWS_CERT_CRT);
net.setPrivateKey(AWS_CERT_PRIVATE);
// Start the MQTT client
client.begin(AWS_IOT_ENDPOINT, 8883, net);
while (!client.connect(CLIENT_NAME)) {
Serial.print(".");
delay(100);
}
if(!client.connected()){
Serial.println("AWS IoT Timeout! :(");
while(1);
}
else{
Serial.println("AWS IoT Connected! :D");
}
sleep(1);
}
int counter = 0;
// This is the pubslish subroutine that will simplify sending messages to the AWS Broker
// It will generate an JSON string formatted
void publish(int count, String action ){
// Define a new ArduinoJSON document object
// Arguably not the most efficient use of memory resources
// but a very efficient use of developer time!
StaticJsonDocument<200> doc;
// Add records to the JSON Doc
doc["count"] = count;
doc["action"] = action;
// Create a char buffer
char jsonBuffer[512];
// Generate the JSON object and store it in the char buffer
serializeJson(doc, jsonBuffer);
Serial.print("JSON Object: ");
Serial.println(jsonBuffer);
client.publish("counter", jsonBuffer);
// We could add more granularity and filtering options to our topics by including the action
// String topic = "counter/" + action;
// Serial.println(topic);
// client.publish(topic, jsonBuffer);
}
void loop() {
Serial.println("loop ");
if(digitalRead(BUTTON_0) == false){
Serial.println("Button 0 is pressed");
counter++;
publish(counter, "increment");
}
if (digitalRead(BUTTON_1) == false){
Serial.println("Button 1 is pressed");
counter--;
publish(counter, "decrement");
}
Serial.print("counter value: ");
Serial.println(counter);
sleep(1);
} | 22.593985 | 94 | 0.686855 |
28257fdbab3a888d0240cdd2ddad2ef460f5574a | 8,838 | cpp | C++ | binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2015-02-14T15:09:54.000Z | 2021-11-10T15:09:45.000Z | binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | binding-cpp/runtime/src/test/transport/EtchMessagizerTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | 14 | 2015-04-20T10:35:00.000Z | 2021-11-10T15:09:35.000Z | /* $Id$
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "serialization/EtchDefaultValueFactory.h"
#include "serialization/EtchBinaryTaggedData.h"
#include "serialization/EtchBinaryTaggedDataInput.h"
#include "serialization/EtchValidatorShort.h"
#include "transport/EtchMessagizer.h"
#include "transport/EtchTcpConnection.h"
#include "transport/EtchPacketizer.h"
#include "transport/EtchSessionListener.h"
#include "transport/EtchTcpListener.h"
class MockListener11 : public virtual EtchSessionListener<EtchSocket> {
public:
MockListener11(EtchTransport<EtchSessionListener<EtchSocket> >* transport)
: mTransport(transport) {
if(mTransport != NULL) {
mTransport->setSession(this);
}
}
virtual ~MockListener11() {
if(mTransport != NULL) {
delete mTransport;
}
}
//This method is called
status_t sessionAccepted(EtchSocket* connection) {
delete connection;
return ETCH_OK;
}
MOCK_METHOD2(sessionQuery, status_t(capu::SmartPointer<EtchObject> query, capu::SmartPointer<EtchObject> &result));
MOCK_METHOD2(sessionControl, status_t(capu::SmartPointer<EtchObject> control, capu::SmartPointer<EtchObject> value));
status_t sessionNotify(capu::SmartPointer<EtchObject> event) {
return ETCH_OK;
}
private:
EtchTransport<EtchSessionListener<EtchSocket> >* mTransport;
};
class MockMailboxManager : public EtchSessionMessage {
public:
status_t sessionMessage(capu::SmartPointer<EtchWho> receipent, capu::SmartPointer<EtchMessage> buf) {
EXPECT_TRUE(buf->count() == 1);
buf->clear();
return ETCH_OK;
}
MOCK_METHOD2(sessionQuery, status_t(capu::SmartPointer<EtchObject> query, capu::SmartPointer<EtchObject> &result));
MOCK_METHOD2(sessionControl, status_t(capu::SmartPointer<EtchObject> control, capu::SmartPointer<EtchObject> value));
status_t sessionNotify(capu::SmartPointer<EtchObject> event) {
return ETCH_OK;
}
};
class EtchMessagizerTest
: public ::testing::Test {
protected:
virtual void SetUp() {
mRuntime = new EtchRuntime();
mRuntime->start();
}
virtual void TearDown() {
mRuntime->shutdown();
delete mRuntime;
mRuntime = NULL;
}
EtchRuntime* mRuntime;
};
TEST_F(EtchMessagizerTest, constructorTest) {
EtchTypeMap types;
EtchClass2TypeMap class2type;
EtchDefaultValueFactory * factory;
EtchDefaultValueFactory::Init(mRuntime, &types, &class2type);
EtchString uri("tcp://127.0.0.1:4001");
factory = new EtchDefaultValueFactory(uri, &types, &class2type);
//created value factory
EtchURL u("tcp://127.0.0.1:4001");
EtchResources r;
EtchObject *out;
r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out);
EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u);
EtchTransportPacket* pac = new EtchPacketizer(mRuntime, conn, &u);
EtchSessionPacket* mes = new EtchMessagizer(mRuntime, pac, &u, &r);
//Delete created stack
delete conn;
delete mes;
delete pac;
delete factory;
types.clear();
}
TEST_F(EtchMessagizerTest, TransportControlTest) {
EtchTypeMap types;
EtchClass2TypeMap class2type;
EtchDefaultValueFactory * factory;
MockMailboxManager manager;
EtchDefaultValueFactory::Init(mRuntime, &types, &class2type);
EtchString uri("tcp://127.0.0.1:4001");
factory = new EtchDefaultValueFactory(uri, &types, &class2type);
//created value factory
EtchURL u("tcp://127.0.0.1:4001");
EtchResources r;
EtchObject *out;
r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out);
EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u);
EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u);
EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r);
mess->setSession(&manager);
EtchTcpListener* transport = new EtchTcpListener(mRuntime, &u);
EtchSessionListener<EtchSocket>* mSessionListener = new MockListener11(transport);
transport->transportControl(new EtchString(EtchTcpListener::START_AND_WAIT_UP()), new EtchInt32(1000));
mess->transportControl(new EtchString(EtchPacketizer::START_AND_WAIT_UP()), new EtchInt32(1000));
//test transport commands
mess->transportControl(new EtchString(EtchPacketizer::STOP_AND_WAIT_DOWN()), new EtchInt32(1000));
transport->transportControl(new EtchString(EtchTcpListener::STOP_AND_WAIT_DOWN()), new EtchInt32(1000));
delete conn;
delete mSessionListener;
delete pac;
delete mess;
delete factory;
types.clear();
}
TEST_F(EtchMessagizerTest, TransportMessageTest) {
EtchTypeMap types;
EtchClass2TypeMap class2type;
EtchDefaultValueFactory * factory;
MockMailboxManager manager;
EtchDefaultValueFactory::Init(mRuntime, &types, &class2type);
EtchString uri("tcp://127.0.0.1:4001");
factory = new EtchDefaultValueFactory(uri, &types, &class2type);
//default value factory
EtchURL u("tcp://127.0.0.1:4001");
EtchResources r;
EtchObject *out;
//add to the resource
r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out);
EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u);
EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u);
EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r);
mess->setSession(&manager);
//creation of example message which will be serialized
EtchType *mt_foo = NULL;
EtchField mf_x("x");
EtchString str("foo");
factory->getType(str, mt_foo);
capu::SmartPointer<EtchValidator> v;
EtchValidatorShort::Get(mRuntime, 0, v);
mt_foo->putValidator(mf_x, v);
capu::SmartPointer<EtchShort> data = new EtchShort(10000);
capu::SmartPointer<EtchMessage> msg = new EtchMessage(mt_foo, factory);
msg->put(mf_x, data);
EXPECT_TRUE(mess->transportMessage(NULL, msg) == ETCH_ERROR);
delete conn;
delete mess;
delete pac;
delete factory;
types.clear();
}
TEST_F(EtchMessagizerTest, SessionDataTest) {
//creation of an example message to compare the deserialized messageMyValueFactory vf("tcp:");
EtchTypeMap types;
EtchClass2TypeMap class2type;
EtchString name1("a");
EtchString name2("b");
EtchType *mt_foo = new EtchType(1, name1);
EtchField mf_x(2, name2);
capu::SmartPointer<EtchValidator> v;
EtchValidatorShort::Get(mRuntime, 0, v);
mt_foo->putValidator(mf_x, v);
types.add(mt_foo);
capu::SmartPointer<EtchShort> data = new EtchShort(10000);
//default value factory
EtchDefaultValueFactory * factory;
EtchDefaultValueFactory::Init(mRuntime, &types, &class2type);
EtchString uri("tcp://127.0.0.1:4001");
factory = new EtchDefaultValueFactory(uri, &types, &class2type);
capu::SmartPointer<EtchMessage> msg = new EtchMessage(mt_foo, factory);
msg->put(mf_x, data);
EtchURL u(uri);
EtchResources r;
EtchObject *out;
//add the value factory to the resources
r.put(EtchTransport<EtchSessionMessage>::VALUE_FACTORY(), factory, out);
//create stack
EtchTransportData* conn = new EtchTcpConnection(mRuntime, NULL, &u);
EtchPacketizer* pac = new EtchPacketizer(mRuntime, conn, &u);
EtchMessagizer* mess = new EtchMessagizer(mRuntime, pac, &u, &r);
capu::SmartPointer<EtchFlexBuffer> buffer = new EtchFlexBuffer();
//A packet is created
capu::int8_t byte_pos[] = {3, 1, 1, 2, -123, 39, 16, -127};
buffer->setByteRepresentation(ETCH_BIG_ENDIAN);
buffer->put((capu::int8_t *)"_header_", pac->getHeaderSize());
buffer->put((capu::int8_t *)byte_pos, 8);
buffer->setIndex(0);
capu::int32_t pktsize = buffer->getLength() - pac->getHeaderSize();
buffer->put((capu::int8_t *) & pac->SIG, sizeof (capu::int32_t));
buffer->put((capu::int8_t *) & pktsize, sizeof (capu::int32_t));
buffer->setIndex(pac->getHeaderSize());
EXPECT_TRUE(buffer->getLength() == 16);
//Simulate call with fake package
EtchSessionMessage* mMailboxManager = new MockMailboxManager();
mess->setSession(mMailboxManager);
EXPECT_TRUE(mess->sessionPacket(NULL, buffer) == ETCH_OK);
mess->setSession(NULL);
types.clear();
delete conn;
delete mMailboxManager;
delete pac;
delete mess;
delete factory;
}
| 34.123552 | 119 | 0.739194 |
2828538a14b2a0bbd6583b6dadb46893cfd40c07 | 2,177 | cc | C++ | components/spellcheck/renderer/platform_spelling_engine.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/spellcheck/renderer/platform_spelling_engine.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/spellcheck/renderer/platform_spelling_engine.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/spellcheck/renderer/platform_spelling_engine.h"
#include "content/public/renderer/render_thread.h"
#include "services/service_manager/public/cpp/local_interface_provider.h"
using content::RenderThread;
SpellingEngine* CreateNativeSpellingEngine(
service_manager::LocalInterfaceProvider* embedder_provider) {
DCHECK(embedder_provider);
return new PlatformSpellingEngine(embedder_provider);
}
PlatformSpellingEngine::PlatformSpellingEngine(
service_manager::LocalInterfaceProvider* embedder_provider)
: embedder_provider_(embedder_provider) {}
PlatformSpellingEngine::~PlatformSpellingEngine() = default;
spellcheck::mojom::SpellCheckHost&
PlatformSpellingEngine::GetOrBindSpellCheckHost() {
if (spell_check_host_)
return *spell_check_host_;
embedder_provider_->GetInterface(&spell_check_host_);
return *spell_check_host_;
}
void PlatformSpellingEngine::Init(base::File bdict_file) {
DCHECK(!bdict_file.IsValid());
}
bool PlatformSpellingEngine::InitializeIfNeeded() {
return false;
}
bool PlatformSpellingEngine::IsEnabled() {
return true;
}
// Synchronously query against the platform's spellchecker.
// TODO(groby): We might want async support here, too. Ideally,
// all engines share a similar path for async requests.
bool PlatformSpellingEngine::CheckSpelling(const base::string16& word_to_check,
int tag) {
bool word_correct = false;
GetOrBindSpellCheckHost().CheckSpelling(word_to_check, tag, &word_correct);
return word_correct;
}
// Synchronously query against the platform's spellchecker.
// TODO(groby): We might want async support here, too. Ideally,
// all engines share a similar path for async requests.
void PlatformSpellingEngine::FillSuggestionList(
const base::string16& wrong_word,
std::vector<base::string16>* optional_suggestions) {
GetOrBindSpellCheckHost().FillSuggestionList(wrong_word,
optional_suggestions);
}
| 34.015625 | 79 | 0.762058 |
28286fc38f45510bdb7d3e72f057aa401cd1e532 | 8,781 | cpp | C++ | wrap/csllbc/native/src/comm/_Service.cpp | shakeumm/llbc | 5aaf6f83eedafde87d52adf44b7548e85ad4a9d1 | [
"MIT"
] | 5 | 2021-10-31T17:12:45.000Z | 2022-01-10T11:10:27.000Z | wrap/csllbc/native/src/comm/_Service.cpp | shakeumm/llbc | 5aaf6f83eedafde87d52adf44b7548e85ad4a9d1 | [
"MIT"
] | 1 | 2019-09-04T12:23:37.000Z | 2019-09-04T12:23:37.000Z | wrap/csllbc/native/src/comm/_Service.cpp | ericyonng/llbc | a7fd1193db03b8ad34879441b09914adec8a62e6 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// 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 "csllbc/common/Export.h"
#include "csllbc/comm/csCoder.h"
#include "csllbc/comm/csFacade.h"
#include "csllbc/comm/csService.h"
#include "csllbc/comm/_Service.h"
LLBC_BEGIN_C_DECL
csllbc_Service *csllbc_Service_Create(int svcType,
const char *svcName,
bool fullStack,
csllbc_Delegates::Deleg_Service_EncodePacket encodeDeleg,
csllbc_Delegates::Deleg_Service_DecodePacket decodeDeleg,
csllbc_Delegates::Deleg_Service_PacketHandler handlerDeleg,
csllbc_Delegates::Deleg_Service_PacketPreHandler preHandlerDeleg,
csllbc_Delegates::Deleg_Service_PacketUnifyPreHandler unifyPreHandlerDeleg,
csllbc_Delegates::Deleg_Service_NativeCouldNotFoundDecoderReport notFoundDecoderDeleg)
{
if (svcType != static_cast<int>(LLBC_IService::Raw) &&
svcType != static_cast<int>(LLBC_IService::Normal))
{
LLBC_SetLastError(LLBC_ERROR_ARG);
return NULL;
}
return LLBC_New9(csllbc_Service,
static_cast<csllbc_Service::Type>(svcType),
svcName,
fullStack != 0,
encodeDeleg,
decodeDeleg,
handlerDeleg,
preHandlerDeleg,
unifyPreHandlerDeleg,
notFoundDecoderDeleg);
}
void csllbc_Service_Delete(csllbc_Service *svc)
{
LLBC_XDelete(svc);
}
int csllbc_Service_GetType(csllbc_Service *svc)
{
return static_cast<int>(svc->GetType());
}
int csllbc_Service_GetId(csllbc_Service *svc)
{
return svc->GetId();
}
int csllbc_Service_IsFullStack(csllbc_Service *svc)
{
return svc->IsFullStack() ? 1 : 0;
}
int csllbc_Service_GetDriveMode(csllbc_Service *svc)
{
return static_cast<int>(svc->GetDriveMode());
}
int csllbc_Service_SetDriveMode(csllbc_Service *svc, int driveMode)
{
return svc->SetDriveMode(static_cast<LLBC_IService::DriveMode>(driveMode));
}
int csllbc_Service_Start(csllbc_Service *svc, int pollerCount)
{
return svc->Start(pollerCount);
}
void csllbc_Service_Stop(csllbc_Service *svc)
{
svc->Stop();
}
int csllbc_Service_IsStarted(csllbc_Service *svc)
{
return svc->IsStarted() ? 1 : 0;
}
int csllbc_Service_GetFPS(csllbc_Service *svc)
{
return svc->GetFPS();
}
int csllbc_Service_SetFPS(csllbc_Service *svc, int fps)
{
return svc->SetFPS(fps);
}
int csllbc_Service_GetFrameInterval(csllbc_Service *svc)
{
return svc->GetFrameInterval();
}
int csllbc_Service_Listen(csllbc_Service *svc, const char *ip, int port)
{
return svc->Listen(ip, port);
}
int csllbc_Service_Connect(csllbc_Service *svc, const char *ip, int port)
{
return svc->Connect(ip, port);
}
int csllbc_Service_AsyncConn(csllbc_Service *svc, const char *ip, int port)
{
return svc->AsyncConn(ip, port);
}
int csllbc_Service_RemoveSession(csllbc_Service *svc, int sessionId, const char *reason, int reasonLength)
{
char *nativeReason;
if (reasonLength == 0)
{
nativeReason = NULL;
}
else
{
nativeReason = LLBC_Malloc(char, reasonLength + 1);
memcpy(nativeReason, reason, reasonLength);
nativeReason[reasonLength] = '\0';
}
const int ret = svc->RemoveSession(sessionId, nativeReason);
LLBC_XFree(nativeReason);
return ret;
}
int csllbc_Service_IsSessionValidate(csllbc_Service *svc, int sessionId)
{
return svc->IsSessionValidate(sessionId) ? 1 : 0;
}
int csllbc_Service_SendBytes(csllbc_Service *svc,
int sessionId,
int opcode,
const void *data,
int dataLen,
int status)
{
return svc->Send(sessionId, opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_SendPacket(csllbc_Service *svc,
int sessionId,
int opcode,
sint64 packetId,
int status)
{
csllbc_Coder *coder = LLBC_New(csllbc_Coder);
coder->SetEncodeInfo(packetId, svc->GetEncodePacketDeleg());
if (svc->Send(sessionId, opcode, coder, status) != LLBC_OK)
{
LLBC_Delete(coder);
return LLBC_FAILED;
}
return LLBC_OK;
}
int csllbc_Service_Multicast(csllbc_Service *svc,
int *sessionIds,
int sessionIdCount,
int opcode,
const void *data,
int dataLen,
int status)
{
LLBC_SessionIdList sessionIdList(sessionIdCount);
for (int idx = 0; idx < sessionIdCount; ++idx)
sessionIdList.push_back(sessionIds[idx]);
LLBC_XFree(sessionIds);
return svc->Multicast(sessionIdList, opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_Broadcast(csllbc_Service *svc,
int opcode,
const void *data,
int dataLen,
int status)
{
return svc->Broadcast(opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_RegisterFacade(csllbc_Service *svc,
csllbc_Delegates::Deleg_Facade_OnInit initDeleg,
csllbc_Delegates::Deleg_Facade_OnDestroy destroyDeleg,
csllbc_Delegates::Deleg_Facade_OnStart startDeleg,
csllbc_Delegates::Deleg_Facade_OnStop stopDeleg,
csllbc_Delegates::Deleg_Facade_OnUpdate updateDeleg,
csllbc_Delegates::Deleg_Facade_OnIdle idleDeleg,
csllbc_Delegates::Deleg_Facade_OnSessionCreate sessionCreateDeleg,
csllbc_Delegates::Deleg_Facade_OnSessionDestroy sessionDestroyDeleg,
csllbc_Delegates::Deleg_Facade_OnAsyncConnResult asyncConnResultDeleg,
csllbc_Delegates::Deleg_Facade_OnProtoReport protoReportDeleg,
csllbc_Delegates::Deleg_Facade_OnUnHandledPacket unHandledPacketDeleg)
{
csllbc_Facade *facade = new csllbc_Facade(initDeleg, destroyDeleg,
startDeleg, stopDeleg,
updateDeleg, idleDeleg,
sessionCreateDeleg, sessionDestroyDeleg, asyncConnResultDeleg,
protoReportDeleg, unHandledPacketDeleg);
if (svc->RegisterFacade(facade) != LLBC_OK)
{
LLBC_Delete(facade);
return LLBC_FAILED;
}
return LLBC_OK;
}
int csllbc_Service_RegisterCoder(csllbc_Service *svc, int opcode)
{
return svc->RegisterCoder(opcode);
}
int csllbc_Service_Subscribe(csllbc_Service *svc, int opcode)
{
return svc->Subscribe(opcode);
}
int csllbc_Service_PreSubscribe(csllbc_Service *svc, int opcode)
{
return svc->PreSubscribe(opcode);
}
int csllbc_Service_UnifyPreSubscribe(csllbc_Service *svc)
{
return svc->UnifyPreSubscribe();
}
void csllbc_Service_OnSvc(csllbc_Service *svc, bool fullFrame)
{
svc->OnSvc(fullFrame);
}
LLBC_END_C_DECL
| 32.643123 | 124 | 0.623961 |
282c19a79fdd2e73cbab17a4ac5b4a42ea2f5aaf | 1,511 | cpp | C++ | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | 3 | 2021-03-31T01:39:25.000Z | 2021-05-04T10:02:35.000Z | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i <= n; i++)
#define FORR(i, m, n) for (int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v + n)
#define MAX 100000
#define inf 1000000007
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;
using Graph = vector<vector<int>>;
int main()
{
// cin高速化
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> ball(n + 1);
// 色名の管理
set<int> ctyp;
int x, c;
REP(i, n)
{
cin >> x >> c;
ball[c].push_back(x);
ctyp.insert(c);
}
// 色iまで回収し終えたあとに左・右端にいるスコアの最小値
// 左端にいる場合のスコア、右端にいる場合のスコア
ll lscore = 0, rscore = 0;
// 0色回収後の色
int lnew = 0, rnew = 0;
for (auto c : ctyp)
{
sort(ball[c].begin(), ball[c].end());
// 次の色の左端、右端の座標
int l = ball[c][0], r = ball[c][ball[c].size() - 1];
// lnew or rnewからrに移動して、rからlへ回収
ll lmi = min(lscore + abs(r - lnew), rscore + abs(r - rnew)) + abs(r - l);
// lnew or rnewからlに移動して、lからrへ回収
ll rmi = min(lscore + abs(l - lnew), rscore + abs(l - rnew)) + abs(r - l);
// 更新後のスコア
lscore = lmi;
rscore = rmi;
// 操作後の座標
lnew = l;
rnew = r;
}
// 原点へ戻る
cout << min(lscore + abs(lnew), rscore + abs(rnew)) << "\n";
return 0;
} | 26.051724 | 82 | 0.512244 |
282c401068b45c3be3e3878068c02abbf2ac662e | 5,002 | hpp | C++ | Zaimoni.STL/iterator_array_size.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 2 | 2019-11-23T12:35:49.000Z | 2022-02-10T08:27:54.000Z | Zaimoni.STL/iterator_array_size.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 8 | 2019-11-15T08:13:48.000Z | 2020-04-29T00:35:42.000Z | Zaimoni.STL/iterator_array_size.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | null | null | null | // iterator_array_size.hpp
#ifndef ITERATOR_ARRAY_SIZE_HPP
#define ITERATOR_ARRAY_SIZE_HPP 1
#include "Logging.h"
#include "iterator.on.hpp"
#include <iterator>
namespace zaimoni {
template<class T>
class iterator_array_size
{
public:
typedef typename T::difference_type difference_type; // these five aligned with container
typedef typename T::size_type size_type;
typedef typename T::value_type value_type;
typedef typename T::reference reference;
typedef typename T::pointer pointer;
typedef std::random_access_iterator_tag iterator_category;
private:
T* _src;
size_type _i;
bool can_dereference() const {return _src && _i < _src->size();}
public:
bool is_valid() const {return _src && _i <= _src->size();} // for post-condition testing
iterator_array_size(T* src = 0, size_type offset = 0) : _src(src),_i(offset) {};
ZAIMONI_DEFAULT_COPY_DESTROY_ASSIGN(iterator_array_size);
bool operator==(const iterator_array_size& rhs) const {return _src==rhs._src && _i==rhs._i;}
reference operator*() const {
assert(can_dereference());
return (*_src)[_i];
};
iterator_array_size& operator++() { // prefix
if (_src->size() > _i) _i++;
return *this;
};
iterator_array_size operator++(int) { // postfix
iterator_array_size ret(*this);
if (_src->size() > _i) _i++;
return ret;
};
// bidirectional
iterator_array_size& operator--() { // prefix
if (0 < _i) _i--;
return *this;
};
iterator_array_size operator--(int) { // postfix
iterator_array_size ret(*this);
if (0 < _i) _i--;
return ret;
};
// random access
iterator_array_size& operator+=(difference_type n) {
if (0<n) {
assert(_src.size()-_i >= n);
_i += n;
} else if (0>n) {
assert(_i >= -n);
_i += n;
}
return *this;
};
iterator_array_size& operator-=(difference_type n) {
if (0<n) {
assert(_i >= -n);
_i -= n;
} else if (0>n) {
assert(_src.size()-_i >= n);
_i -= n;
}
return *this;
};
difference_type operator-(const iterator_array_size& rhs) {
assert(_src==rhs._src);
return _i-rhs._i;
}
reference operator[](size_type n) const {
assert(_src->size()-_i >= n);
return _src[_i+n];
}
bool operator<(const iterator_array_size& rhs) const {
assert(_src==rhs._src);
return _i < rhs._i;
}
ZAIMONI_ITER_DECLARE(iterator_array_size)
};
template<class T>
class const_iterator_array_size
{
public:
typedef typename T::difference_type difference_type; // these five aligned with container
typedef typename T::size_type size_type;
typedef const typename T::value_type value_type;
typedef const typename T::reference reference;
typedef const typename T::pointer pointer;
typedef std::random_access_iterator_tag iterator_category;
private:
const T* _src;
size_type _i;
bool can_dereference() const {return _src && _i < _src->size();}
public:
bool is_valid() const {return _src && _i <= _src->size();} // for post-condition testing
const_iterator_array_size(const T* src = 0, size_type offset = 0) : _src(src),_i(offset) {};
ZAIMONI_DEFAULT_COPY_DESTROY_ASSIGN(const_iterator_array_size);
bool operator==(const const_iterator_array_size& rhs) const {return _src==rhs._src && _i==rhs._i;}
reference operator*() const {
assert(can_dereference());
return (*_src)[_i];
};
const_iterator_array_size& operator++() { // prefix
if (_src->size() > _i) _i++;
assert(is_valid());
return *this;
};
const_iterator_array_size operator++(int) { // postfix
const_iterator_array_size ret(*this);
if (_src->size() > _i) _i++;
assert(is_valid());
return ret;
};
// bidirectional
const_iterator_array_size& operator--() { // prefix
if (0 < _i) _i--;
assert(is_valid());
return *this;
};
const_iterator_array_size operator--(int) { // postfix
const_iterator_array_size ret(*this);
if (0 < _i) _i--;
assert(is_valid());
return ret;
};
const_iterator_array_size& operator+=(difference_type n) { // postfix
if (0<n) {
assert(_src.size()-_i >= n);
_i += n;
} else if (0>n) {
assert(_i >= -n);
_i += n;
}
assert(is_valid());
return *this;
};
const_iterator_array_size& operator-=(difference_type n) {
if (0<n) {
assert(_i >= -n);
_i -= n;
} else if (0>n) {
assert(_src.size()-_i >= n);
_i -= n;
}
assert(is_valid());
return *this;
};
difference_type operator-(const const_iterator_array_size& rhs) const {
assert(_src==rhs._src);
return _i-rhs._i;
}
reference operator[](size_type n) const { // random access
assert(_src->size()-_i >= n);
return _src[_i+n];
}
bool operator<(const const_iterator_array_size& rhs) const {
assert(_src==rhs._src);
return _i < rhs._i;
}
ZAIMONI_ITER_DECLARE(const_iterator_array_size)
};
} // namespace zaimoni
#undef ZAIMONI_ITER_DECLARE
#endif
| 24.885572 | 100 | 0.647341 |
282d1de720e5f1e4780992e97cf6ce995786aa92 | 62 | cpp | C++ | Src/Evora/Engine/game_state.cpp | medovina/Evora | 95e41e7b2d5c408d515a01a5649ddfaa211e9349 | [
"Apache-2.0"
] | 1 | 2020-11-25T20:53:36.000Z | 2020-11-25T20:53:36.000Z | Src/Evora/Engine/game_state.cpp | medovina/Evora | 95e41e7b2d5c408d515a01a5649ddfaa211e9349 | [
"Apache-2.0"
] | 16 | 2020-03-06T09:11:55.000Z | 2020-07-24T10:57:41.000Z | Src/Evora/Engine/game_state.cpp | medovina/Evora | 95e41e7b2d5c408d515a01a5649ddfaa211e9349 | [
"Apache-2.0"
] | 1 | 2020-01-18T13:11:38.000Z | 2020-01-18T13:11:38.000Z | #include "game_state.h"
game_state::~game_state() = default;
| 15.5 | 36 | 0.725806 |
28306a60542b3d1077c9f2f0a2c231c56e530088 | 443 | cpp | C++ | boost/join.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | 3 | 2017-12-07T04:29:36.000Z | 2022-01-11T10:58:14.000Z | boost/join.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | 14 | 2018-07-17T05:16:42.000Z | 2022-03-22T00:43:47.000Z | boost/join.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | null | null | null | // ysoftman
// boost join 사용하기
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string/join.hpp>
using namespace std;
int main()
{
cout << "boost join test" << endl;
vector<string> strVec;
strVec.push_back("Yoon");
strVec.push_back("Byoung");
strVec.push_back("Hoon");
string joined_string = boost::algorithm::join(strVec, ",\n");
cout << joined_string << endl;
return 0;
}
| 19.26087 | 65 | 0.654628 |
283206c28f3ee30b3afe64271cb1a35d04d539d4 | 1,525 | cpp | C++ | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | /*!
* \author Daniel Sundfeld
* \copyright MIT License
*/
#include "read_fasta.h"
#include <fstream>
#include <iostream>
#include <string>
#include "Sequences.h"
int read_fasta_file_core(const std::string &name)
{
std::ifstream file(name.c_str());
Sequences *sequences = Sequences::get_instance();
if (!file.is_open())
{
std::cout << "Can't open file " << name << std::endl;
return -1;
}
while (!file.eof())
{
std::string seq;
while (!file.eof())
{
std::string buf;
getline(file, buf);
if ((buf.length() <= 0) || (buf.at(0) == '>'))
break;
seq.append(buf);
}
if (!seq.empty())
sequences->set_seq(seq);
}
return 0;
}
/*!
* Read the \a name fasta file, loading it to the Sequences singleton.
* Fail if the number of sequences is non-null and not equal to \a limit
*/
int read_fasta_file(const std::string &name, const int &check)
{
try
{
int ret = read_fasta_file_core(name);
if (ret == 0 && check != 0 && Sequences::get_nseq() != check)
{
std::cerr << "Invalid fasta file: must have " << check << " sequences.\n";
return -1;
}
return ret;
}
catch (std::exception &e)
{
std::cerr << "Reading file fatal error: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown fatal error while reading file!\n";
}
return -1;
}
| 22.761194 | 86 | 0.523934 |
283245e594d24b971e8c22fbe2604a2550742e54 | 22,479 | cc | C++ | third_party/blink/renderer/modules/indexeddb/idb_database.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | third_party/blink/renderer/modules/indexeddb/idb_database.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/modules/indexeddb/idb_database.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/modules/indexeddb/idb_database.h"
#include <limits>
#include <memory>
#include <utility>
#include "base/atomic_sequence_num.h"
#include "base/optional.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/indexed_db_names.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_any.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_event_dispatcher.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_index.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key_path.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_tracing.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h"
#include "third_party/blink/renderer/modules/indexeddb/web_idb_database_callbacks.h"
#include "third_party/blink/renderer/modules/indexeddb/web_idb_database_callbacks_impl.h"
#include "third_party/blink/renderer/modules/indexeddb/web_idb_transaction_impl.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
const char IDBDatabase::kIndexDeletedErrorMessage[] =
"The index or its object store has been deleted.";
const char IDBDatabase::kIndexNameTakenErrorMessage[] =
"An index with the specified name already exists.";
const char IDBDatabase::kIsKeyCursorErrorMessage[] =
"The cursor is a key cursor.";
const char IDBDatabase::kNoKeyOrKeyRangeErrorMessage[] =
"No key or key range specified.";
const char IDBDatabase::kNoSuchIndexErrorMessage[] =
"The specified index was not found.";
const char IDBDatabase::kNoSuchObjectStoreErrorMessage[] =
"The specified object store was not found.";
const char IDBDatabase::kNoValueErrorMessage[] =
"The cursor is being iterated or has iterated past its end.";
const char IDBDatabase::kNotValidKeyErrorMessage[] =
"The parameter is not a valid key.";
const char IDBDatabase::kNotVersionChangeTransactionErrorMessage[] =
"The database is not running a version change transaction.";
const char IDBDatabase::kObjectStoreDeletedErrorMessage[] =
"The object store has been deleted.";
const char IDBDatabase::kObjectStoreNameTakenErrorMessage[] =
"An object store with the specified name already exists.";
const char IDBDatabase::kRequestNotFinishedErrorMessage[] =
"The request has not finished.";
const char IDBDatabase::kSourceDeletedErrorMessage[] =
"The cursor's source or effective object store has been deleted.";
const char IDBDatabase::kTransactionInactiveErrorMessage[] =
"The transaction is not active.";
const char IDBDatabase::kTransactionFinishedErrorMessage[] =
"The transaction has finished.";
const char IDBDatabase::kTransactionReadOnlyErrorMessage[] =
"The transaction is read-only.";
const char IDBDatabase::kDatabaseClosedErrorMessage[] =
"The database connection is closed.";
IDBDatabase::IDBDatabase(
ExecutionContext* context,
std::unique_ptr<WebIDBDatabase> backend,
IDBDatabaseCallbacks* callbacks,
mojo::PendingRemote<mojom::blink::ObservedFeature> connection_lifetime)
: ExecutionContextLifecycleObserver(context),
backend_(std::move(backend)),
connection_lifetime_(std::move(connection_lifetime)),
event_queue_(
MakeGarbageCollected<EventQueue>(context, TaskType::kDatabaseAccess)),
database_callbacks_(callbacks),
feature_handle_for_scheduler_(
context
? context->GetScheduler()->RegisterFeature(
SchedulingPolicy::Feature::kIndexedDBConnection,
{SchedulingPolicy::DisableBackForwardCache()})
: FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle()) {
database_callbacks_->Connect(this);
}
IDBDatabase::~IDBDatabase() {
if (!close_pending_ && backend_)
backend_->Close();
}
void IDBDatabase::Trace(Visitor* visitor) const {
visitor->Trace(version_change_transaction_);
visitor->Trace(transactions_);
visitor->Trace(event_queue_);
visitor->Trace(database_callbacks_);
EventTargetWithInlineData::Trace(visitor);
ExecutionContextLifecycleObserver::Trace(visitor);
}
int64_t IDBDatabase::NextTransactionId() {
// Starts at 1, unlike AtomicSequenceNumber.
// Only keep a 32-bit counter to allow ports to use the other 32
// bits of the id.
static base::AtomicSequenceNumber current_transaction_id;
return current_transaction_id.GetNext() + 1;
}
void IDBDatabase::SetMetadata(const IDBDatabaseMetadata& metadata) {
metadata_ = metadata;
}
void IDBDatabase::SetDatabaseMetadata(const IDBDatabaseMetadata& metadata) {
metadata_.CopyFrom(metadata);
}
void IDBDatabase::TransactionCreated(IDBTransaction* transaction) {
DCHECK(transaction);
DCHECK(!transactions_.Contains(transaction->Id()));
transactions_.insert(transaction->Id(), transaction);
if (transaction->IsVersionChange()) {
DCHECK(!version_change_transaction_);
version_change_transaction_ = transaction;
}
}
void IDBDatabase::TransactionFinished(const IDBTransaction* transaction) {
DCHECK(transaction);
DCHECK(transactions_.Contains(transaction->Id()));
DCHECK_EQ(transactions_.at(transaction->Id()), transaction);
transactions_.erase(transaction->Id());
if (transaction->IsVersionChange()) {
DCHECK_EQ(version_change_transaction_, transaction);
version_change_transaction_ = nullptr;
}
if (close_pending_ && transactions_.IsEmpty())
CloseConnection();
}
void IDBDatabase::OnAbort(int64_t transaction_id, DOMException* error) {
DCHECK(transactions_.Contains(transaction_id));
transactions_.at(transaction_id)->OnAbort(error);
}
void IDBDatabase::OnComplete(int64_t transaction_id) {
DCHECK(transactions_.Contains(transaction_id));
transactions_.at(transaction_id)->OnComplete();
}
DOMStringList* IDBDatabase::objectStoreNames() const {
auto* object_store_names = MakeGarbageCollected<DOMStringList>();
for (const auto& it : metadata_.object_stores)
object_store_names->Append(it.value->name);
object_store_names->Sort();
return object_store_names;
}
const String& IDBDatabase::GetObjectStoreName(int64_t object_store_id) const {
const auto& it = metadata_.object_stores.find(object_store_id);
DCHECK(it != metadata_.object_stores.end());
return it->value->name;
}
IDBObjectStore* IDBDatabase::createObjectStore(
const String& name,
const IDBKeyPath& key_path,
bool auto_increment,
ExceptionState& exception_state) {
IDB_TRACE("IDBDatabase::createObjectStore");
if (!version_change_transaction_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
IDBDatabase::kNotVersionChangeTransactionErrorMessage);
return nullptr;
}
if (!version_change_transaction_->IsActive()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kTransactionInactiveError,
version_change_transaction_->InactiveErrorMessage());
return nullptr;
}
if (!key_path.IsNull() && !key_path.IsValid()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The keyPath option is not a valid key path.");
return nullptr;
}
if (ContainsObjectStore(name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kConstraintError,
IDBDatabase::kObjectStoreNameTakenErrorMessage);
return nullptr;
}
if (auto_increment && ((key_path.GetType() == mojom::IDBKeyPathType::String &&
key_path.GetString().IsEmpty()) ||
key_path.GetType() == mojom::IDBKeyPathType::Array)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The autoIncrement option was set but the "
"keyPath option was empty or an array.");
return nullptr;
}
if (!backend_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
IDBDatabase::kDatabaseClosedErrorMessage);
return nullptr;
}
int64_t object_store_id = metadata_.max_object_store_id + 1;
DCHECK_NE(object_store_id, IDBObjectStoreMetadata::kInvalidId);
version_change_transaction_->transaction_backend()->CreateObjectStore(
object_store_id, name, key_path, auto_increment);
scoped_refptr<IDBObjectStoreMetadata> store_metadata =
base::AdoptRef(new IDBObjectStoreMetadata(
name, object_store_id, key_path, auto_increment,
WebIDBDatabase::kMinimumIndexId));
auto* object_store = MakeGarbageCollected<IDBObjectStore>(
store_metadata, version_change_transaction_.Get());
version_change_transaction_->ObjectStoreCreated(name, object_store);
metadata_.object_stores.Set(object_store_id, std::move(store_metadata));
++metadata_.max_object_store_id;
return object_store;
}
void IDBDatabase::deleteObjectStore(const String& name,
ExceptionState& exception_state) {
IDB_TRACE("IDBDatabase::deleteObjectStore");
if (!version_change_transaction_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
IDBDatabase::kNotVersionChangeTransactionErrorMessage);
return;
}
if (!version_change_transaction_->IsActive()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kTransactionInactiveError,
version_change_transaction_->InactiveErrorMessage());
return;
}
int64_t object_store_id = FindObjectStoreId(name);
if (object_store_id == IDBObjectStoreMetadata::kInvalidId) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotFoundError,
"The specified object store was not found.");
return;
}
if (!backend_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
IDBDatabase::kDatabaseClosedErrorMessage);
return;
}
version_change_transaction_->transaction_backend()->DeleteObjectStore(
object_store_id);
version_change_transaction_->ObjectStoreDeleted(object_store_id, name);
metadata_.object_stores.erase(object_store_id);
}
IDBTransaction* IDBDatabase::transaction(
ScriptState* script_state,
const StringOrStringSequence& store_names,
const String& mode,
ExceptionState& exception_state) {
return transaction(script_state, store_names, mode, nullptr, exception_state);
}
IDBTransaction* IDBDatabase::transaction(
ScriptState* script_state,
const StringOrStringSequence& store_names,
const String& mode_string,
const IDBTransactionOptions* options,
ExceptionState& exception_state) {
IDB_TRACE("IDBDatabase::transaction");
HashSet<String> scope;
if (store_names.IsString()) {
scope.insert(store_names.GetAsString());
} else if (store_names.IsStringSequence()) {
for (const String& name : store_names.GetAsStringSequence())
scope.insert(name);
} else {
NOTREACHED();
}
if (version_change_transaction_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"A version change transaction is running.");
return nullptr;
}
if (close_pending_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"The database connection is closing.");
return nullptr;
}
if (!backend_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
IDBDatabase::kDatabaseClosedErrorMessage);
return nullptr;
}
if (scope.IsEmpty()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The storeNames parameter was empty.");
return nullptr;
}
Vector<int64_t> object_store_ids;
for (const String& name : scope) {
int64_t object_store_id = FindObjectStoreId(name);
if (object_store_id == IDBObjectStoreMetadata::kInvalidId) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotFoundError,
"One of the specified object stores was not found.");
return nullptr;
}
object_store_ids.push_back(object_store_id);
}
mojom::IDBTransactionMode mode = IDBTransaction::StringToMode(mode_string);
if (mode != mojom::IDBTransactionMode::ReadOnly &&
mode != mojom::IDBTransactionMode::ReadWrite) {
exception_state.ThrowTypeError(
"The mode provided ('" + mode_string +
"') is not one of 'readonly' or 'readwrite'.");
return nullptr;
}
// TODO(cmp): Delete |transaction_id| once all users are removed.
int64_t transaction_id = NextTransactionId();
auto transaction_backend = std::make_unique<WebIDBTransactionImpl>(
ExecutionContext::From(script_state)
->GetTaskRunner(TaskType::kDatabaseAccess),
transaction_id);
mojom::IDBTransactionDurability durability =
mojom::IDBTransactionDurability::Default;
if (options) {
DCHECK(RuntimeEnabledFeatures::IDBRelaxedDurabilityEnabled());
if (options->durability() == indexed_db_names::kRelaxed) {
durability = mojom::IDBTransactionDurability::Relaxed;
} else if (options->durability() == indexed_db_names::kStrict) {
durability = mojom::IDBTransactionDurability::Strict;
}
}
backend_->CreateTransaction(transaction_backend->CreateReceiver(),
transaction_id, object_store_ids, mode,
durability);
return IDBTransaction::CreateNonVersionChange(
script_state, std::move(transaction_backend), transaction_id, scope, mode,
durability, this);
}
void IDBDatabase::ForceClose() {
for (const auto& it : transactions_)
it.value->abort(IGNORE_EXCEPTION_FOR_TESTING);
this->close();
EnqueueEvent(Event::Create(event_type_names::kClose));
}
void IDBDatabase::close() {
IDB_TRACE("IDBDatabase::close");
if (close_pending_)
return;
connection_lifetime_.reset();
close_pending_ = true;
feature_handle_for_scheduler_.reset();
if (transactions_.IsEmpty())
CloseConnection();
}
void IDBDatabase::CloseConnection() {
DCHECK(close_pending_);
DCHECK(transactions_.IsEmpty());
if (backend_) {
backend_->Close();
backend_.reset();
}
if (database_callbacks_)
database_callbacks_->DetachWebCallbacks();
if (!GetExecutionContext())
return;
// Remove any pending versionchange events scheduled to fire on this
// connection. They would have been scheduled by the backend when another
// connection attempted an upgrade, but the frontend connection is being
// closed before they could fire.
event_queue_->CancelAllEvents();
}
void IDBDatabase::OnVersionChange(int64_t old_version, int64_t new_version) {
IDB_TRACE("IDBDatabase::onVersionChange");
if (!GetExecutionContext())
return;
if (close_pending_) {
// If we're pending, that means there's a busy transaction. We won't
// fire 'versionchange' but since we're not closing immediately the
// back-end should still send out 'blocked'.
backend_->VersionChangeIgnored();
return;
}
base::Optional<uint64_t> new_version_nullable;
if (new_version != IDBDatabaseMetadata::kNoVersion) {
new_version_nullable = new_version;
}
EnqueueEvent(MakeGarbageCollected<IDBVersionChangeEvent>(
event_type_names::kVersionchange, old_version, new_version_nullable));
}
void IDBDatabase::EnqueueEvent(Event* event) {
DCHECK(GetExecutionContext());
event->SetTarget(this);
event_queue_->EnqueueEvent(FROM_HERE, *event);
}
DispatchEventResult IDBDatabase::DispatchEventInternal(Event& event) {
IDB_TRACE("IDBDatabase::dispatchEvent");
event.SetTarget(this);
// If this event originated from script, it should have no side effects.
if (!event.isTrusted())
return EventTarget::DispatchEventInternal(event);
DCHECK(event.type() == event_type_names::kVersionchange ||
event.type() == event_type_names::kClose);
if (!GetExecutionContext())
return DispatchEventResult::kCanceledBeforeDispatch;
DispatchEventResult dispatch_result =
EventTarget::DispatchEventInternal(event);
if (event.type() == event_type_names::kVersionchange && !close_pending_ &&
backend_)
backend_->VersionChangeIgnored();
return dispatch_result;
}
int64_t IDBDatabase::FindObjectStoreId(const String& name) const {
for (const auto& it : metadata_.object_stores) {
if (it.value->name == name) {
DCHECK_NE(it.key, IDBObjectStoreMetadata::kInvalidId);
return it.key;
}
}
return IDBObjectStoreMetadata::kInvalidId;
}
void IDBDatabase::RenameObjectStore(int64_t object_store_id,
const String& new_name) {
DCHECK(version_change_transaction_)
<< "Object store renamed on database without a versionchange transaction";
DCHECK(version_change_transaction_->IsActive())
<< "Object store renamed when versionchange transaction is not active";
DCHECK(backend_) << "Object store renamed after database connection closed";
DCHECK(metadata_.object_stores.Contains(object_store_id));
backend_->RenameObjectStore(version_change_transaction_->Id(),
object_store_id, new_name);
IDBObjectStoreMetadata* object_store_metadata =
metadata_.object_stores.at(object_store_id);
version_change_transaction_->ObjectStoreRenamed(object_store_metadata->name,
new_name);
object_store_metadata->name = new_name;
}
void IDBDatabase::RevertObjectStoreCreation(int64_t object_store_id) {
DCHECK(version_change_transaction_) << "Object store metadata reverted on "
"database without a versionchange "
"transaction";
DCHECK(!version_change_transaction_->IsActive())
<< "Object store metadata reverted when versionchange transaction is "
"still active";
DCHECK(metadata_.object_stores.Contains(object_store_id));
metadata_.object_stores.erase(object_store_id);
}
void IDBDatabase::RevertObjectStoreMetadata(
scoped_refptr<IDBObjectStoreMetadata> old_metadata) {
DCHECK(version_change_transaction_) << "Object store metadata reverted on "
"database without a versionchange "
"transaction";
DCHECK(!version_change_transaction_->IsActive())
<< "Object store metadata reverted when versionchange transaction is "
"still active";
DCHECK(old_metadata.get());
metadata_.object_stores.Set(old_metadata->id, std::move(old_metadata));
}
bool IDBDatabase::HasPendingActivity() const {
// The script wrapper must not be collected before the object is closed or
// we can't fire a "versionchange" event to let script manually close the
// connection.
return !close_pending_ && GetExecutionContext() && HasEventListeners();
}
void IDBDatabase::ContextDestroyed() {
// Immediately close the connection to the back end. Don't attempt a
// normal close() since that may wait on transactions which require a
// round trip to the back-end to abort.
if (backend_) {
backend_->Close();
backend_.reset();
}
connection_lifetime_.reset();
if (database_callbacks_)
database_callbacks_->DetachWebCallbacks();
}
const AtomicString& IDBDatabase::InterfaceName() const {
return event_target_names::kIDBDatabase;
}
ExecutionContext* IDBDatabase::GetExecutionContext() const {
return ExecutionContextLifecycleObserver::GetExecutionContext();
}
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kNoError,
DOMExceptionCode::kNoError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kUnknownError,
DOMExceptionCode::kUnknownError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kConstraintError,
DOMExceptionCode::kConstraintError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kDataError,
DOMExceptionCode::kDataError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kVersionError,
DOMExceptionCode::kVersionError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kAbortError,
DOMExceptionCode::kAbortError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kQuotaError,
DOMExceptionCode::kQuotaExceededError);
STATIC_ASSERT_ENUM(mojom::blink::IDBException::kTimeoutError,
DOMExceptionCode::kTimeoutError);
} // namespace blink
| 38.294719 | 94 | 0.735531 |
28331d1fad394a87a4e92012de0e9b6b0598c39f | 26,831 | cpp | C++ | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2019-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "patchtokens_decoder.h"
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/helpers/debug_helpers.h"
#include "shared/source/helpers/hash.h"
#include "shared/source/helpers/ptr_math.h"
#include <algorithm>
namespace NEO {
namespace PatchTokenBinary {
struct PatchTokensStreamReader {
const ArrayRef<const uint8_t> data;
PatchTokensStreamReader(ArrayRef<const uint8_t> data) : data(data) {}
template <typename DecodePosT>
bool notEnoughDataLeft(DecodePosT *decodePos, size_t requestedSize) {
return getDataSizeLeft(decodePos) < requestedSize;
}
template <typename T, typename DecodePosT>
constexpr bool notEnoughDataLeft(DecodePosT *decodePos) {
return notEnoughDataLeft(decodePos, sizeof(T));
}
template <typename... ArgsT>
bool enoughDataLeft(ArgsT &&...args) {
return false == notEnoughDataLeft(std::forward<ArgsT>(args)...);
}
template <typename T, typename... ArgsT>
bool enoughDataLeft(ArgsT &&...args) {
return false == notEnoughDataLeft<T>(std::forward<ArgsT>(args)...);
}
template <typename DecodePosT>
size_t getDataSizeLeft(DecodePosT *decodePos) {
auto dataConsumed = ptrDiff(decodePos, data.begin());
UNRECOVERABLE_IF(dataConsumed > data.size());
return data.size() - dataConsumed;
}
};
template <typename T>
inline void assignToken(const T *&dst, const SPatchItemHeader *src) {
dst = reinterpret_cast<const T *>(src);
}
inline KernelArgFromPatchtokens &getKernelArg(KernelFromPatchtokens &kernel, size_t argNum, ArgObjectType type = ArgObjectType::None, ArgObjectTypeSpecialized typeSpecialized = ArgObjectTypeSpecialized::None) {
if (kernel.tokens.kernelArgs.size() < argNum + 1) {
kernel.tokens.kernelArgs.resize(argNum + 1);
}
auto &arg = kernel.tokens.kernelArgs[argNum];
if (arg.objectType == ArgObjectType::None) {
arg.objectType = type;
} else if ((arg.objectType != type) && (type != ArgObjectType::None)) {
kernel.decodeStatus = DecodeError::InvalidBinary;
DBG_LOG(LogPatchTokens, "\n Mismatched metadata for kernel arg :", argNum);
DEBUG_BREAK_IF(true);
}
if (arg.objectTypeSpecialized == ArgObjectTypeSpecialized::None) {
arg.objectTypeSpecialized = typeSpecialized;
} else if (typeSpecialized != ArgObjectTypeSpecialized::None) {
UNRECOVERABLE_IF(arg.objectTypeSpecialized != typeSpecialized);
}
return arg;
}
inline void assignArgInfo(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) {
auto argInfoToken = reinterpret_cast<const SPatchKernelArgumentInfo *>(src);
getKernelArg(kernel, argInfoToken->ArgumentNumber, ArgObjectType::None).argInfo = argInfoToken;
}
template <typename T>
inline uint32_t getArgNum(const SPatchItemHeader *argToken) {
return reinterpret_cast<const T *>(argToken)->ArgumentNumber;
}
inline void assignArg(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) {
uint32_t argNum = 0;
ArgObjectType type = ArgObjectType::Buffer;
switch (src->Token) {
default:
UNRECOVERABLE_IF(src->Token != PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT);
argNum = getArgNum<SPatchSamplerKernelArgument>(src);
type = ArgObjectType::Sampler;
break;
case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchImageMemoryObjectKernelArgument>(src);
type = ArgObjectType::Image;
break;
case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchGlobalMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessGlobalMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessConstantMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessDeviceQueueKernelArgument>(src);
break;
}
getKernelArg(kernel, argNum, type).objectArg = src;
}
inline void assignToken(StackVecStrings &stringVec, const SPatchItemHeader *src) {
auto stringToken = reinterpret_cast<const SPatchString *>(src);
if (stringVec.size() < stringToken->Index + 1) {
stringVec.resize(stringToken->Index + 1);
}
stringVec[stringToken->Index] = stringToken;
}
template <size_t S>
inline void assignTokenInArray(const SPatchDataParameterBuffer *(&tokensArray)[S], const SPatchDataParameterBuffer *src, StackVecUnhandledTokens &unhandledTokens) {
auto sourceIndex = src->SourceOffset >> 2;
if (sourceIndex >= S) {
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex);
DEBUG_BREAK_IF(true);
unhandledTokens.push_back(src);
return;
}
assignToken(tokensArray[sourceIndex], src);
}
template <typename PatchT, size_t NumInlineEl>
inline void addTok(StackVec<const PatchT *, NumInlineEl> &tokensVec, const SPatchItemHeader *src) {
tokensVec.push_back(reinterpret_cast<const PatchT *>(src));
}
inline void decodeKernelDataParameterToken(const SPatchDataParameterBuffer *token, KernelFromPatchtokens &out) {
auto &crossthread = out.tokens.crossThreadPayloadArgs;
auto sourceIndex = token->SourceOffset >> 2;
auto argNum = token->ArgumentNumber;
switch (token->Type) {
default:
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled SPatchDataParameterBuffer ", token->Type);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
case DATA_PARAMETER_KERNEL_ARGUMENT:
getKernelArg(out, argNum, ArgObjectType::None).byValMap.push_back(token);
break;
case DATA_PARAMETER_LOCAL_WORK_SIZE: {
if (sourceIndex >= 3) {
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
return;
}
auto localWorkSizeArray = (crossthread.localWorkSize[sourceIndex] == nullptr)
? crossthread.localWorkSize
: crossthread.localWorkSize2;
localWorkSizeArray[sourceIndex] = token;
break;
}
case DATA_PARAMETER_GLOBAL_WORK_OFFSET:
assignTokenInArray(crossthread.globalWorkOffset, token, out.unhandledTokens);
break;
case DATA_PARAMETER_ENQUEUED_LOCAL_WORK_SIZE:
assignTokenInArray(crossthread.enqueuedLocalWorkSize, token, out.unhandledTokens);
break;
case DATA_PARAMETER_GLOBAL_WORK_SIZE:
assignTokenInArray(crossthread.globalWorkSize, token, out.unhandledTokens);
break;
case DATA_PARAMETER_NUM_WORK_GROUPS:
assignTokenInArray(crossthread.numWorkGroups, token, out.unhandledTokens);
break;
case DATA_PARAMETER_MAX_WORKGROUP_SIZE:
crossthread.maxWorkGroupSize = token;
break;
case DATA_PARAMETER_WORK_DIMENSIONS:
crossthread.workDimensions = token;
break;
case DATA_PARAMETER_SIMD_SIZE:
crossthread.simdSize = token;
break;
case DATA_PARAMETER_PRIVATE_MEMORY_STATELESS_SIZE:
crossthread.privateMemoryStatelessSize = token;
break;
case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_SIZE:
crossthread.localMemoryStatelessWindowSize = token;
break;
case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_START_ADDRESS:
crossthread.localMemoryStatelessWindowStartAddress = token;
break;
case DATA_PARAMETER_OBJECT_ID:
getKernelArg(out, argNum, ArgObjectType::None).objectId = token;
break;
case DATA_PARAMETER_SUM_OF_LOCAL_MEMORY_OBJECT_ARGUMENT_SIZES: {
auto &kernelArg = getKernelArg(out, argNum, ArgObjectType::Slm);
kernelArg.byValMap.push_back(token);
kernelArg.metadata.slm.token = token;
} break;
case DATA_PARAMETER_BUFFER_OFFSET:
getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.bufferOffset = token;
break;
case DATA_PARAMETER_BUFFER_STATEFUL:
getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.pureStateful = token;
break;
case DATA_PARAMETER_IMAGE_WIDTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.width = token;
break;
case DATA_PARAMETER_IMAGE_HEIGHT:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.height = token;
break;
case DATA_PARAMETER_IMAGE_DEPTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.depth = token;
break;
case DATA_PARAMETER_IMAGE_CHANNEL_DATA_TYPE:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelDataType = token;
break;
case DATA_PARAMETER_IMAGE_CHANNEL_ORDER:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelOrder = token;
break;
case DATA_PARAMETER_IMAGE_ARRAY_SIZE:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.arraySize = token;
break;
case DATA_PARAMETER_IMAGE_NUM_SAMPLES:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numSamples = token;
break;
case DATA_PARAMETER_IMAGE_NUM_MIP_LEVELS:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numMipLevels = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_BASEOFFSET:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatBaseOffset = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_WIDTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatWidth = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_HEIGHT:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatHeight = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_PITCH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatPitch = token;
break;
case DATA_PARAMETER_SAMPLER_COORDINATE_SNAP_WA_REQUIRED:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.coordinateSnapWaRequired = token;
break;
case DATA_PARAMETER_SAMPLER_ADDRESS_MODE:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.addressMode = token;
break;
case DATA_PARAMETER_SAMPLER_NORMALIZED_COORDS:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.normalizedCoords = token;
break;
case DATA_PARAMETER_VME_MB_BLOCK_TYPE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.mbBlockType = token;
break;
case DATA_PARAMETER_VME_SUBPIXEL_MODE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.subpixelMode = token;
break;
case DATA_PARAMETER_VME_SAD_ADJUST_MODE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.sadAdjustMode = token;
break;
case DATA_PARAMETER_VME_SEARCH_PATH_TYPE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.searchPathType = token;
break;
case DATA_PARAMETER_PARENT_EVENT:
crossthread.parentEvent = token;
break;
case DATA_PARAMETER_PREFERRED_WORKGROUP_MULTIPLE:
crossthread.preferredWorkgroupMultiple = token;
break;
case DATA_PARAMETER_IMPL_ARG_BUFFER:
out.tokens.crossThreadPayloadArgs.implicitArgsBufferOffset = token;
break;
case DATA_PARAMETER_NUM_HARDWARE_THREADS:
case DATA_PARAMETER_PRINTF_SURFACE_SIZE:
case DATA_PARAMETER_IMAGE_SRGB_CHANNEL_ORDER:
case DATA_PARAMETER_STAGE_IN_GRID_ORIGIN:
case DATA_PARAMETER_STAGE_IN_GRID_SIZE:
case DATA_PARAMETER_LOCAL_ID:
case DATA_PARAMETER_EXECUTION_MASK:
case DATA_PARAMETER_VME_IMAGE_TYPE:
case DATA_PARAMETER_VME_MB_SKIP_BLOCK_TYPE:
case DATA_PARAMETER_CHILD_BLOCK_SIMD_SIZE:
// ignored intentionally
break;
}
}
inline bool decodeToken(const SPatchItemHeader *token, KernelFromPatchtokens &out) {
switch (token->Token) {
default: {
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown kernel-scope Patch Token: %d\n", token->Token);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
}
case PATCH_TOKEN_INTERFACE_DESCRIPTOR_DATA:
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Ignored kernel-scope Patch Token: %d\n", token->Token);
break;
case PATCH_TOKEN_SAMPLER_STATE_ARRAY:
assignToken(out.tokens.samplerStateArray, token);
break;
case PATCH_TOKEN_BINDING_TABLE_STATE:
assignToken(out.tokens.bindingTableState, token);
break;
case PATCH_TOKEN_ALLOCATE_LOCAL_SURFACE:
assignToken(out.tokens.allocateLocalSurface, token);
break;
case PATCH_TOKEN_MEDIA_VFE_STATE:
assignToken(out.tokens.mediaVfeState[0], token);
break;
case PATCH_TOKEN_MEDIA_VFE_STATE_SLOT1:
assignToken(out.tokens.mediaVfeState[1], token);
break;
case PATCH_TOKEN_MEDIA_INTERFACE_DESCRIPTOR_LOAD:
assignToken(out.tokens.mediaInterfaceDescriptorLoad, token);
break;
case PATCH_TOKEN_THREAD_PAYLOAD:
assignToken(out.tokens.threadPayload, token);
break;
case PATCH_TOKEN_EXECUTION_ENVIRONMENT:
assignToken(out.tokens.executionEnvironment, token);
break;
case PATCH_TOKEN_KERNEL_ATTRIBUTES_INFO:
assignToken(out.tokens.kernelAttributesInfo, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_PRIVATE_MEMORY:
assignToken(out.tokens.allocateStatelessPrivateSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_CONSTANT_MEMORY_SURFACE_WITH_INITIALIZATION:
assignToken(out.tokens.allocateStatelessConstantMemorySurfaceWithInitialization, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_GLOBAL_MEMORY_SURFACE_WITH_INITIALIZATION:
assignToken(out.tokens.allocateStatelessGlobalMemorySurfaceWithInitialization, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_PRINTF_SURFACE:
assignToken(out.tokens.allocateStatelessPrintfSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_EVENT_POOL_SURFACE:
assignToken(out.tokens.allocateStatelessEventPoolSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_DEFAULT_DEVICE_QUEUE_SURFACE:
assignToken(out.tokens.allocateStatelessDefaultDeviceQueueSurface, token);
break;
case PATCH_TOKEN_STRING:
assignToken(out.tokens.strings, token);
break;
case PATCH_TOKEN_INLINE_VME_SAMPLER_INFO:
assignToken(out.tokens.inlineVmeSamplerInfo, token);
break;
case PATCH_TOKEN_GTPIN_FREE_GRF_INFO:
assignToken(out.tokens.gtpinFreeGrfInfo, token);
break;
case PATCH_TOKEN_GTPIN_INFO:
assignToken(out.tokens.gtpinInfo, token);
break;
case PATCH_TOKEN_STATE_SIP:
assignToken(out.tokens.stateSip, token);
break;
case PATCH_TOKEN_ALLOCATE_SIP_SURFACE:
assignToken(out.tokens.allocateSystemThreadSurface, token);
break;
case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE:
assignToken(out.tokens.programSymbolTable, token);
break;
case PATCH_TOKEN_PROGRAM_RELOCATION_TABLE:
assignToken(out.tokens.programRelocationTable, token);
break;
case PATCH_TOKEN_KERNEL_ARGUMENT_INFO:
assignArgInfo(out, token);
break;
case PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT:
case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT:
assignArg(out, token);
break;
case PATCH_TOKEN_DATA_PARAMETER_STREAM:
assignToken(out.tokens.dataParameterStream, token);
break;
case PATCH_TOKEN_DATA_PARAMETER_BUFFER: {
auto tokDataP = reinterpret_cast<const SPatchDataParameterBuffer *>(token);
decodeKernelDataParameterToken(tokDataP, out);
} break;
case PATCH_TOKEN_ALLOCATE_SYNC_BUFFER: {
assignToken(out.tokens.allocateSyncBuffer, token);
} break;
}
return out.decodeStatus != DecodeError::InvalidBinary;
}
inline bool decodeToken(const SPatchItemHeader *token, ProgramFromPatchtokens &out) {
auto &progTok = out.programScopeTokens;
switch (token->Token) {
default: {
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown program-scope Patch Token: %d\n", token->Token);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
}
case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
addTok(progTok.allocateConstantMemorySurface, token);
break;
case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
addTok(progTok.allocateGlobalMemorySurface, token);
break;
case PATCH_TOKEN_GLOBAL_POINTER_PROGRAM_BINARY_INFO:
addTok(progTok.globalPointer, token);
break;
case PATCH_TOKEN_CONSTANT_POINTER_PROGRAM_BINARY_INFO:
addTok(progTok.constantPointer, token);
break;
case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE:
assignToken(progTok.symbolTable, token);
break;
case _PATCH_TOKEN_GLOBAL_HOST_ACCESS_TABLE:
assignToken(progTok.hostAccessTable, token);
break;
}
return true;
}
template <typename DecodeContext>
inline size_t getPatchTokenTotalSize(PatchTokensStreamReader stream, const SPatchItemHeader *token);
template <>
inline size_t getPatchTokenTotalSize<KernelFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) {
return token->Size;
}
template <>
inline size_t getPatchTokenTotalSize<ProgramFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) {
size_t tokSize = token->Size;
switch (token->Token) {
default:
return tokSize;
case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
return stream.enoughDataLeft<SPatchAllocateConstantMemorySurfaceProgramBinaryInfo>(token)
? tokSize + reinterpret_cast<const SPatchAllocateConstantMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize
: std::numeric_limits<size_t>::max();
case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
return stream.enoughDataLeft<SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo>(token)
? tokSize + reinterpret_cast<const SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize
: std::numeric_limits<size_t>::max();
}
}
template <typename OutT>
inline bool decodePatchList(PatchTokensStreamReader patchListStream, OutT &out) {
auto decodePos = patchListStream.data.begin();
auto decodeEnd = patchListStream.data.end();
bool decodeSuccess = true;
while ((ptrDiff(decodeEnd, decodePos) > sizeof(SPatchItemHeader)) && decodeSuccess) {
auto token = reinterpret_cast<const SPatchItemHeader *>(decodePos);
size_t tokenTotalSize = getPatchTokenTotalSize<OutT>(patchListStream, token);
decodeSuccess = patchListStream.enoughDataLeft(decodePos, tokenTotalSize);
decodeSuccess = decodeSuccess && (tokenTotalSize > 0U);
decodeSuccess = decodeSuccess && decodeToken(token, out);
decodePos = ptrOffset(decodePos, tokenTotalSize);
}
return decodeSuccess;
}
bool decodeKernelFromPatchtokensBlob(ArrayRef<const uint8_t> kernelBlob, KernelFromPatchtokens &out) {
PatchTokensStreamReader stream{kernelBlob};
auto decodePos = stream.data.begin();
out.decodeStatus = DecodeError::Undefined;
if (stream.notEnoughDataLeft<SKernelBinaryHeaderCommon>(decodePos)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.header = reinterpret_cast<const SKernelBinaryHeaderCommon *>(decodePos);
auto kernelInfoBlobSize = sizeof(SKernelBinaryHeaderCommon) + out.header->KernelNameSize + out.header->KernelHeapSize + out.header->GeneralStateHeapSize + out.header->DynamicStateHeapSize + out.header->SurfaceStateHeapSize + out.header->PatchListSize;
if (stream.notEnoughDataLeft(decodePos, kernelInfoBlobSize)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.blobs.kernelInfo = ArrayRef<const uint8_t>(stream.data.begin(), kernelInfoBlobSize);
decodePos = ptrOffset(decodePos, sizeof(SKernelBinaryHeaderCommon));
auto kernelName = reinterpret_cast<const char *>(decodePos);
out.name = ArrayRef<const char>(kernelName, out.header->KernelNameSize);
decodePos = ptrOffset(decodePos, out.name.size());
out.isa = ArrayRef<const uint8_t>(decodePos, out.header->KernelHeapSize);
decodePos = ptrOffset(decodePos, out.isa.size());
out.heaps.generalState = ArrayRef<const uint8_t>(decodePos, out.header->GeneralStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.generalState.size());
out.heaps.dynamicState = ArrayRef<const uint8_t>(decodePos, out.header->DynamicStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.dynamicState.size());
out.heaps.surfaceState = ArrayRef<const uint8_t>(decodePos, out.header->SurfaceStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.surfaceState.size());
out.blobs.patchList = ArrayRef<const uint8_t>(decodePos, out.header->PatchListSize);
if (false == decodePatchList(out.blobs.patchList, out)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.decodeStatus = DecodeError::Success;
return true;
}
inline bool decodeProgramHeader(ProgramFromPatchtokens &decodedProgram) {
auto decodePos = decodedProgram.blobs.programInfo.begin();
PatchTokensStreamReader stream{decodedProgram.blobs.programInfo};
if (stream.notEnoughDataLeft<SProgramBinaryHeader>(decodePos)) {
return false;
}
decodedProgram.header = reinterpret_cast<const SProgramBinaryHeader *>(decodePos);
if (decodedProgram.header->Magic != MAGIC_CL) {
return false;
}
decodePos = ptrOffset(decodePos, sizeof(SProgramBinaryHeader));
if (stream.notEnoughDataLeft(decodePos, decodedProgram.header->PatchListSize)) {
return false;
}
decodedProgram.blobs.patchList = ArrayRef<const uint8_t>(decodePos, decodedProgram.header->PatchListSize);
decodePos = ptrOffset(decodePos, decodedProgram.blobs.patchList.size());
decodedProgram.blobs.kernelsInfo = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos));
return true;
}
inline bool decodeKernels(ProgramFromPatchtokens &decodedProgram) {
auto numKernels = decodedProgram.header->NumberOfKernels;
decodedProgram.kernels.reserve(decodedProgram.header->NumberOfKernels);
const uint8_t *decodePos = decodedProgram.blobs.kernelsInfo.begin();
bool decodeSuccess = true;
PatchTokensStreamReader stream{decodedProgram.blobs.kernelsInfo};
for (uint32_t i = 0; (i < numKernels) && decodeSuccess; i++) {
decodedProgram.kernels.resize(decodedProgram.kernels.size() + 1);
auto &currKernelInfo = *decodedProgram.kernels.rbegin();
auto kernelDataLeft = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos));
decodeSuccess = decodeKernelFromPatchtokensBlob(kernelDataLeft, currKernelInfo);
decodePos = ptrOffset(decodePos, currKernelInfo.blobs.kernelInfo.size());
}
return decodeSuccess;
}
bool decodeProgramFromPatchtokensBlob(ArrayRef<const uint8_t> programBlob, ProgramFromPatchtokens &out) {
out.blobs.programInfo = programBlob;
bool decodeSuccess = decodeProgramHeader(out);
decodeSuccess = decodeSuccess && decodeKernels(out);
decodeSuccess = decodeSuccess && decodePatchList(out.blobs.patchList, out);
out.decodeStatus = decodeSuccess ? DecodeError::Success : DecodeError::InvalidBinary;
return decodeSuccess;
}
uint32_t calcKernelChecksum(const ArrayRef<const uint8_t> kernelBlob) {
UNRECOVERABLE_IF(kernelBlob.size() <= sizeof(SKernelBinaryHeaderCommon));
auto dataToHash = ArrayRef<const uint8_t>(ptrOffset(kernelBlob.begin(), sizeof(SKernelBinaryHeaderCommon)), kernelBlob.end());
uint64_t hashValue = Hash::hash(reinterpret_cast<const char *>(dataToHash.begin()), dataToHash.size());
uint32_t checksum = hashValue & 0xFFFFFFFF;
return checksum;
}
bool hasInvalidChecksum(const KernelFromPatchtokens &decodedKernel) {
uint32_t decodedChecksum = decodedKernel.header->CheckSum;
uint32_t calculatedChecksum = NEO::PatchTokenBinary::calcKernelChecksum(decodedKernel.blobs.kernelInfo);
return decodedChecksum != calculatedChecksum;
}
const KernelArgAttributesFromPatchtokens getInlineData(const SPatchKernelArgumentInfo *ptr) {
KernelArgAttributesFromPatchtokens ret = {};
UNRECOVERABLE_IF(ptr == nullptr);
auto decodePos = reinterpret_cast<const char *>(ptr + 1);
auto bounds = reinterpret_cast<const char *>(ptr) + ptr->Size;
ret.addressQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AddressQualifierSize, bounds));
decodePos += ret.addressQualifier.size();
ret.accessQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AccessQualifierSize, bounds));
decodePos += ret.accessQualifier.size();
ret.argName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->ArgumentNameSize, bounds));
decodePos += ret.argName.size();
ret.typeName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeNameSize, bounds));
decodePos += ret.typeName.size();
ret.typeQualifiers = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeQualifierSize, bounds));
return ret;
}
const iOpenCL::SProgramBinaryHeader *decodeProgramHeader(const ArrayRef<const uint8_t> programBlob) {
ProgramFromPatchtokens program;
program.blobs.programInfo = programBlob;
if (false == decodeProgramHeader(program)) {
return nullptr;
}
return program.header;
}
} // namespace PatchTokenBinary
} // namespace NEO
| 42.120879 | 255 | 0.735232 |
283383cbfb967feccae62aef0f0c14b3dd3a6c3b | 2,502 | cc | C++ | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/common/service_manifests/builtin_service_manifests.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/constants.mojom.h"
#include "chrome/services/printing/public/cpp/manifest.h"
#include "components/services/pdf_compositor/public/cpp/manifest.h" // nogncheck
#include "components/spellcheck/common/spellcheck.mojom.h"
#include "components/startup_metric_utils/common/startup_metric.mojom.h"
#include "extensions/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#if defined(OS_MACOSX)
#include "components/spellcheck/common/spellcheck_panel.mojom.h"
#endif
namespace {
const service_manager::Manifest& GetCefManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.WithServiceName(chrome::mojom::kServiceName)
.WithDisplayName("CEF")
.WithOptions(
service_manager::ManifestOptionsBuilder()
.WithExecutionMode(
service_manager::Manifest::ExecutionMode::kInProcessBuiltin)
.WithInstanceSharingPolicy(
service_manager::Manifest::InstanceSharingPolicy::
kSharedAcrossGroups)
.CanConnectToInstancesWithAnyId(true)
.CanRegisterOtherServiceInstances(true)
.Build())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
#if defined(OS_MACOSX)
spellcheck::mojom::SpellCheckPanelHost,
#endif
spellcheck::mojom::SpellCheckHost,
startup_metric_utils::mojom::StartupMetricHost>())
.RequireCapability(chrome::mojom::kRendererServiceName, "browser")
.Build()
};
return *manifest;
}
} // namespace
const std::vector<service_manager::Manifest>& GetBuiltinServiceManifests() {
static base::NoDestructor<std::vector<service_manager::Manifest>> manifests{{
GetCefManifest(),
printing::GetPdfCompositorManifest(),
GetChromePrintingManifest(),
}};
return *manifests;
}
| 39.09375 | 81 | 0.698641 |
283494667f8cc67ec616bfd5cbb8447c4cc7275e | 4,735 | cpp | C++ | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | 5 | 2016-01-19T02:12:40.000Z | 2018-01-12T09:20:53.000Z | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | null | null | null | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | null | null | null |
#include "Poco/CountingStream.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include <ctrl/form/User.h>
using namespace ctrl::form;
static const std::string birthdayFormat = "%Y-%n-%e";
std::string birthdayFromDate(const Poco::DateTime &date)
{
return Poco::DateTimeFormatter::format(date, birthdayFormat);
}
Poco::DateTime birthdayToDate(const std::string &bday)
{
Poco::DateTime date;
int timeZoneDifferential;
if(Poco::DateTimeParser::tryParse(birthdayFormat, bday, date, timeZoneDifferential))
return date;
return Poco::DateTime(Poco::Timestamp(0));
}
User::User()
{
userTable.hideEmptyCollumns(true);
userGroups.prompt = "Set Group";
userGroups.add("Admin", "0");
userGroups.add("User", "2");
userGroups.add("Subscriber", "3");
addEvent(updateUser);
addEvent(removeUser);
addEvent(selectUser);
addEvent(updateGroup);
addEvent(paginate);
}
User::~User()
{
}
std::string User::format(const std::string &in)
{
return core::util::Html::format(in);
}
User::Mode User::mode()
{
if(users)
return MODE_USERS;
else
return MODE_SETTINGS;
}
std::string User::param()
{
std::string ret;
switch(mode())
{
case MODE_USERS: ret += "m=users&"; break;
case MODE_SETTINGS: ret += ""; break;
}
ret += "p=" + std::to_string(paginator.page()) + "&";
ret += "s=" + std::to_string(userTable.sort()) + "&";
return ret;
}
void User::onEnter()
{
val["status"] = "";
/// Fill settings
val["firstName"] = user().firstName();
val["lastName"] = user().lastName();
val["phoneNumber"] = user().phoneNumber();
val["country"] = user().country();
val["state"] = user().state();
val["birthday"] = birthdayFromDate(user().birthday());
}
void User::onLoad()
{
users = NULL;
/// Parameters
auto &mode = val["m"];
std::int64_t sort = 0; std::istringstream(val["s"]) >> sort;
std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page;
userTable.sort(sort);
if(page != INTMAX(32)) paginator.page(page);
/// Mode
switch(0)
{ default:
/// Prepare User table
bool modeUsers = mode == "users" && user().group() == user().ADMIN;
if(modeUsers)
{
paginator.doPaging(ctrl().service().getUsersCount());
users = ctrl().service().getUsers(-1, userTable.sort(), paginator.limit(), paginator.offset());
userTable.set(users);
break;
}
userTable.clear();
}
/// Reset parameters
val["m"] = val["s"] = val["p"] = "";
}
void User::updateUser(std::istream *stream)
{
if(!user()) return;
/// Parameters
auto firstName = val["firstName"];
auto lastName = val["lastName"];
auto phoneNumber = val["phoneNumber"];
auto country = val["country"];
auto state = val["state"];
auto birthday = birthdayToDate(val["birthday"]);
val["status"] = "";
/// Validation
if(!birthday.timestamp().raw())
val["status"] = "*Incorrect birthday format!";
if(lastName.empty())
val["status"] = "*Please enter Last Name!";
if(firstName.empty())
val["status"] = "*Please enter First Name!";
if(!val["status"].empty()) return;
model::User user = this->user();
user.firstName(firstName);
user.lastName(lastName);
user.phoneNumber(phoneNumber);
user.country(country);
user.state(state);
user.birthday(birthday);
ctrl().service().updateUser(user);
ctrl().update();
val["status"] = "Updated successfully!";
}
void User::removeUser(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
for(std::uint32_t i=0; i<users->size(); ++i) {
if(!userTable.rows()[i]->checked) continue;
ctrl().service().deleteUser(users()[i]->id());
}
userTable.clear();
}
void User::selectUser(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
/// Parameters
core::DataID rowAll = 0; std::istringstream(val["a"]) >> rowAll;
core::DataID rowInd = core::DataID(-1); std::istringstream(val["r"]) >> rowInd;
val["a"] = val["r"] = "";
if(rowAll) {
userTable.toggleAll();
return;
}
userTable.toggle(rowInd);
}
void User::updateGroup(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
/// Parameters
std::int32_t group = -1; std::istringstream(val["g"]) >> group;
val["g"] = "";
if(group < 0) return;
for(std::uint32_t i=0; i<users->size(); ++i) {
if(!userTable.rows()[i]->checked) continue;
users()[i]->group((model::User::Group)group);
ctrl().service().updateUser(*users()[i]);
}
userTable.clear();
}
void User::paginate(std::istream *stream)
{
/// Parameters
std::int32_t sort = INTMAX(32); std::istringstream(val["s"]) >> sort;
std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page;
val["s"] = val["p"] = "";
if(sort != INTMAX(32)) userTable.sort(sort);
else if(page != INTMAX(32)) paginator.page(page);
else paginator.extend();
ctrl().redirect(path() + "?" + param());
} | 22.023256 | 98 | 0.646251 |
28359254006702bcfe15cb754c96fba7efaae5fb | 397 | hpp | C++ | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | //
// sin.hpp
//
//
// Created by Himatya on 2015/12/18.
// Copyright (c) 2015 Himatya. All rights reserved.
//
#pragma once
#include <type_traits>
#include <mk2/math/cos.hpp>
namespace mk2{
namespace math{
template<class T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
inline constexpr T sin(T x){
return cos(x - math::half_pi<T>);
}
}
}
| 17.26087 | 97 | 0.649874 |
2836bc8a211175328048c71d425b69e73c5cceb8 | 1,015 | cpp | C++ | src/chatterbox_1.1.0/lib/Manual/Pots.cpp | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | 2 | 2021-02-19T22:30:59.000Z | 2021-03-19T19:07:36.000Z | src/chatterbox_1.1.0/lib/Manual/Pots.cpp | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | null | null | null | src/chatterbox_1.1.0/lib/Manual/Pots.cpp | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <Wavetable.h>
#include <Pots.h>
#include <Pot.h>
Pots::Pots()
{
}
void Pots::init()
{
// float tablesize = (float)TABLESIZE; // move
potArray[POT_P0] = Pot("f1f", 36);
potArray[POT_P1] = Pot("f2f", 39);
potArray[POT_P2] = Pot("f3f", 32);
potArray[POT_P3] = Pot("f3q", 33);
potArray[POT_P4] = Pot("larynx", 34);
potArray[POT_P5] = Pot("pitch", 35);
for (int i = 0; i < N_POTS_ACTUAL; i++)
{
adcAttachPin(potArray[i].channel());
}
potArray[POT_P0].range(ADC_TOP, F1F_LOW, F1F_HIGH);
potArray[POT_P1].range(ADC_TOP, F2F_LOW, F2F_HIGH);
potArray[POT_P2].range(ADC_TOP, F3F_LOW, F3F_HIGH);
potArray[POT_P3].range(ADC_TOP, F3Q_MIN, F3Q_MAX);
potArray[POT_P4].range(ADC_TOP, tablesize * LARYNX_MIN / 100.0f, tablesize * LARYNX_MAX / 100.0f);
potArray[POT_P5].range(ADC_TOP, PITCH_MIN, PITCH_MAX);
potArray[POT_GROWL].range(ADC_TOP, GROWL_MAX, GROWL_MIN);
}
Pot &Pots::getPot(int n)
{
return potArray[n];
} | 25.375 | 102 | 0.64532 |
2836e0aee839529b28bec1912dfa074e4306a4fa | 34 | cpp | C++ | 2D_Processing/src/LineStrip.cpp | Epono/5A-3DJV-2D_Processing | de64ef4c851775abd87a00db526c98ec41124dc2 | [
"MIT"
] | null | null | null | 2D_Processing/src/LineStrip.cpp | Epono/5A-3DJV-2D_Processing | de64ef4c851775abd87a00db526c98ec41124dc2 | [
"MIT"
] | null | null | null | 2D_Processing/src/LineStrip.cpp | Epono/5A-3DJV-2D_Processing | de64ef4c851775abd87a00db526c98ec41124dc2 | [
"MIT"
] | null | null | null | #include "../headers/LineStrip.h"
| 17 | 33 | 0.705882 |
2837ca8e718fbb7d3c28209ed54b6039e3f1c823 | 17,969 | hxx | C++ | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbLabelImageRegionMergingFilter_hxx
#define otbLabelImageRegionMergingFilter_hxx
#include "otbLabelImageRegionMergingFilter.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
namespace otb
{
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageRegionMergingFilter()
{
m_RangeBandwidth = 1.0;
m_NumberOfComponentsPerPixel = 0;
this->SetNumberOfRequiredInputs(2);
this->SetNumberOfRequiredOutputs(2);
this->SetNthOutput(0, OutputLabelImageType::New());
this->SetNthOutput(1, OutputClusteredImageType::New());
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputLabelImage(
const TInputLabelImage* labelImage)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(0, const_cast<TInputLabelImage*>(labelImage));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputSpectralImage(
const TInputSpectralImage* spectralImage)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(1, const_cast<TInputSpectralImage*>(spectralImage));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TInputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputLabelImage()
{
return dynamic_cast<TInputLabelImage*>(itk::ProcessObject::GetInput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TInputSpectralImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputSpectralImage()
{
return dynamic_cast<TInputSpectralImage*>(itk::ProcessObject::GetInput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::~LabelImageRegionMergingFilter()
{
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput()
{
if (this->GetNumberOfOutputs() < 1)
{
return nullptr;
}
return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
const TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput() const
{
if (this->GetNumberOfOutputs() < 1)
{
return 0;
}
return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType*
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput()
{
if (this->GetNumberOfOutputs() < 2)
{
return nullptr;
}
return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
const typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType*
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput() const
{
if (this->GetNumberOfOutputs() < 2)
{
return 0;
}
return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
unsigned int numberOfComponentsPerPixel = this->GetInputSpectralImage()->GetNumberOfComponentsPerPixel();
if (this->GetClusteredOutput())
{
this->GetClusteredOutput()->SetNumberOfComponentsPerPixel(numberOfComponentsPerPixel);
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::EnlargeOutputRequestedRegion(
itk::DataObject* itkNotUsed(output))
{
// This filter requires all of the output images in the buffer.
for (unsigned int j = 0; j < this->GetNumberOfOutputs(); j++)
{
if (this->itk::ProcessObject::GetOutput(j))
{
this->itk::ProcessObject::GetOutput(j)->SetRequestedRegionToLargestPossibleRegion();
}
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateData()
{
typename InputSpectralImageType::Pointer spectralImage = this->GetInputSpectralImage();
typename InputLabelImageType::Pointer inputLabelImage = this->GetInputLabelImage();
typename OutputLabelImageType::Pointer outputLabelImage = this->GetLabelOutput();
typename OutputClusteredImageType::Pointer outputClusteredImage = this->GetClusteredOutput();
// Allocate output
outputLabelImage->SetBufferedRegion(outputLabelImage->GetRequestedRegion());
outputLabelImage->Allocate();
outputClusteredImage->SetBufferedRegion(outputClusteredImage->GetRequestedRegion());
outputClusteredImage->Allocate();
m_NumberOfComponentsPerPixel = spectralImage->GetNumberOfComponentsPerPixel();
// std::cout << "Copy input label image to output label image" << std::endl;
// Copy input label image to output label image
typename itk::ImageRegionConstIterator<InputLabelImageType> inputIt(inputLabelImage, outputLabelImage->GetRequestedRegion());
typename itk::ImageRegionIterator<OutputLabelImageType> outputIt(outputLabelImage, outputLabelImage->GetRequestedRegion());
inputIt.GoToBegin();
outputIt.GoToBegin();
while (!inputIt.IsAtEnd())
{
outputIt.Set(inputIt.Get());
++inputIt;
++outputIt;
}
RegionAdjacencyMapType regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage);
unsigned int regionCount = regionAdjacencyMap.size() - 1;
// Initialize arrays for mode information
m_CanonicalLabels.clear();
m_CanonicalLabels.resize(regionCount + 1);
m_Modes.clear();
m_Modes.reserve(regionCount + 1);
for (unsigned int i = 0; i < regionCount + 1; ++i)
{
m_Modes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel));
}
m_PointCounts.clear();
m_PointCounts.resize(regionCount + 1); // = std::vector<unsigned int>(regionCount+1);
// Associate each label to a spectral value, a canonical label and a point count
typename itk::ImageRegionConstIterator<InputLabelImageType> inputItWithIndex(inputLabelImage, outputLabelImage->GetRequestedRegion());
inputItWithIndex.GoToBegin();
while (!inputItWithIndex.IsAtEnd())
{
LabelType label = inputItWithIndex.Get();
// if label has not been initialized yet ..
if (m_PointCounts[label] == 0)
{
// m_CanonicalLabels[label] = label;
m_Modes[label] = spectralImage->GetPixel(inputItWithIndex.GetIndex());
}
m_PointCounts[label]++;
++inputItWithIndex;
}
// Region Merging
bool finishedMerging = false;
unsigned int mergeIterations = 0;
// std::cout << "Start merging" << std::endl;
// Iterate until no more merge to do
// while(!finishedMerging)
// {
while (!finishedMerging)
{
// Initialize Canonical Labels
for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel)
m_CanonicalLabels[curLabel] = curLabel;
// Iterate over all regions
for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel)
{
if (m_PointCounts[curLabel] == 0)
{
// do not process empty regions
continue;
}
// std::cout<<" point in label "<<curLabel<<" "<<m_PointCounts[curLabel]<<std::endl;
const SpectralPixelType& curSpectral = m_Modes[curLabel];
// Iterate over all adjacent regions and check for merge
typename AdjacentLabelsContainerType::const_iterator adjIt = regionAdjacencyMap[curLabel].begin();
while (adjIt != regionAdjacencyMap[curLabel].end())
{
LabelType adjLabel = *adjIt;
assert(adjLabel <= regionCount);
const SpectralPixelType& adjSpectral = m_Modes[adjLabel];
// Check condition to merge regions
bool isSimilar = true;
RealType norm2 = 0;
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
RealType e;
e = (curSpectral[comp] - adjSpectral[comp]) / m_RangeBandwidth;
norm2 += e * e;
}
isSimilar = norm2 < 0.25;
if (isSimilar)
{
// Find canonical label for current region
LabelType curCanLabel = curLabel; // m_CanonicalLabels[curLabel];
while (m_CanonicalLabels[curCanLabel] != curCanLabel)
{
curCanLabel = m_CanonicalLabels[curCanLabel];
}
// Find canonical label for adjacent region
LabelType adjCanLabel = adjLabel; // m_CanonicalLabels[curLabel];
while (m_CanonicalLabels[adjCanLabel] != adjCanLabel)
{
adjCanLabel = m_CanonicalLabels[adjCanLabel];
}
// Assign same canonical label to both regions
if (curCanLabel < adjCanLabel)
{
m_CanonicalLabels[adjCanLabel] = curCanLabel;
}
else
{
m_CanonicalLabels[m_CanonicalLabels[curCanLabel]] = adjCanLabel;
m_CanonicalLabels[curCanLabel] = adjCanLabel;
}
}
++adjIt;
} // end of loop over adjacent labels
} // end of loop over labels
// std::cout << "Simplify the table of canonical labels" << std::endl;
/* Simplify the table of canonical labels */
for (LabelType i = 1; i < regionCount + 1; ++i)
{
LabelType can = i;
while (m_CanonicalLabels[can] != can)
{
can = m_CanonicalLabels[can];
}
m_CanonicalLabels[i] = can;
}
// std::cout << "merge regions with same canonical label" << std::endl;
/* Merge regions with same canonical label */
/* - update modes and point counts */
std::vector<SpectralPixelType> newModes;
newModes.reserve(regionCount + 1); //(regionCount+1, SpectralPixelType(m_NumberOfComponentsPerPixel));
for (unsigned int i = 0; i < regionCount + 1; ++i)
{
newModes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel));
}
std::vector<unsigned int> newPointCounts(regionCount + 1);
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
newModes[i].Fill(0);
newPointCounts[i] = 0;
}
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
LabelType canLabel = m_CanonicalLabels[i];
unsigned int nPoints = m_PointCounts[i];
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
newModes[canLabel][comp] += nPoints * m_Modes[i][comp];
}
newPointCounts[canLabel] += nPoints;
}
// std::cout << "re-labeling" << std::endl;
/* re-labeling */
std::vector<LabelType> newLabels(regionCount + 1);
std::vector<bool> newLabelSet(regionCount + 1);
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
newLabelSet[i] = false;
}
LabelType label = 0;
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
LabelType canLabel = m_CanonicalLabels[i];
if (newLabelSet[canLabel] == false)
{
newLabelSet[canLabel] = true;
label++;
newLabels[canLabel] = label;
unsigned int nPoints = newPointCounts[canLabel];
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
m_Modes[label][comp] = newModes[canLabel][comp] / nPoints;
}
m_PointCounts[label] = newPointCounts[canLabel];
}
}
unsigned int oldRegionCount = regionCount;
regionCount = label;
/* reassign labels in label image */
outputIt.GoToBegin();
while (!outputIt.IsAtEnd())
{
LabelType l = outputIt.Get();
LabelType canLabel;
assert(m_CanonicalLabels[l] <= oldRegionCount);
canLabel = newLabels[m_CanonicalLabels[l]];
outputIt.Set(canLabel);
++outputIt;
}
finishedMerging = oldRegionCount == regionCount || mergeIterations >= 10 || regionCount == 1;
// only one iteration for now
if (!finishedMerging)
{
/* Update adjacency table */
regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage);
}
mergeIterations++;
} // end of main iteration loop
// std::cout << "merge iterations: " << mergeIterations << std::endl;
// std::cout << "number of label objects: " << regionCount << std::endl;
// Generate clustered output
itk::ImageRegionIterator<OutputClusteredImageType> outputClusteredIt(outputClusteredImage, outputClusteredImage->GetRequestedRegion());
outputClusteredIt.GoToBegin();
outputIt.GoToBegin();
while (!outputClusteredIt.IsAtEnd())
{
LabelType label = outputIt.Get();
const SpectralPixelType& p = m_Modes[label];
outputClusteredIt.Set(p);
++outputClusteredIt;
++outputIt;
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::PrintSelf(std::ostream& os,
itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Range bandwidth: " << m_RangeBandwidth << std::endl;
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::RegionAdjacencyMapType
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageToRegionAdjacencyMap(
typename OutputLabelImageType::Pointer labelImage)
{
// declare the output map
RegionAdjacencyMapType ram;
// Find the maximum label value
itk::ImageRegionConstIterator<OutputLabelImageType> it(labelImage, labelImage->GetRequestedRegion());
it.GoToBegin();
LabelType maxLabel = 0;
while (!it.IsAtEnd())
{
LabelType label = it.Get();
maxLabel = std::max(maxLabel, label);
++it;
}
// Set the size of the adjacency map
ram.resize(maxLabel + 1);
// set the image region without bottom and right borders so that bottom and
// right neighbors always exist
RegionType regionWithoutBottomRightBorders = labelImage->GetRequestedRegion();
SizeType size = regionWithoutBottomRightBorders.GetSize();
for (unsigned int d = 0; d < ImageDimension; ++d)
size[d] -= 1;
regionWithoutBottomRightBorders.SetSize(size);
itk::ImageRegionConstIteratorWithIndex<OutputLabelImageType> inputIt(labelImage, regionWithoutBottomRightBorders);
inputIt.GoToBegin();
while (!inputIt.IsAtEnd())
{
const InputIndexType& index = inputIt.GetIndex();
LabelType label = inputIt.Get();
// check neighbors
for (unsigned int d = 0; d < ImageDimension; ++d)
{
InputIndexType neighborIndex = index;
neighborIndex[d]++;
LabelType neighborLabel = labelImage->GetPixel(neighborIndex);
// add adjacency if different labels
if (neighborLabel != label)
{
ram[label].insert(neighborLabel);
ram[neighborLabel].insert(label);
}
}
++inputIt;
}
return ram;
}
} // end namespace otb
#endif
| 38.069915 | 159 | 0.718181 |
28387227adf8dd2d42870d9474af4f96725dc1d4 | 2,120 | cpp | C++ | solved-codeforces/the_redback/contest/749/c/23155481.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-codeforces/the_redback/contest/749/c/23155481.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-codeforces/the_redback/contest/749/c/23155481.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define sf(a) scanf("%lld",&a)
#define ssf(a) scanf("%s",&a)
#define sf2(a,b) scanf("%lld %lld",&a,&b)
#define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#ifdef redback
#define bug printf("line=%d\n",__LINE__);
#define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;}
struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg;
#else
#define bug
#define debug(args...)
#endif //debugging macros
struct node
{
int w;
node(){}
node(int b) {w = b;}
bool operator < ( const node& p ) const { return w > p.w; }
};
priority_queue<node>R,D;
char a[200010];
ll b[200010];
int main()
{
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
ll t=1,tc;
//sf(tc);
ll l,m,n;
while(~sf(n)) {
ll i,j,k;
R=priority_queue<node>();
D=priority_queue<node>();
mem(b,-1);
ssf(a);
for(i=0;i<n;i++)
{
if(a[i]=='D') D.push(node(i));
if(a[i]=='R') R.push(node(i));
}
while(!R.empty() && !D.empty())
{
node rr=R.top();
node dd=D.top();
R.pop();
D.pop();
if(rr.w<dd.w)
{
R.push(node(rr.w+n));
}
else
D.push(node(dd.w+n));
}
if(!R.empty()) puts("R");
else puts("D");
}
return 0;
}
| 22.083333 | 102 | 0.49434 |
2838a15aef565c77fc2e1f02155ebe31e09a2244 | 12,215 | cpp | C++ | applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/image/imagetoolbox/depth/depthimagetoolboxaction.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | #include "depthimagetoolbox.h"
#include "depthimagetoolboxaction.h"
#include <QString>
#include <QLabel>
namespace sofa
{
namespace gui
{
namespace qt
{
int DepthRowImageToolBoxAction::numindex=0;
DepthImageToolBoxAction::DepthImageToolBoxAction(sofa::component::engine::LabelImageToolBox* lba,QObject *parent):
LabelImageToolBoxAction(lba,parent)
{
/* QGroupBox *gb = new QGroupBox();
gb->setTitle("Main Commands");
QHBoxLayout *hb = new QHBoxLayout();
//button selection point
select = new QPushButton("Select Point");
hb->addWidget(select);
//this->addWidget(select);
select->setCheckable(true);
connect(select,SIGNAL(toggled(bool)),this,SLOT(selectionPointButtonClick(bool)));
QPushButton* section = new QPushButton("Go to");
hb->addWidget(section);
//this->addWidget(section);
connect(section,SIGNAL(clicked()),this,SLOT(sectionButtonClick()));
gb->setLayout(hb);
this->addWidget(gb);*/
createMainCommands();
//createInfoWidget();
//createBoxCommands();
//createGridCommands();
//createNormalCommands();
createListLayers();
//executeButtonClick();
}
void DepthImageToolBoxAction::createMainCommands()
{
QGroupBox *gb = new QGroupBox("Main Commands");
QHBoxLayout *hb = new QHBoxLayout();
// QPushButton *reloadButton = new QPushButton("Reload");
//QPushButton *executeButton = new QPushButton("Execute");
// hb->addWidget(reloadButton);
//hb->addWidget(executeButton);
QHBoxLayout *hb2 = new QHBoxLayout();
QPushButton *saveParamButton = new QPushButton("Save params");
QPushButton *loadParamButton = new QPushButton("Load params");
QPushButton *saveSceneButton = new QPushButton("Save SCN");
connect(saveParamButton,SIGNAL(clicked()),this,SLOT(saveButtonClick()));
connect(loadParamButton,SIGNAL(clicked()),this,SLOT(loadButtonClick()));
connect(saveSceneButton,SIGNAL(clicked()),this,SLOT(saveSceneButtonClick()));
hb2->addWidget(saveParamButton);
hb2->addWidget(loadParamButton);
QHBoxLayout *hb3 = new QHBoxLayout();
hb3->addWidget(saveSceneButton);
QVBoxLayout *vb =new QVBoxLayout();
vb->addLayout(hb);
vb->addLayout(hb2);
vb->addLayout(hb3);
gb->setLayout(vb);
this->addWidget(gb);
}
void DepthImageToolBoxAction::createListLayers()
{
std::cout<<"nnn "<<std::endl;
sofa::component::engine::DepthImageToolBox *l = DITB();
unsigned int numberGrid = l->labelsOfGrid.size();
QGroupBox * gp = new QGroupBox("List of Layers");
QFormLayout *form = new QFormLayout();
form->addRow("numbers of Grids:",new QLabel(QString::number(numberGrid)));
listLayers = new QTableWidget();
listLayers->insertColumn(0);
listLayers->insertColumn(1);
listLayers->insertColumn(2);
listLayers->insertColumn(3);
QStringList header; header << "name" << "geometry" << "grid1" << "grid2";
listLayers->setHorizontalHeaderLabels(header);
QPushButton *listLayersAdd = new QPushButton("Add");
connect(listLayersAdd,SIGNAL(clicked()),this,SLOT(createNewRow()));
QPushButton *listLayersRem = new QPushButton("remove");
QPushButton *listLayersGenerate = new QPushButton("generate");
connect(listLayersGenerate,SIGNAL(clicked()),this,SLOT(executeButtonClick()));
QHBoxLayout * hb = new QHBoxLayout();
hb->addWidget(listLayersAdd);
hb->addWidget(listLayersRem);
QVBoxLayout *vb = new QVBoxLayout();
vb->addLayout(form);
vb->addWidget(listLayers);
vb->addLayout(hb);
vb->addWidget(listLayersGenerate);
gp->setLayout(vb);
if(numberGrid==0)
{
listLayersAdd->setEnabled(false);
listLayersRem->setEnabled(false);
//listLayers->setEnabled(false);
}
this->addWidget(gp);
}
void DepthImageToolBoxAction::createNewRow(int layer)
{
sofa::component::engine::DepthImageToolBox *d = DITB();
sofa::component::engine::DepthImageToolBox::Layer &l = d->layers[layer];
this->createNewRow();
DepthRowImageToolBoxAction *row = listRows.back();
QString offset1;offsetToText(offset1,l.offset1,l.typeOffset1);
QString offset2;offsetToText(offset2,l.offset2,l.typeOffset2);
row->setValue(QString::fromStdString(l.name), l.layer1, offset1, l.layer2, offset2, l.base,l.nbSlice);
}
void DepthImageToolBoxAction::createNewRow()
{
//std::cout << "createNewRow"<<std::endl;
sofa::component::engine::DepthImageToolBox *l = DITB();
DepthRowImageToolBoxAction *row = new DepthRowImageToolBoxAction(listRows.size());
row->setParameters(l->labelsOfGrid);
row->toTableWidgetRow(listLayers);
listLayers->update();
l->createLayer();
//std::cout << l->layers.size()<<std::endl;
this->connect(row,SIGNAL(valueChanged(int,QString,int,QString,int,QString,int,int)),this,SLOT(changeRow(int,QString,int,QString,int,QString,int,int)));
row->change();
listRows.push_back(row);
}
void DepthImageToolBoxAction::offsetToText(QString &out, double outValue, int type)
{
switch(type)
{
case DepthImageToolBox::Layer::Distance:
out = QString::number(outValue);
break;
case DepthImageToolBox::Layer::Percent:
out = QString::number(outValue*100) +"%";
break;
}
return;
}
void DepthImageToolBoxAction::textToOffset(QString text, double &outValue, int &type)
{
bool ok;
outValue = text.toDouble(&ok);
if(ok)
{
type = sofa::component::engine::DepthImageToolBox::Layer::Distance;
return;
}
if(text.contains("%"))
{
text.replace("%","");
outValue = text.toDouble(&ok);
outValue *= 0.01;
if(ok)
{
type = sofa::component::engine::DepthImageToolBox::Layer::Percent;
return;
}
}
outValue = 0;
type = sofa::component::engine::DepthImageToolBox::Layer::Distance;
return;
}
void DepthImageToolBoxAction::changeRow(int index,QString name,int layer1,QString offset1,int layer2,QString offset2,int base,int nbSlice)
{
//std::cout << "DepthImageToolBoxAction::changeRow " << index << " "<< name.toStdString() << " "<<layer1<<" "<<offset1.toStdString()<<" "<<layer2<<" "<<offset2.toStdString()<<std::endl;
sofa::component::engine::DepthImageToolBox *l = DITB();
if(l->layers.size()<=(unsigned int)index)return;
sofa::component::engine::DepthImageToolBox::Layer &layer = l->layers[index];
layer.name = name.toStdString();
layer.layer1 = layer1;
layer.layer2 = layer2;
layer.base = base;
layer.nbSlice = nbSlice;
textToOffset(offset1,layer.offset1,layer.typeOffset1);
textToOffset(offset2,layer.offset2,layer.typeOffset2);
//std::cout << layer.name << " " << layer.offset1 << " " << layer.typeOffset1 <<layer.offset2 << " " << layer.typeOffset2 <<std::endl;
}
DepthImageToolBoxAction::~DepthImageToolBoxAction()
{
//delete select;
}
sofa::component::engine::DepthImageToolBox* DepthImageToolBoxAction::DITB()
{
return dynamic_cast<sofa::component::engine::DepthImageToolBox*>(this->p_label);
}
void DepthImageToolBoxAction::executeButtonClick()
{
sofa::component::engine::DepthImageToolBox *l = DITB();
l->executeAction();
//updateGraphs();
//std::cout << "exitButton"<<std::endl;
}
void DepthImageToolBoxAction::saveButtonClick()
{
//std::cout << "saveButtonClick"<<std::endl;
sofa::component::engine::DepthImageToolBox *l = DITB();
l->saveFile();
//updateGraphs();
//std::cout << "exitButton"<<std::endl;
}
void DepthImageToolBoxAction::loaduttonClick()
{
sofa::component::engine::DepthImageToolBox *l = DITB();
l->loadFile();
updateGraphs();
//std::cout << "exitButton"<<std::endl;
}
void DepthImageToolBoxAction::saveSceneButtonClick()
{
sofa::component::engine::DepthImageToolBox *l = DITB();
l->saveSCN();
}
void DepthImageToolBoxAction::selectionPointEvent(int /*mouseevent*/, const unsigned int /*axis*/,const sofa::defaulttype::Vec3d& /*imageposition*/,const sofa::defaulttype::Vec3d& /*position3D*/,const QString& /*value*/)
{
/*
select->setChecked(false);
disconnect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)));
sofa::component::engine::DepthImageToolBox* lp = LGITB();
lp->d_ip.setValue(imageposition);
lp->d_p.setValue(position3D);
lp->d_axis.setValue(axis);
lp->d_value.setValue(value.toStdString());
updateGraphs();*/
}
/*
void DepthImageToolBoxAction::selectionPointButtonClick(bool b)
{
if(b)
{
//select->setChecked(true);
connect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)));
}
else
{
//select->setChecked(false);
disconnect(this,SIGNAL(clickImage(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)),this,SLOT(selectionPointEvent(int,unsigned int,sofa::defaulttype::Vec3d,sofa::defaulttype::Vec3d,QString)));
}
}*/
void DepthImageToolBoxAction::addOnGraphs()
{
// std::cout << "addOnGraph"<<std::endl;
path[0] = GraphXY->addPath(QPainterPath());
path[1] = GraphXZ->addPath(QPainterPath());
path[2] = GraphZY->addPath(QPainterPath());
for(int i=0;i<3;i++)
{
path[i]->setVisible(true);
}
updateColor();
}
void DepthImageToolBoxAction::moveTo(const unsigned int axis,const sofa::defaulttype::Vec3d& imageposition)
{
QPainterPath poly;
int ximage,yimage;
switch(axis)
{
case 0:
ximage = 0; yimage = 1;
break;
case 1:
ximage = 0; yimage = 2;
break;
case 2:
ximage = 2; yimage = 1;
break;
default:
return;
}
poly = path[axis]->path();
poly.moveTo(imageposition[ximage],imageposition[yimage]);
path[axis]->setPath(poly);
}
void DepthImageToolBoxAction::lineTo(const unsigned int axis,const sofa::defaulttype::Vec3d& imageposition)
{
QPainterPath poly;
int ximage,yimage;
switch(axis)
{
case 0:
ximage = 0; yimage = 1;
break;
case 1:
ximage = 0; yimage = 2;
break;
case 2:
ximage =2; yimage = 1;
break;
default:
return;
}
poly = path[axis]->path();
poly.lineTo(imageposition[ximage],imageposition[yimage]);
path[axis]->setPath(poly);
}
void DepthImageToolBoxAction::updateGraphs()
{
sofa::component::engine::DepthImageToolBox *l = DITB();
listLayers->clear();
listRows.clear();
for(unsigned int i=0;i<l->layers.size();i++)
{
this->createNewRow(i);
}
//int axis = l->d_axis.getValue();
//this->setAxis(axis);
/*helper::vector<sofa::defaulttype::Vec3d>& pos = *(l->d_outImagePosition.beginEdit());
sofa::component::engine::DepthImageToolBox::Edges& edges = *(l->d_outEdges.beginEdit());
path[0]->setPath(QPainterPath());
path[1]->setPath(QPainterPath());
path[2]->setPath(QPainterPath());
for(unsigned int i=0;i<edges.size();i++)
{
sofa::defaulttype::Vec3d p1 = pos[edges[i][0]];
sofa::defaulttype::Vec3d p2 = pos[edges[i][1]];
moveTo(0,p1);
moveTo(1,p1);
moveTo(2,p1);
lineTo(0,p2);
lineTo(1,p2);
lineTo(2,p2);
}*/
}
void DepthImageToolBoxAction::updateColor()
{
for(int i=0;i<3;i++)
{
path[i]->setPen(QPen(this->color()));
}
}
/*
void DepthImageToolBoxAction::sectionButtonClick()
{
// std::cout << "DepthImageToolBoxAction::sectionButtonClick()"<<std::endl;
sofa::defaulttype::Vec3d pos = LGITB()->d_ip.getValue();
sofa::defaulttype::Vec3i pos2(round(pos.x()),round(pos.y()),round(pos.z()));
emit sectionChanged(pos2);
}*/
SOFA_DECL_CLASS(DepthImageToolBoxAction)
}
}
}
| 26.439394 | 227 | 0.654032 |
283a534e855eb822e3a85e59fcc8f8cf13f9b13d | 2,116 | cc | C++ | shell/common/asar/scoped_temporary_file.cc | TarunavBA/electron | a41898bb9b889486fb93c11b7107b9412818133a | [
"MIT"
] | 88,283 | 2016-04-04T19:29:13.000Z | 2022-03-31T23:33:33.000Z | shell/common/asar/scoped_temporary_file.cc | TarunavBA/electron | a41898bb9b889486fb93c11b7107b9412818133a | [
"MIT"
] | 27,327 | 2016-04-04T19:38:58.000Z | 2022-03-31T22:34:10.000Z | shell/common/asar/scoped_temporary_file.cc | TarunavBA/electron | a41898bb9b889486fb93c11b7107b9412818133a | [
"MIT"
] | 15,972 | 2016-04-04T19:32:06.000Z | 2022-03-31T08:54:00.000Z | // Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/asar/scoped_temporary_file.h"
#include <vector>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/threading/thread_restrictions.h"
#include "shell/common/asar/asar_util.h"
namespace asar {
ScopedTemporaryFile::ScopedTemporaryFile() = default;
ScopedTemporaryFile::~ScopedTemporaryFile() {
if (!path_.empty()) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
// On Windows it is very likely the file is already in use (because it is
// mostly used for Node native modules), so deleting it now will halt the
// program.
#if defined(OS_WIN)
base::DeleteFileAfterReboot(path_);
#else
base::DeleteFile(path_);
#endif
}
}
bool ScopedTemporaryFile::Init(const base::FilePath::StringType& ext) {
if (!path_.empty())
return true;
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!base::CreateTemporaryFile(&path_))
return false;
#if defined(OS_WIN)
// Keep the original extension.
if (!ext.empty()) {
base::FilePath new_path = path_.AddExtension(ext);
if (!base::Move(path_, new_path))
return false;
path_ = new_path;
}
#endif
return true;
}
bool ScopedTemporaryFile::InitFromFile(
base::File* src,
const base::FilePath::StringType& ext,
uint64_t offset,
uint64_t size,
const absl::optional<IntegrityPayload>& integrity) {
if (!src->IsValid())
return false;
if (!Init(ext))
return false;
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::vector<char> buf(size);
int len = src->Read(offset, buf.data(), buf.size());
if (len != static_cast<int>(size))
return false;
if (integrity.has_value()) {
ValidateIntegrityOrDie(buf.data(), buf.size(), integrity.value());
}
base::File dest(path_, base::File::FLAG_OPEN | base::File::FLAG_WRITE);
if (!dest.IsValid())
return false;
return dest.WriteAtCurrentPos(buf.data(), buf.size()) ==
static_cast<int>(size);
}
} // namespace asar
| 25.190476 | 77 | 0.690926 |
283a71c9583a82d67aa9059ac89118881af9ce63 | 47,507 | cpp | C++ | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | 1 | 2020-12-11T03:28:32.000Z | 2020-12-11T03:28:32.000Z | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null | // Copyright (c) 2019-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 <array>
#include <thread>
#include <numeric>
#include "utils.h"
#include "report.h"
#include "conformance_utils.h"
#include "conformance_framework.h"
#include "composition_utils.h"
#include <catch2/catch.hpp>
#include <openxr/openxr.h>
#include <xr_linear.h>
using namespace Conformance;
namespace
{
const XrVector3f Up{0, 1, 0};
enum class LayerMode
{
Scene,
Help,
Complete
};
namespace Colors
{
constexpr XrColor4f Red = {1, 0, 0, 1};
constexpr XrColor4f Green = {0, 1, 0, 1};
constexpr XrColor4f Blue = {0, 0, 1, 1};
constexpr XrColor4f Purple = {1, 0, 1, 1};
constexpr XrColor4f Yellow = {1, 1, 0, 1};
constexpr XrColor4f Orange = {1, 0.65f, 0, 1};
constexpr XrColor4f White = {1, 1, 1, 1};
constexpr XrColor4f Transparent = {0, 0, 0, 0};
// Avoid including red which is a "failure color".
constexpr std::array<XrColor4f, 4> UniqueColors{Green, Blue, Yellow, Orange};
} // namespace Colors
namespace Math
{
// Do a linear conversion of a number from one range to another range.
// e.g. 5 in range [0-8] projected into range (-.6 to 0.6) is 0.15.
float LinearMap(int i, int sourceMin, int sourceMax, float targetMin, float targetMax)
{
float percent = (i - sourceMin) / (float)sourceMax;
return targetMin + ((targetMax - targetMin) * percent);
}
constexpr float DegToRad(float degree)
{
return degree / 180 * MATH_PI;
}
} // namespace Math
namespace Quat
{
constexpr XrQuaternionf Identity{0, 0, 0, 1};
XrQuaternionf FromAxisAngle(XrVector3f axis, float radians)
{
XrQuaternionf rowQuat;
XrQuaternionf_CreateFromAxisAngle(&rowQuat, &axis, radians);
return rowQuat;
}
} // namespace Quat
// Appends composition layers for interacting with interactive composition tests.
struct InteractiveLayerManager
{
InteractiveLayerManager(CompositionHelper& compositionHelper, const char* exampleImage, const char* descriptionText)
: m_compositionHelper(compositionHelper)
{
// Set up the input system for toggling between modes and passing/failing.
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "interaction_test");
strcpy(actionSetInfo.localizedActionSetName, "Interaction Test");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &m_actionSet));
compositionHelper.GetInteractionManager().AddActionSet(m_actionSet);
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
strcpy(actionInfo.actionName, "interaction_manager_select");
strcpy(actionInfo.localizedActionName, "Interaction Manager Select");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_select));
strcpy(actionInfo.actionName, "interaction_manager_menu");
strcpy(actionInfo.localizedActionName, "Interaction Manager Menu");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_menu));
XrPath simpleInteractionProfile =
StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/select/click")},
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/select/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/menu/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/menu/click")},
}});
}
m_viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{{0, 0, 0, 1}, {0, 0, 0}});
// Load example screenshot if available and set up the quad layer for it.
{
XrSwapchain exampleSwapchain;
if (exampleImage) {
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(RGBAImage::Load(exampleImage), true /* sRGB */);
}
else {
RGBAImage image(256, 256);
image.PutText(XrRect2Di{{0, image.height / 2}, {image.width, image.height}}, "Example Not Available", 64, {1, 0, 0, 1});
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(image);
}
// Create a quad to the right of the help text.
m_exampleQuad = compositionHelper.CreateQuadLayer(exampleSwapchain, m_viewSpace, 1.25f, {Quat::Identity, {0.5f, 0, -1.5f}});
XrQuaternionf_CreateFromAxisAngle(&m_exampleQuad->pose.orientation, &Up, -15 * MATH_PI / 180);
}
// Set up the quad layer for showing the help text to the left of the example image.
m_descriptionQuad = compositionHelper.CreateQuadLayer(
m_compositionHelper.CreateStaticSwapchainImage(CreateTextImage(768, 768, descriptionText, 48)), m_viewSpace, 0.75f,
{Quat::Identity, {-0.5f, 0, -1.5f}});
m_descriptionQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
XrQuaternionf_CreateFromAxisAngle(&m_descriptionQuad->pose.orientation, &Up, 15 * MATH_PI / 180);
constexpr uint32_t actionsWidth = 768, actionsHeight = 128;
m_sceneActionsSwapchain = compositionHelper.CreateStaticSwapchainImage(
CreateTextImage(actionsWidth, actionsHeight, "Press Select to PASS. Press Menu for description", 48));
m_helpActionsSwapchain =
compositionHelper.CreateStaticSwapchainImage(CreateTextImage(actionsWidth, actionsHeight, "Press select to FAIL", 48));
// Set up the quad layer and swapchain for showing what actions the user can take in the Scene/Help mode.
m_actionsQuad =
compositionHelper.CreateQuadLayer(m_sceneActionsSwapchain, m_viewSpace, 0.75f, {Quat::Identity, {0, -0.4f, -1}});
m_actionsQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
}
template <typename T>
void AddLayer(T* layer)
{
m_sceneLayers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(layer));
}
bool EndFrame(const XrFrameState& frameState, std::vector<XrCompositionLayerBaseHeader*> layers = {})
{
bool keepRunning = AppendLayers(layers);
keepRunning &= m_compositionHelper.PollEvents();
m_compositionHelper.EndFrame(frameState.predictedDisplayTime, std::move(layers));
return keepRunning;
}
private:
bool AppendLayers(std::vector<XrCompositionLayerBaseHeader*>& layers)
{
// Add layer(s) based on the interaction mode.
switch (GetLayerMode()) {
case LayerMode::Scene:
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_sceneActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
for (auto& sceneLayer : m_sceneLayers) {
layers.push_back(sceneLayer);
}
break;
case LayerMode::Help:
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_descriptionQuad));
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_exampleQuad));
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_helpActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
break;
case LayerMode::Complete:
return false; // Interactive test is complete.
}
return true;
}
LayerMode GetLayerMode()
{
m_compositionHelper.GetInteractionManager().SyncActions(XR_NULL_PATH);
XrActionStateBoolean actionState{XR_TYPE_ACTION_STATE_BOOLEAN};
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO};
LayerMode mode = LayerMode::Scene;
getInfo.action = m_menu;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.currentState) {
mode = LayerMode::Help;
}
getInfo.action = m_select;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.changedSinceLastSync && actionState.currentState) {
if (mode != LayerMode::Scene) {
// Select on the non-Scene modes (help description/preview image) means FAIL and move to the next.
FAIL("User failed the interactive test");
}
// Select on scene means PASS and move to next
mode = LayerMode::Complete;
}
return mode;
}
CompositionHelper& m_compositionHelper;
XrActionSet m_actionSet;
XrAction m_select;
XrAction m_menu;
XrSpace m_viewSpace;
XrSwapchain m_sceneActionsSwapchain;
XrSwapchain m_helpActionsSwapchain;
XrCompositionLayerQuad* m_actionsQuad;
XrCompositionLayerQuad* m_descriptionQuad;
XrCompositionLayerQuad* m_exampleQuad;
std::vector<XrCompositionLayerBaseHeader*> m_sceneLayers;
};
} // namespace
namespace Conformance
{
// Purpose: Verify behavior of quad visibility and occlusion with the expectation that:
// 1. Quads render with painters algo.
// 2. Quads which are facing away are not visible.
TEST_CASE("Quad Occlusion", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Occlusion");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_occlusion.png",
"This test includes a blue and green quad at Z=-2 with opposite rotations on Y axis forming X. The green quad should be"
" fully visible due to painter's algorithm. A red quad is facing away and should not be visible.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain redSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Red);
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
// Each quad is rotated on Y axis by 45 degrees to form an X.
// Green is added second so it should draw over the blue quad.
const XrQuaternionf blueRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(-45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{blueRot, {0, 0, -2}}));
const XrQuaternionf greenRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{greenRot, {0, 0, -2}}));
// Red quad is rotated away from the viewer and should not be visible.
const XrQuaternionf redRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(180));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(redSwapchain, viewSpace, 1.0f, XrPosef{redRot, {0, 0, -1}}));
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Verify order of transforms by exercising the two ways poses can be specified:
// 1. A pose offset when creating the space
// 2. A pose offset when adding the layer
// If the poses are applied in an incorrect order, the quads will not rendener in the correct place or orientation.
TEST_CASE("Quad Poses", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Poses");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_poses.png",
"Render pairs of quads using similar poses to validate order of operations. The blue/green quads apply a"
" rotation around the Z axis on an XrSpace and then translate the quad out on the Z axis through the quad"
" layer's pose. The purple/yellow quads apply the same translation on the XrSpace and the rotation on the"
" quad layer's pose.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain orangeSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Orange);
const XrSwapchain yellowSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Yellow);
constexpr int RotationCount = 2;
constexpr float MaxRotationDegrees = 30;
// For each rotation there are a pair of quads.
static_assert(RotationCount * 2 <= XR_MIN_COMPOSITION_LAYERS_SUPPORTED, "Too many layers");
for (int i = 0; i < RotationCount; i++) {
const float radians =
Math::LinearMap(i, 0, RotationCount - 1, Math::DegToRad(-MaxRotationDegrees), Math::DegToRad(MaxRotationDegrees));
const XrPosef pose1 = XrPosef{Quat::FromAxisAngle({0, 1, 0}, radians), {0, 0, 0}};
const XrPosef pose2 = XrPosef{Quat::Identity, {0, 0, -1}};
const XrSpace viewSpacePose1 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose1);
const XrSpace viewSpacePose2 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose2);
auto quad1 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? blueSwapchain : greenSwapchain, viewSpacePose1, 0.25f, pose2);
interactiveLayerManager.AddLayer(quad1);
auto quad2 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? orangeSwapchain : yellowSwapchain, viewSpacePose2, 0.25f, pose1);
interactiveLayerManager.AddLayer(quad2);
}
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validates alpha blending (both premultiplied and unpremultiplied).
TEST_CASE("Source Alpha Blending", "[composition][interactive]")
{
CompositionHelper compositionHelper("Source Alpha Blending");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "source_alpha_blending.png",
"All three squares should have an identical blue-green gradient.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
constexpr float QuadZ = -3; // How far away quads are placed.
// Creates image with correctly combined green and blue gradient (this is the the source of truth).
{
Conformance::RGBAImage blueGradientOverGreen(256, 256);
for (int y = 0; y < 256; y++) {
const float t = y / 255.0f;
const XrColor4f dst = Colors::Green;
const XrColor4f src{0, 0, t, t};
const XrColor4f blended{dst.r * (1 - src.a) + src.r, dst.g * (1 - src.a) + src.g, dst.b * (1 - src.a) + src.b, 1};
blueGradientOverGreen.DrawRect(0, y, blueGradientOverGreen.width, 1, blended);
}
const XrSwapchain answerSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradientOverGreen);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(answerSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {0, 0, QuadZ}}));
}
auto createGradientTest = [&](bool premultiplied, float x, float y) {
// A solid green quad layer will be composited under a blue gradient.
{
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}}));
}
// Create gradient of blue lines from 0.0 to 1.0.
{
Conformance::RGBAImage blueGradient(256, 256);
for (int row = 0; row < blueGradient.height; row++) {
XrColor4f color{0, 0, 1, row / (float)blueGradient.height};
if (premultiplied) {
color = XrColor4f{color.r * color.a, color.g * color.a, color.b * color.a, color.a};
}
blueGradient.DrawRect(0, row, blueGradient.width, 1, color);
}
const XrSwapchain gradientSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradient);
XrCompositionLayerQuad* gradientQuad =
compositionHelper.CreateQuadLayer(gradientSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}});
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
if (!premultiplied) {
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_UNPREMULTIPLIED_ALPHA_BIT;
}
interactiveLayerManager.AddLayer(gradientQuad);
}
};
createGradientTest(true, -1.02f, 0); // Test premultiplied (left of center "answer")
createGradientTest(false, 1.02f, 0); // Test unpremultiplied (right of center "answer")
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validate eye visibility flags.
TEST_CASE("Eye Visibility", "[composition][interactive]")
{
CompositionHelper compositionHelper("Eye Visibility");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "eye_visibility.png",
"A green quad is shown in the left eye and a blue quad is shown in the right eye.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
XrCompositionLayerQuad* quad1 =
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {-1, 0, -2}});
quad1->eyeVisibility = XR_EYE_VISIBILITY_LEFT;
interactiveLayerManager.AddLayer(quad1);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
XrCompositionLayerQuad* quad2 =
compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {1, 0, -2}});
quad2->eyeVisibility = XR_EYE_VISIBILITY_RIGHT;
interactiveLayerManager.AddLayer(quad2);
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Subimage Tests", "[composition][interactive]")
{
CompositionHelper compositionHelper("Subimage Tests");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "subimage.png",
"Creates a 4x2 grid of quad layers testing subImage array index and imageRect. Red should not be visible except minor bleed in.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{Quat::Identity, {0, 0, -1}});
constexpr float QuadZ = -4; // How far away quads are placed.
constexpr int ImageColCount = 4;
constexpr int ImageArrayCount = 2;
constexpr int ImageWidth = 1024;
constexpr int ImageHeight = ImageWidth / ImageColCount;
constexpr int RedZoneBorderSize = 16;
constexpr int CellWidth = (ImageWidth / ImageColCount);
constexpr int CellHeight = CellWidth;
// Create an array swapchain
auto swapchainCreateInfo =
compositionHelper.DefaultColorSwapchainCreateInfo(ImageWidth, ImageHeight, XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT);
swapchainCreateInfo.format = GetGlobalData().graphicsPlugin->GetRGBA8Format(false /* sRGB */);
swapchainCreateInfo.arraySize = ImageArrayCount;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Render a grid of numbers (1,2,3,4) in slice 0 and (5,6,7,8) in slice 1 of the swapchain
// Create a quad layer referencing each number cell.
compositionHelper.AcquireWaitReleaseImage(swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
int number = 1;
for (int arraySlice = 0; arraySlice < ImageArrayCount; arraySlice++) {
Conformance::RGBAImage numberGridImage(ImageWidth, ImageHeight);
// All unused areas are red (should not be seen).
numberGridImage.DrawRect(0, 0, numberGridImage.width, numberGridImage.height, Colors::Red);
for (int x = 0; x < ImageColCount; x++) {
const auto& color = Colors::UniqueColors[number % Colors::UniqueColors.size()];
const XrRect2Di numberRect{{x * CellWidth + RedZoneBorderSize, RedZoneBorderSize},
{CellWidth - RedZoneBorderSize * 2, CellHeight - RedZoneBorderSize * 2}};
numberGridImage.DrawRect(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width, numberRect.extent.height,
Colors::Transparent);
numberGridImage.PutText(numberRect, std::to_string(number).c_str(), CellHeight, color);
numberGridImage.DrawRectBorder(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width,
numberRect.extent.height, 4, color);
number++;
const float quadX = Math::LinearMap(x, 0, ImageColCount - 1, -2.0f, 2.0f);
const float quadY = Math::LinearMap(arraySlice, 0, ImageArrayCount - 1, 0.75f, -0.75f);
XrCompositionLayerQuad* const quad =
compositionHelper.CreateQuadLayer(swapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {quadX, quadY, QuadZ}});
quad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
quad->subImage.imageArrayIndex = arraySlice;
quad->subImage.imageRect = numberRect;
quad->size.height = 1.0f; // Height needs to be corrected since the imageRect is customized.
interactiveLayerManager.AddLayer(quad);
}
GetGlobalData().graphicsPlugin->CopyRGBAImage(swapchainImage, format, arraySlice, numberGridImage);
}
});
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Projection Array Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Array Swapchain");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "projection_array.png",
"Uses a single texture array for a projection layer (each view is a different slice and each slice has a unique color).");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
// Because a single swapchain is being used for all views (each view is a slice of the texture array), the maximum dimensions must be used
// since the dimensions of all slices are the same.
const auto maxWidth = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectWidth < r.recommendedImageRectWidth;
})
->recommendedImageRectWidth;
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create swapchain with array type.
auto swapchainCreateInfo = compositionHelper.DefaultColorSwapchainCreateInfo(maxWidth, maxHeight);
swapchainCreateInfo.arraySize = (uint32_t)viewProperties.size() * 3;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Set up the projection layer
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
// Use non-contiguous array indices to ferret out any assumptions that implementations are making
// about array indices. In particular 0 != left and 1 != right, but this should test for other
// assumptions too.
uint32_t arrayIndex = swapchainCreateInfo.arraySize - (j * 2 + 1);
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = compositionHelper.MakeDefaultSubImage(swapchain, arrayIndex);
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each slice of the array swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
for (uint32_t slice = 0; slice < (uint32_t)views.size(); slice++) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage,
projLayer->views[slice].subImage.imageArrayIndex, format);
const_cast<XrFovf&>(projLayer->views[slice].fov) = views[slice].fov;
const_cast<XrPosef&>(projLayer->views[slice].pose) = views[slice].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[slice], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Wide Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Wide Swapchain");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_wide.png",
"Uses a single wide texture for a projection layer.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[view], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Separate Swapchains", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Separate Swapchains");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_separate.png",
"Uses separate textures for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
auto updateLayers = [&](const XrFrameState& frameState) {
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Quad Hands", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Hands");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "quad_hands.png",
"10x10cm Quads labeled \'L\' and \'R\' should appear 10cm along the grip "
"positive Z in front of the center of 10cm cubes rendered at the controller "
"grip poses. "
"The quads should face you and be upright when the controllers are in "
"a thumbs-up pointing-into-screen pose. "
"Check that the quads are properly backface-culled, "
"that \'R\' is always rendered atop \'L\', "
"and both are atop the cubes when visible.");
const std::vector<XrPath> subactionPaths{StringToPath(compositionHelper.GetInstance(), "/user/hand/left"),
StringToPath(compositionHelper.GetInstance(), "/user/hand/right")};
XrActionSet actionSet;
XrAction gripPoseAction;
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "quad_hands");
strcpy(actionSetInfo.localizedActionSetName, "Quad Hands");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &actionSet));
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT;
strcpy(actionInfo.actionName, "grip_pose");
strcpy(actionInfo.localizedActionName, "Grip pose");
actionInfo.subactionPaths = subactionPaths.data();
actionInfo.countSubactionPaths = (uint32_t)subactionPaths.size();
XRC_CHECK_THROW_XRCMD(xrCreateAction(actionSet, &actionInfo, &gripPoseAction));
}
compositionHelper.GetInteractionManager().AddActionSet(actionSet);
XrPath simpleInteractionProfile = StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/grip/pose")},
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/grip/pose")},
}});
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
// Spaces attached to the hand (subaction).
std::vector<XrSpace> gripSpaces;
// Create XrSpaces for each grip pose
for (XrPath subactionPath : subactionPaths) {
XrSpace space;
XrActionSpaceCreateInfo spaceCreateInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
spaceCreateInfo.action = gripPoseAction;
spaceCreateInfo.subactionPath = subactionPath;
spaceCreateInfo.poseInActionSpace = {{0, 0, 0, 1}, {0, 0, 0}};
XRC_CHECK_THROW_XRCMD(xrCreateActionSpace(compositionHelper.GetSession(), &spaceCreateInfo, &space));
gripSpaces.push_back(std::move(space));
}
// Create 10x10cm L and R quads
XrCompositionLayerQuad* const leftQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "L", 48)), gripSpaces[0],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
XrCompositionLayerQuad* const rightQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "R", 48)), gripSpaces[1],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
interactiveLayerManager.AddLayer(leftQuadLayer);
interactiveLayerManager.AddLayer(rightQuadLayer);
const XrVector3f cubeSize{0.1f, 0.1f, 0.1f};
auto updateLayers = [&](const XrFrameState& frameState) {
std::vector<Cube> cubes;
for (const auto& space : gripSpaces) {
XrSpaceLocation location{XR_TYPE_SPACE_LOCATION};
if (XR_SUCCEEDED(
xrLocateSpace(space, simpleProjectionLayerHelper.GetLocalSpace(), frameState.predictedDisplayTime, &location))) {
if ((location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) &&
(location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)) {
cubes.emplace_back(Cube{location.pose, cubeSize});
}
}
}
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState, cubes);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Mutable Field-of-View", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Mutable Field-of-View");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_mutable.png",
"Uses mutable field-of-views for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
if (!compositionHelper.GetViewConfigurationProperties().fovMutable) {
return;
}
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-.2f, -.2f, -2}), Cube::Make({.2f, -.2f, -2}), Cube::Make({0, .1f, -2})};
const XrVector3f Forward{0, 0, 1};
XrQuaternionf roll180;
XrQuaternionf_CreateFromAxisAngle(&roll180, &Forward, MATH_PI);
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
// Copy over the provided FOV and pose but use 40% of the suggested FOV.
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
const_cast<float&>(projLayer->views[view].fov.angleUp) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleDown) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleLeft) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleRight) *= 0.4f;
// Render using a 180 degree roll on Z which effectively creates a flip on both the X and Y axis.
XrCompositionLayerProjectionView rolled = projLayer->views[view];
XrQuaternionf_Multiply(&rolled.pose.orientation, &roll180, &views[view].pose.orientation);
GetGlobalData().graphicsPlugin->RenderView(rolled, swapchainImage, format, cubes);
// After rendering, report a flipped FOV on X and Y without the 180 degree roll, which has the same
// effect. This switcheroo is necessary since rendering with flipped FOV will result in an inverted
// winding causing normally hidden triangles to be visible and visible triangles to be hidden.
const_cast<float&>(projLayer->views[view].fov.angleUp) = -projLayer->views[view].fov.angleUp;
const_cast<float&>(projLayer->views[view].fov.angleDown) = -projLayer->views[view].fov.angleDown;
const_cast<float&>(projLayer->views[view].fov.angleLeft) = -projLayer->views[view].fov.angleLeft;
const_cast<float&>(projLayer->views[view].fov.angleRight) = -projLayer->views[view].fov.angleRight;
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
} // namespace Conformance
| 56.088548 | 146 | 0.636832 |
283a80924b2defc573734b3ff42e7e7384c9cffb | 9,532 | cpp | C++ | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* 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 <modules/base/rendering/renderablecartesianaxes.h>
#include <modules/base/basemodule.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
#include <openspace/documentation/verifier.h>
#include <ghoul/glm.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/opengl/programobject.h>
namespace {
constexpr const char* ProgramName = "CartesianAxesProgram";
const int NVertexIndices = 6;
constexpr openspace::properties::Property::PropertyInfo XColorInfo = {
"XColor",
"X Color",
"This value determines the color of the x axis."
};
constexpr openspace::properties::Property::PropertyInfo YColorInfo = {
"YColor",
"Y Color",
"This value determines the color of the y axis."
};
constexpr openspace::properties::Property::PropertyInfo ZColorInfo = {
"ZColor",
"Z Color",
"This value determines the color of the z axis."
};
} // namespace
namespace openspace {
documentation::Documentation RenderableCartesianAxes::Documentation() {
using namespace documentation;
return {
"CartesianAxesProgram",
"base_renderable_cartesianaxes",
{
{
XColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
XColorInfo.description
},
{
YColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
YColorInfo.description
},
{
ZColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
ZColorInfo.description
}
}
};
}
RenderableCartesianAxes::RenderableCartesianAxes(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _program(nullptr)
, _xColor(
XColorInfo,
glm::vec4(0.f, 0.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _yColor(
YColorInfo,
glm::vec4(0.f, 1.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _zColor(
ZColorInfo,
glm::vec4(0.f, 0.f, 1.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableCartesianAxes"
);
if (dictionary.hasKey(XColorInfo.identifier)) {
_xColor = dictionary.value<glm::vec4>(XColorInfo.identifier);
}
_xColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_xColor);
if (dictionary.hasKey(XColorInfo.identifier)) {
_yColor = dictionary.value<glm::vec4>(YColorInfo.identifier);
}
_yColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_yColor);
if (dictionary.hasKey(ZColorInfo.identifier)) {
_zColor = dictionary.value<glm::vec4>(ZColorInfo.identifier);
}
_zColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_zColor);
}
bool RenderableCartesianAxes::isReady() const {
bool ready = true;
ready &= (_program != nullptr);
return ready;
}
void RenderableCartesianAxes::initializeGL() {
_program = BaseModule::ProgramObjectManager.request(
ProgramName,
[]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
return global::renderEngine.buildRenderProgram(
ProgramName,
absPath("${MODULE_BASE}/shaders/axes_vs.glsl"),
absPath("${MODULE_BASE}/shaders/axes_fs.glsl")
);
}
);
glGenVertexArrays(1, &_vaoId);
glGenBuffers(1, &_vBufferId);
glGenBuffers(1, &_iBufferId);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
std::vector<Vertex> vertices({
Vertex{0.f, 0.f, 0.f},
Vertex{1.f, 0.f, 0.f},
Vertex{0.f, 1.f, 0.f},
Vertex{0.f, 0.f, 1.f}
});
std::vector<int> indices = {
0, 1,
0, 2,
0, 3
};
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
vertices.data(),
GL_STATIC_DRAW
);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
indices.size() * sizeof(int),
indices.data(),
GL_STATIC_DRAW
);
}
void RenderableCartesianAxes::deinitializeGL() {
glDeleteVertexArrays(1, &_vaoId);
_vaoId = 0;
glDeleteBuffers(1, &_vBufferId);
_vBufferId = 0;
glDeleteBuffers(1, &_iBufferId);
_iBufferId = 0;
BaseModule::ProgramObjectManager.release(
ProgramName,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine.removeRenderProgram(p);
}
);
_program = nullptr;
}
void RenderableCartesianAxes::render(const RenderData& data, RendererTasks&){
_program->activate();
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() *
modelTransform;
_program->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
_program->setUniform("projectionTransform", data.camera.projectionMatrix());
_program->setUniform("xColor", _xColor);
_program->setUniform("yColor", _yColor);
_program->setUniform("zColor", _zColor);
// Saves current state:
GLboolean isBlendEnabled = glIsEnabledi(GL_BLEND, 0);
GLboolean isLineSmoothEnabled = glIsEnabled(GL_LINE_SMOOTH);
GLfloat currentLineWidth;
glGetFloatv(GL_LINE_WIDTH, ¤tLineWidth);
GLenum blendEquationRGB, blendEquationAlpha, blendDestAlpha,
blendDestRGB, blendSrcAlpha, blendSrcRGB;
glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha);
glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha);
glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB);
// Changes GL state:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnablei(GL_BLEND, 0);
glEnable(GL_LINE_SMOOTH);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glDrawElements(GL_LINES, NVertexIndices, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
_program->deactivate();
// Restores GL State
glLineWidth(currentLineWidth);
glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha);
glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha);
if (!isBlendEnabled) {
glDisablei(GL_BLEND, 0);
}
if (!isLineSmoothEnabled) {
glDisable(GL_LINE_SMOOTH);
}
}
} // namespace openspace
| 34.536232 | 90 | 0.593999 |
283afec9ab13eba507692de14055621e68232683 | 3,020 | hpp | C++ | QuantExt/qle/instruments/makecds.hpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | 1 | 2021-03-30T17:24:17.000Z | 2021-03-30T17:24:17.000Z | QuantExt/qle/instruments/makecds.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | null | null | null | QuantExt/qle/instruments/makecds.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | 1 | 2022-02-07T02:04:10.000Z | 2022-02-07T02:04:10.000Z | /*
Copyright (C) 2017 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*
Copyright (C) 2014 Jose Aparicio
Copyright (C) 2014 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file makecds.hpp
\brief Helper class to instantiate standard market cds.
\ingroup instruments
*/
#ifndef quantext_makecds_hpp
#define quantext_makecds_hpp
#include <boost/optional.hpp>
#include <qle/instruments/creditdefaultswap.hpp>
namespace QuantExt {
using namespace QuantLib;
//! helper class
/*! This class provides a more comfortable way
to instantiate standard cds.
\bug support last period dc
\ingroup instruments
*/
class MakeCreditDefaultSwap {
public:
MakeCreditDefaultSwap(const Period& tenor, const Real couponRate);
MakeCreditDefaultSwap(const Date& termDate, const Real couponRate);
operator CreditDefaultSwap() const;
operator boost::shared_ptr<CreditDefaultSwap>() const;
MakeCreditDefaultSwap& withUpfrontRate(Real);
MakeCreditDefaultSwap& withSide(Protection::Side);
MakeCreditDefaultSwap& withNominal(Real);
MakeCreditDefaultSwap& withCouponTenor(Period);
MakeCreditDefaultSwap& withDayCounter(DayCounter&);
// MakeCreditDefaultSwap& withLastPeriodDayCounter(DayCounter&);
MakeCreditDefaultSwap& withPricingEngine(const boost::shared_ptr<PricingEngine>&);
private:
Protection::Side side_;
Real nominal_;
boost::optional<Period> tenor_;
boost::optional<Date> termDate_;
Period couponTenor_;
Real couponRate_;
Real upfrontRate_;
DayCounter dayCounter_;
// DayCounter lastPeriodDayCounter_;
boost::shared_ptr<PricingEngine> engine_;
};
} // namespace QuantExt
#endif
| 33.555556 | 86 | 0.76755 |
283cf5bab703ddbfe5d27d122222b8ffcb2343d6 | 86,167 | cpp | C++ | dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "InstanceDataHierarchy.h"
#include <AzCore/std/bind/bind.h>
#include <AzCore/std/functional.h>
#include <AzCore/std/sort.h>
#include <AzCore/Serialization/Utils.h>
#include <AzCore/Math/MathUtils.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Debug/Profiler.h>
#include <AzCore/RTTI/AttributeReader.h>
#include <AzCore/Serialization/DynamicSerializableField.h>
#include <AzCore/Script/ScriptProperty.h>
#include <AzCore/Math/Crc.h>
#include <AzCore/Serialization/EditContextConstants.inl>
#include "ComponentEditor.hxx"
#include "PropertyEditorAPI.h"
#include <AzToolsFramework/ToolsComponents/TransformComponent.h>
namespace
{
AZ::Edit::Attribute* FindAttributeInNode(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
if (!node)
{
return nullptr;
}
AZ::Edit::Attribute* attr{};
const AZ::Edit::ElementData* elementEditData = node->GetElementEditMetadata();
if (elementEditData)
{
attr = elementEditData->FindAttribute(attribId);
}
// Attempt to look up the attribute on the node reflected class data.
// This look up is done via AZ::SerializeContext::ClassData -> AZ::Edit::ClassData -> EditorData element
if (!attr)
{
if (const AZ::SerializeContext::ClassData* classData = node->GetClassMetadata())
{
if (const auto* editClassData = classData->m_editData)
{
if (const auto* classEditorData = editClassData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
attr = classEditorData->FindAttribute(attribId);
}
}
}
}
return attr;
}
template<typename ... Args>
AZStd::string GetStringFromAttributeWithParams(AzToolsFramework::InstanceDataNode* node, AZ::Edit::Attribute* attribute, Args&& ... params)
{
if (!node || !attribute)
{
return "";
}
// Read the string from the attribute found.
AZStd::string label;
for (size_t instIndex = 0; instIndex < node->GetNumInstances(); ++instIndex)
{
AzToolsFramework::PropertyAttributeReader reader(node->GetInstance(instIndex), attribute);
if (reader.Read<AZStd::string>(label, AZStd::forward<Args>(params) ...))
{
return label;
}
}
return "";
}
AZStd::string GetIndexedStringFromAttribute(AzToolsFramework::InstanceDataNode* parentNode, AzToolsFramework::InstanceDataNode* attributeNode, AZ::Edit::AttributeId attribId, int siblingIndex)
{
AZ::Edit::Attribute* attribute = FindAttributeInNode(attributeNode, attribId);
return GetStringFromAttributeWithParams(parentNode, attribute, siblingIndex);
}
AZStd::string GetStringFromAttribute(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
AZ::Edit::Attribute* attribute = FindAttributeInNode(node, attribId);
return GetStringFromAttributeWithParams(node, attribute);
}
template<typename Type>
Type GetFromAttribute(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
if (!node)
{
return Type();
}
AZ::Edit::Attribute* attr{};
const AZ::Edit::ElementData* elementEditData = node->GetElementEditMetadata();
if (elementEditData)
{
attr = elementEditData->FindAttribute(attribId);
}
// Attempt to look up the attribute on the node reflected class data.
// This look up is done via AZ::SerializeContext::ClassData -> AZ::Edit::ClassData -> EditorData element
if (!attr)
{
if (const AZ::SerializeContext::ClassData* classData = node->GetClassMetadata())
{
if (const auto* editClassData = classData->m_editData)
{
if (const auto* classEditorData = editClassData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
attr = classEditorData->FindAttribute(attribId);
}
}
}
}
if (!attr)
{
return Type();
}
// Read the value from the attribute found.
Type retVal = Type();
for (size_t instIndex = 0; instIndex < node->GetNumInstances(); ++instIndex)
{
AzToolsFramework::PropertyAttributeReader reader(node->GetInstance(instIndex), attr);
if (reader.Read<Type>(retVal))
{
return retVal;
}
}
return Type();
}
AZStd::string GetDisplayLabel(AzToolsFramework::InstanceDataNode* node, int siblingIndex = 0)
{
if (!node)
{
return "";
}
AZStd::string label;
// We want to check to see if a name override was provided by our first real
// non-container parent.
//
// 'real' basically means something that is actually going to display.
//
// If we don't have a parent override, then we can take a look at applying out internal name override.
AzToolsFramework::InstanceDataNode* parentNode = node->GetParent();
while (parentNode)
{
bool nonContainerNodeFound = !parentNode->GetClassMetadata() || !parentNode->GetClassMetadata()->m_container;
if (nonContainerNodeFound)
{
const bool isSlicePushUI = false;
AzToolsFramework::NodeDisplayVisibility visibility = CalculateNodeDisplayVisibility((*parentNode), isSlicePushUI);
nonContainerNodeFound = (visibility == AzToolsFramework::NodeDisplayVisibility::Visible);
}
label = GetStringFromAttribute(parentNode, AZ::Edit::Attributes::ChildNameLabelOverride);
if (!label.empty() || nonContainerNodeFound)
{
break;
}
parentNode = parentNode->GetParent();
}
// If our parent isn't controlling us. Fall back to whatever we want to be called
if (label.empty())
{
label = GetStringFromAttribute(node, AZ::Edit::Attributes::NameLabelOverride);
}
if (label.empty())
{
parentNode = node;
do
{
parentNode = parentNode->GetParent();
}
while (parentNode && parentNode->GetClassMetadata() && parentNode->GetClassMetadata()->m_container);
// trying to get per-item name provided by real parent
label = GetIndexedStringFromAttribute(parentNode, node->GetParent(), AZ::Edit::Attributes::IndexedChildNameLabelOverride, siblingIndex);
}
return label;
}
}
namespace AzToolsFramework
{
//-----------------------------------------------------------------------------
void* ResolvePointer(void* ptr, const AZ::SerializeContext::ClassElement& classElement, const AZ::SerializeContext& context)
{
if (classElement.m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// In the case of pointer-to-pointer, we'll deference.
ptr = *(void**)(ptr);
// Pointer-to-pointer fields may be base class / polymorphic, so cast pointer to actual type,
// safe for passing as 'this' to member functions.
if (ptr && classElement.m_azRtti)
{
AZ::Uuid actualClassId = classElement.m_azRtti->GetActualUuid(ptr);
if (actualClassId != classElement.m_typeId)
{
const AZ::SerializeContext::ClassData* classData = context.FindClassData(actualClassId);
if (classData)
{
ptr = classElement.m_azRtti->Cast(ptr, classData->m_azRtti->GetTypeId());
}
}
}
}
return ptr;
}
//-----------------------------------------------------------------------------
// InstanceDataNode
//-----------------------------------------------------------------------------
//! Read the value of the node.
//! Clones the node's value and returns its address into valuePtr. ValuePtr will be overridden.
bool InstanceDataNode::ReadRaw(void*& valuePtr, AZ::TypeId valueType)
{
void* firstInstanceCast = (GetSerializeContext()->DownCast(FirstInstance(), GetClassMetadata()->m_typeId, valueType));
if (!firstInstanceCast)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
return false;
}
valuePtr = firstInstanceCast;
// check all instance values are the same
return std::all_of(m_instances.begin(), m_instances.end(), [this, valueType, firstInstanceCast](void* instance)
{
void* instanceCast = (GetSerializeContext()->DownCast(instance, GetClassMetadata()->m_typeId, valueType));
if (!instanceCast)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
return false;
}
return (GetClassMetadata()->m_serializer && GetClassMetadata()->m_serializer->CompareValueData(instanceCast, firstInstanceCast)) ||
(!GetClassMetadata()->m_serializer && instanceCast == firstInstanceCast);
});
}
//! Write the value into the node.
void InstanceDataNode::WriteRaw(const void* valuePtr, AZ::TypeId valueType)
{
for (void* instance : m_instances)
{
// If type does not match, bail
if (valueType != GetClassMetadata()->m_typeId)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
continue;
}
if (valueType == GetClassMetadata()->m_typeId)
{
GetSerializeContext()->CloneObjectInplace(instance, valuePtr, GetClassMetadata()->m_typeId);
}
}
}
void* InstanceDataNode::GetInstance(size_t idx) const
{
void* ptr = m_instances[idx];
if (m_classElement)
{
ptr = ResolvePointer(ptr, *m_classElement, *m_context);
}
return ptr;
}
//-----------------------------------------------------------------------------
void** InstanceDataNode::GetInstanceAddress(size_t idx) const
{
AZ_Assert(m_classElement && (m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER), "You can not call GetInstanceAddress() on a node that is not of a pointer type!");
return reinterpret_cast<void**>(m_instances[idx]);
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::CreateContainerElement(const SelectClassCallback& selectClass, const FillDataClassCallback& fillData)
{
AZ::SerializeContext::IDataContainer* container = m_classData->m_container;
AZ_Assert(container, "This node is NOT a container node!");
const AZ::SerializeContext::ClassElement* containerClassElement = container->GetElement(container->GetDefaultElementNameCrc());
AZ_Assert(containerClassElement != NULL, "We should have a valid default element in the container, otherwise we don't know what elements to make!");
if (containerClassElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// TEMP until it's safe to pass 0 as type id
const AZ::Uuid& baseTypeId = containerClassElement->m_azRtti ? containerClassElement->m_azRtti->GetTypeId() : AZ::AzTypeInfo<int>::Uuid();
// ask the GUI and use to create one (if there is choice)
const AZ::SerializeContext::ClassData* classData = selectClass(containerClassElement->m_typeId, baseTypeId, m_context);
if (classData && classData->m_factory)
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
// create entry
void* newDataAddress = classData->m_factory->Create(classData->m_name);
AZ_Assert(newDataAddress, "Faliled to create new element for the continer!");
// cast to base type (if needed)
void* basePtr = m_context->DownCast(newDataAddress, classData->m_typeId, containerClassElement->m_typeId, classData->m_azRtti, containerClassElement->m_azRtti);
AZ_Assert(basePtr != NULL, "Can't cast container element %s to %s, make sure classes are registered in the system and not generics!", classData->m_name, containerClassElement->m_name);
*reinterpret_cast<void**>(dataAddress) = basePtr; // store the pointer in the class
/// Store the element in the container
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
}
else if (containerClassElement->m_typeId == AZ::SerializeTypeInfo<AZ::DynamicSerializableField>::GetUuid())
{
// Dynamic serializable fields are capable of wrapping any type. Each one within a container can technically contain
// an entirely different type from the others. We're going to assume that we're getting here via
// ScriptPropertyGenericClassArray and that it strictly uses one type.
const AZ::SerializeContext::ClassData* classData = m_context->FindClassData(AZ::SerializeTypeInfo<AZ::DynamicSerializableField>::GetUuid());
const AZ::Edit::ElementData* element = m_parent->m_classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData);
if (element)
{
// Grab the AttributeMemberFunction used to get the Uuid type of the element wrapped by the DynamicSerializableField
AZ::Edit::Attribute* assetTypeAttribute = element->FindAttribute(AZ::Edit::Attributes::DynamicElementType);
if (assetTypeAttribute)
{
//Invoke the function we just grabbed and pull the class data based on that Uuid
AZ_Assert(m_parent->GetNumInstances() <= 1, "ScriptPropertyGenericClassArray should not have more than one DynamicSerializableField vector");
AZ::AttributeReader elementTypeIdReader(m_parent->GetInstance(0), assetTypeAttribute);
AZ::Uuid dynamicClassUuid;
if (elementTypeIdReader.Read<AZ::Uuid>(dynamicClassUuid))
{
const AZ::SerializeContext::ClassData* dynamicClassData = m_context->FindClassData(dynamicClassUuid);
//Construct a new element based on the Uuid we just grabbed and wrap it in a DynamicSerializeableField for storage
if (classData && classData->m_factory &&
dynamicClassData && dynamicClassData->m_factory)
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// Reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
// Create DynamicSerializeableField entry
void* newDataAddress = classData->m_factory->Create(classData->m_name);
AZ_Assert(newDataAddress, "Faliled to create new element for the continer!");
// Create dynamic element and populate entry with it
AZ::DynamicSerializableField* dynamicFieldDesc = reinterpret_cast<AZ::DynamicSerializableField*>(newDataAddress);
void* newDynamicData = dynamicClassData->m_factory->Create(dynamicClassData->m_name);
dynamicFieldDesc->m_data = newDynamicData;
dynamicFieldDesc->m_typeId = dynamicClassData->m_typeId;
/// Store the entry in the container
*reinterpret_cast<AZ::DynamicSerializableField*>(dataAddress) = *dynamicFieldDesc;
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
}
}
}
}
else
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// check capacity of container before attempting to reserve an element
if (container->IsFixedCapacity() && !container->IsSmartPointer() && container->Size(GetInstance(i)) >= container->Capacity(GetInstance(i)))
{
AZ_Warning("Serializer", false, "Cannot add additional entries to the container as it is at its capacity of %zu", container->Capacity(GetInstance(i)));
return false;
}
// reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
bool isAssociative = false;
ReadAttribute(AZ::Edit::Attributes::ShowAsKeyValuePairs, isAssociative, true);
bool noDefaultData = isAssociative || (containerClassElement->m_flags & AZ::SerializeContext::ClassElement::FLG_NO_DEFAULT_VALUE) != 0;
if (!dataAddress || !fillData(dataAddress, containerClassElement, noDefaultData, m_context) && noDefaultData) // fill default data
{
return false;
}
/// Store the element in the container
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
return false;
}
bool InstanceDataNode::ChildMatchesAddress(const InstanceDataNode::Address& elementAddress) const
{
if (elementAddress.empty())
{
return false;
}
for (const InstanceDataNode& child : m_children)
{
if (elementAddress == child.ComputeAddress())
{
return true;
}
if (child.ChildMatchesAddress(elementAddress))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkNewVersusComparison()
{
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::New);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkDifferentVersusComparison()
{
if (ShouldComparisonBeIgnored())
{
return;
}
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::Differs);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkRemovedVersusComparison()
{
m_comparisonFlags &= ~static_cast<AZ::u32>(ComparisonFlags::New);
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::Removed);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::ClearComparisonData()
{
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::None);
m_comparisonNode = nullptr;
}
//-----------------------------------------------------------------------------
void InstanceDataNode::SetIgnoreComparisonResult(bool ignoreResult)
{
m_ignoreComparisonResult = ignoreResult;
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsNewVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::New));
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsDifferentVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::Differs));
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsRemovedVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::Removed));
}
//-----------------------------------------------------------------------------
const InstanceDataNode* InstanceDataNode::GetComparisonNode() const
{
return m_comparisonNode;
}
bool InstanceDataNode::HasChangesVersusComparison(bool includeChildren) const
{
if (m_comparisonFlags)
{
return true;
}
if (includeChildren)
{
for (auto child : m_children)
{
if (child.HasChangesVersusComparison(includeChildren))
{
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::ShouldComparisonBeIgnored() const
{
return m_ignoreComparisonResult;
}
//-----------------------------------------------------------------------------
InstanceDataNode::Address InstanceDataNode::ComputeAddress() const
{
Address addressStack;
addressStack.reserve(32);
addressStack.push_back(m_identifier);
InstanceDataNode* parent = m_parent;
while (parent)
{
addressStack.push_back(parent->m_identifier);
parent = parent->m_parent;
}
return addressStack;
}
AZ::Edit::Attribute* InstanceDataNode::FindAttribute(AZ::Edit::AttributeId nameCrc) const
{
AZ::Edit::Attribute* attribute = nullptr;
// Edit Data > Class Element > Class Data in terms of specificity to what we're editing, so prioritize their attributes accordingly
if (m_elementEditData)
{
attribute = m_elementEditData->FindAttribute(nameCrc);
}
if (!attribute && m_classElement)
{
attribute = m_classElement->FindAttribute(nameCrc);
}
if (!attribute && m_classData)
{
attribute = m_classData->FindAttribute(nameCrc);
}
return attribute;
}
//-----------------------------------------------------------------------------
// InstanceDataHierarchy
//-----------------------------------------------------------------------------
InstanceDataHierarchy::InstanceDataHierarchy()
: m_curParentNode(nullptr)
, m_isMerging(false)
, m_nodeDiscarded(false)
, m_valueComparisonFunction(DefaultValueComparisonFunction)
{
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::AddRootInstance(void* instance, const AZ::Uuid& classId)
{
m_rootInstances.emplace_back(instance, classId);
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::AddComparisonInstance(void* instance, const AZ::Uuid& classId)
{
m_comparisonInstances.emplace_back(instance, classId);
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::ContainsRootInstance(const void* instance) const
{
for (InstanceDataArray::const_iterator it = m_rootInstances.begin(); it != m_rootInstances.end(); ++it)
{
if (it->m_instance == instance)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::SetBuildFlags(AZ::u8 flags)
{
m_buildFlags = flags;
}
void InstanceDataHierarchy::EnumerateUIElements(InstanceDataNode* node, DynamicEditDataProvider dynamicEditDataProvider)
{
for (InstanceDataNode& child : node->m_children)
{
EnumerateUIElements(&child, dynamicEditDataProvider);
}
AZ::Edit::ClassData* nodeEditData = node->GetClassMetadata() ? node->GetClassMetadata()->m_editData : nullptr;
if (nodeEditData)
{
const AZ::Edit::ElementData* groupData = nullptr;
const AZ::Edit::ElementData* previousData = nullptr;
for (auto& element : nodeEditData->m_elements)
{
if (element.IsClassElement() && element.m_elementId == AZ::Edit::ClassElements::Group)
{
groupData = (element.m_description && element.m_description[0]) ? &element : nullptr;
continue;
}
//create ui elements in their relative edit context positions
if (element.m_elementId == AZ::Edit::ClassElements::UIElement)
{
//if there is no matching, previous element, assume the UI element comes first
m_childIndexOverride = 0;
if (previousData)
{
//search for matching sibling element data by name
auto it = AZStd::find_if(
node->m_children.begin(),
node->m_children.end(),
[previousData](const InstanceDataNode& otherNode) {
return otherNode.m_classElement->m_editData == previousData;
});
if (it != node->m_children.end())
{
//if there is element data matching the previous entry, place the UI element after it
m_childIndexOverride = static_cast<int>(AZStd::distance(node->m_children.begin(), it)) + 1;
}
}
// For every UIElement, generate an InstanceDataNode pointed at our instance with the corresponding attributes
for (size_t i = 0, numInstances = node->GetNumInstances(); i < numInstances; ++i)
{
m_supplementalElementData.push_back();
auto& serializeFieldElement = m_supplementalElementData.back();
serializeFieldElement.m_name = element.m_description;
serializeFieldElement.m_nameCrc = AZ::Crc32(element.m_description);
serializeFieldElement.m_azRtti = nullptr;
serializeFieldElement.m_dataSize = sizeof(void*);
serializeFieldElement.m_offset = 0;
serializeFieldElement.m_typeId = AZ::Uuid::CreateNull();
serializeFieldElement.m_editData = &element;
serializeFieldElement.m_flags = AZ::SerializeContext::ClassElement::FLG_UI_ELEMENT;
m_curParentNode = node;
BeginNode(node->GetInstance(i), nullptr, &serializeFieldElement, dynamicEditDataProvider);
m_curParentNode->m_groupElementData = groupData;
EndNode();
}
}
previousData = &element;
}
m_childIndexOverride = -1;
m_curParentNode = nullptr;
}
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::Build(AZ::SerializeContext* sc, unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider, ComponentEditor* editorParent)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
AZ_Assert(sc, "sc can't be NULL!");
AZ_Assert(m_rootInstances.size() > 0, "No root instances have been added to this hierarchy!");
m_curParentNode = NULL;
m_isMerging = false;
m_instances.clear();
m_children.clear();
m_matched = true;
m_nodeDiscarded = false;
m_context = sc;
m_comparisonHierarchies.clear();
m_supplementalEditData.clear();
AZ::SerializeContext::EnumerateInstanceCallContext callContext(
AZStd::bind(&InstanceDataHierarchy::BeginNode, this, AZStd::placeholders::_1, AZStd::placeholders::_2, AZStd::placeholders::_3, dynamicEditDataProvider),
AZStd::bind(&InstanceDataHierarchy::EndNode, this),
sc,
AZ::SerializeContext::ENUM_ACCESS_FOR_READ,
nullptr
);
sc->EnumerateInstanceConst(
&callContext
, m_rootInstances[0].m_instance
, m_rootInstances[0].m_classId
, nullptr
, nullptr
);
for (size_t i = 1; i < m_rootInstances.size(); ++i)
{
m_curParentNode = NULL;
m_isMerging = true;
m_matched = false;
sc->EnumerateInstanceConst(
&callContext
, m_rootInstances[i].m_instance
, m_rootInstances[i].m_classId
, nullptr
, nullptr
);
}
EnumerateUIElements(this, dynamicEditDataProvider);
// Fixup our container edit data first, as we may specifically affect comparison data
bool foundRootParent = false;
FixupEditData(this, 0, foundRootParent);
bool dataIdentical = RefreshComparisonData(accessFlags, dynamicEditDataProvider);
if (editorParent)
{
editorParent->SetComponentOverridden(!dataIdentical);
}
}
namespace InstanceDataHierarchyHelper
{
template <class T>
bool GetEnumStringRepresentation(AZStd::string& value, const AZ::Edit::ElementData* data, void* instance, const AZ::Uuid& storageTypeId)
{
if (storageTypeId == azrtti_typeid<T>())
{
for (const AZ::AttributePair& attributePair : data->m_attributes)
{
PropertyAttributeReader reader(instance, attributePair.second);
AZ::Edit::EnumConstant<T> enumPair;
if (reader.Read<AZ::Edit::EnumConstant<T>>(enumPair))
{
T* enumValue = reinterpret_cast<T*>(instance);
if (enumPair.m_value == *enumValue)
{
value = enumPair.m_description;
return true;
}
}
}
}
return false;
}
// Try GetEnumStringRepresentation<Type> on all of the specified types
template <class T1, class T2, class... TRest>
bool GetEnumStringRepresentation(AZStd::string& value, const AZ::Edit::ElementData* data, void* instance, const AZ::Uuid& storageTypeId)
{
return GetEnumStringRepresentation<T1>(value, data, instance, storageTypeId) || GetEnumStringRepresentation<T2, TRest...>(value, data, instance, storageTypeId);
}
bool GetValueStringRepresentation(const InstanceDataNode* node, AZStd::string& value)
{
if (!node || !node->GetClassMetadata())
{
return false;
}
AZ::SerializeContext* serializeContext = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext);
// Get our enum string value from the edit context if we're actually an enum
AZ::Uuid enumId;
if (serializeContext && node->ReadAttribute(AZ::Edit::InternalAttributes::EnumType, enumId))
{
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
const AZ::Edit::ElementData* data = editContext->GetEnumElementData(enumId);
if (data)
{
// Check all underlying enum storage types
if (GetEnumStringRepresentation<
AZ::u8, AZ::u16, AZ::u32, AZ::u64,
AZ::s8, AZ::s16, AZ::s32, AZ::s64>(value, data, node->FirstInstance(), node->GetClassMetadata()->m_typeId))
{
return true;
}
}
}
}
// Just use our underlying AZStd::string if we're a string
if (node->GetClassMetadata()->m_typeId == azrtti_typeid<AZStd::string>())
{
value = *reinterpret_cast<AZStd::string*>(node->FirstInstance());
return true;
}
// Fall back on using our serializer's DataToText
if (node->GetElementMetadata())
{
if (auto& serializer = node->GetClassMetadata()->m_serializer)
{
AZ::IO::MemoryStream memStream(node->FirstInstance(), 0, node->GetElementMetadata()->m_dataSize);
AZStd::vector<char> buffer;
AZ::IO::ByteContainerStream<AZStd::vector<char>> outStream(&buffer);
serializer->DataToText(memStream, outStream, false);
value = AZStd::string(buffer.data(), buffer.size());
return !value.empty();
}
}
return false;
}
}
void InstanceDataHierarchy::FixupComparisonData(InstanceDataNode* node, bool& foundRootParent)
{
if (!foundRootParent)
{
bool isRootParentId = false;
if (node->GetClassMetadata() && node->GetClassMetadata()->m_typeId == AZ::AzTypeInfo<AZ::EntityId>::Uuid())
{
if (node->GetElementMetadata()->m_nameCrc == AzToolsFramework::Components::TransformComponent::GetParentEntityCRC())
{
isRootParentId = true;
}
}
if (isRootParentId && !ShouldComparisonBeIgnored())
{
node->SetIgnoreComparisonResult(true);
foundRootParent = true;
}
}
else if (node->GetParent() && node->GetParent()->ShouldComparisonBeIgnored())
{
node->SetIgnoreComparisonResult(true);
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::FixupEditData(InstanceDataNode* node, int siblingIdx, bool& foundRootParent)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
bool mergeElementEditData = node->m_classElement && node->m_classElement->m_editData && node->GetElementEditMetadata() != node->m_classElement->m_editData;
bool mergeContainerEditData = node->m_parent && node->m_parent->m_classData->m_container && node->m_parent->GetElementEditMetadata() && (node->m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER) == 0;
node->SetIgnoreComparisonResult(false);
FixupComparisonData(node, foundRootParent);
bool showAsKeyValue = false;
if (!(m_buildFlags & Flags::IgnoreKeyValuePairs))
{
// Default to showing as key values if we're an associative interface, but always respect ShowAsKeyValuePairs if it's specified
showAsKeyValue = node->m_parent && node->m_parent->m_classData->m_container && node->m_parent->m_classData->m_container->GetAssociativeContainerInterface();
node->ReadAttribute(AZ::Edit::Attributes::ShowAsKeyValuePairs, showAsKeyValue);
}
if (mergeElementEditData || mergeContainerEditData || showAsKeyValue)
{
AZStd::string label;
if (!showAsKeyValue)
{
label = GetDisplayLabel(node, siblingIdx);
}
// Grab a copy of our instances if we might need to move them to a key/value attribute.
// We need a copy because the current node may well be replaced in its entirety by one of its children.
AZStd::vector<void*> elementInstances;
if (showAsKeyValue)
{
elementInstances = node->m_instances;
}
// If our node is a pair, and we're not enumerating multiple instances, respect showAsKeyValue and promote the value data element with a label matching our instance's string representation
if (showAsKeyValue && node->m_children.size() == 2 && node->GetNumInstances() == 1)
{
// Make sure we can get a valid string representation before doing the conversion
if (label.empty())
{
showAsKeyValue = InstanceDataHierarchyHelper::GetValueStringRepresentation(&node->m_children.front(), label);
}
}
m_supplementalEditData.push_back();
AZ::Edit::ElementData* editData = &m_supplementalEditData.back().m_editElementData;
if (node->GetElementEditMetadata())
{
*editData = *node->GetElementEditMetadata();
}
node->m_elementEditData = editData;
// Flag our new key node with our original instances for any future element modification
if (showAsKeyValue)
{
node->m_identifier = AZ::Crc32(label.c_str());
auto attribute = aznew AZ::AttributeContainerType<AZStd::vector<void*>>(AZStd::move(elementInstances));
m_supplementalEditData.back().m_attributes.emplace_back(attribute); // Ensure the attribute gets cleaned up
editData->m_attributes.emplace_back(
AZ::Edit::InternalAttributes::ElementInstances,
attribute);
}
if (mergeElementEditData)
{
for (AZ::Edit::AttributeArray::const_iterator elemAttrIter = node->m_classElement->m_editData->m_attributes.begin(); elemAttrIter != node->m_classElement->m_editData->m_attributes.end(); ++elemAttrIter)
{
AZ::Edit::AttributeArray::iterator editAttrIter = editData->m_attributes.begin();
for (; editAttrIter != editData->m_attributes.end(); ++editAttrIter)
{
if (elemAttrIter->first == editAttrIter->first)
{
break;
}
}
if (editAttrIter == editData->m_attributes.end())
{
editData->m_attributes.push_back(*elemAttrIter);
}
}
}
if (mergeContainerEditData || !label.empty())
{
m_supplementalEditData.back().m_displayLabel = label.empty() ? AZStd::string::format("[%d]", siblingIdx) : label;
editData->m_description = nullptr;
editData->m_name = m_supplementalEditData.back().m_displayLabel.c_str();
if (mergeContainerEditData)
{
InstanceDataNode* container = node->m_parent;
for (AZ::Edit::AttributeArray::const_iterator containerAttrIter = container->GetElementEditMetadata()->m_attributes.begin(); containerAttrIter != container->GetElementEditMetadata()->m_attributes.end(); ++containerAttrIter)
{
if (!containerAttrIter->second->m_describesChildren)
{
continue;
}
AZ::Edit::AttributeArray::iterator editAttrIter = editData->m_attributes.begin();
for (; editAttrIter != editData->m_attributes.end(); ++editAttrIter)
{
if (containerAttrIter->first == editAttrIter->first)
{
break;
}
}
if (editAttrIter == editData->m_attributes.end())
{
editData->m_attributes.push_back(*containerAttrIter);
}
}
}
}
}
int childIdx = 0;
for (NodeContainer::iterator it = node->m_children.begin(); it != node->m_children.end(); ++it)
{
FixupEditData(&(*it), childIdx++, foundRootParent);
}
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::BeginNode(void* ptr, const AZ::SerializeContext::ClassData* classData, const AZ::SerializeContext::ClassElement* classElement, DynamicEditDataProvider dynamicEditDataProvider)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
const AZ::Edit::ElementData* elementEditData = nullptr;
if (classElement)
{
// Find the correct element edit data to use
elementEditData = classElement->m_editData;
if (dynamicEditDataProvider)
{
void* objectPtr = ResolvePointer(ptr, *classElement, *m_context);
const AZ::Edit::ElementData* labelData = dynamicEditDataProvider(objectPtr, classData);
if (labelData)
{
elementEditData = labelData;
}
}
else if (!m_editDataOverrides.empty())
{
const EditDataOverride& editDataOverride = m_editDataOverrides.back();
void* objectPtr = ResolvePointer(ptr, *classElement, *m_context);
void* overridingInstance = editDataOverride.m_overridingInstance;
const AZ::SerializeContext::ClassElement* overridingElementData = editDataOverride.m_overridingNode->GetElementMetadata();
if (overridingElementData)
{
overridingInstance = ResolvePointer(overridingInstance, *overridingElementData, *m_context);
}
if (classData)
{
const AZ::Edit::ElementData* useData = editDataOverride.m_override(overridingInstance, objectPtr, classData->m_typeId);
if (useData)
{
elementEditData = useData;
}
}
}
}
InstanceDataNode* node = NULL;
// Extra steps need to be taken when we are merging
if (m_isMerging)
{
if (!m_curParentNode)
{
// Only accept root instances that are of the same type
if (classData && classData->m_typeId == m_classData->m_typeId)
{
node = this;
}
}
else
{
// Search through the parent's class elements to find a match
for (NodeContainer::iterator it = m_curParentNode->m_children.begin(); it != m_curParentNode->m_children.end(); ++it)
{
InstanceDataNode* subElement = &(*it);
if (!subElement->m_matched &&
subElement->m_classElement->m_nameCrc == classElement->m_nameCrc &&
subElement->m_classData == classData &&
(subElement->m_elementEditData == elementEditData ||
(subElement->m_elementEditData && elementEditData &&
subElement->m_elementEditData->m_name && elementEditData->m_name &&
azstricmp(subElement->m_elementEditData->m_name, elementEditData->m_name) == 0)))
{
node = subElement;
break;
}
}
}
if (node)
{
// Add the new instance pointer to the list of mapped instances
node->m_instances.push_back(ptr);
// Flag the node as already matched for this pass.
node->m_matched = true;
// prepare the node's children for matching
// we set them all to false so that when we unwind the depth-first enumeration,
// any unmatched nodes can be discarded.
for (NodeContainer::iterator it = node->m_children.begin(); it != node->m_children.end(); ++it)
{
it->m_matched = false;
}
}
else
{
// Reject the node and everything under it
m_nodeDiscarded = true;
return false;
}
}
else
{
// Not merging, just add anything being enumerated to the hierarchy.
if (!m_curParentNode)
{
node = this;
}
else
{
if (m_childIndexOverride >= 0)
{
auto position = m_curParentNode->m_children.begin();
AZStd::advance(position, m_childIndexOverride);
auto iterator = m_curParentNode->m_children.insert(position);
node = &(*iterator);
}
else
{
m_curParentNode->m_children.push_back();
node = &m_curParentNode->m_children.back();
}
}
node->m_instances.push_back(ptr);
node->m_classData = classData;
// ClassElement pointers for DynamicSerializableFields are temporaries, so we need
// to maintain it locally.
if (classElement && (classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_DYNAMIC_FIELD))
{
m_supplementalElementData.push_back(*classElement);
classElement = &m_supplementalElementData.back();
}
node->m_classElement = classElement;
node->m_elementEditData = elementEditData;
node->m_parent = m_curParentNode;
node->m_root = this;
node->m_context = m_context;
// Compute node's identifier, which is used to compute full address within a hierarchy.
if (m_curParentNode)
{
if (m_curParentNode->GetClassMetadata() && m_curParentNode->GetClassMetadata()->m_container)
{
if (classData)
{
// Within a container, use persistentId if available, otherwise use a CRC of name and container index.
AZ::SerializeContext::ClassPersistentId persistentId = classData->GetPersistentId(*m_context);
if (persistentId)
{
node->m_identifier = static_cast<Identifier>(persistentId(ResolvePointer(ptr, *classElement, *m_context)));
}
else
{
AZStd::string indexedName = AZStd::string::format("%s_%d", classData->m_name, m_curParentNode->m_children.size() - 1);
node->m_identifier = static_cast<Identifier>(AZ::Crc32(indexedName.c_str()));
}
}
}
else
{
// Not in a container, just use crc.
node->m_identifier = classElement->m_nameCrc;
}
}
else if (classData)
{
// Root level, use crc of class type.
node->m_identifier = AZ_CRC(classData->m_name);
}
AZ_Assert(node->m_identifier != InvalidIdentifier, "InstanceDataNode has an invalid identifier. Addressing will not be valid.");
}
// if our data contains dynamic edit data handler, push it on the stack
if (classData && classData->m_editData && classData->m_editData->m_editDataProvider)
{
m_editDataOverrides.push_back();
m_editDataOverrides.back().m_override = classData->m_editData->m_editDataProvider;
m_editDataOverrides.back().m_overridingInstance = ptr;
m_editDataOverrides.back().m_overridingNode = node;
}
// Resolve the group metadata for this element
AZ::Edit::ClassData* parentEditData = (node->GetParent() && node->GetParent()->GetClassMetadata()) ? node->GetParent()->GetClassMetadata()->m_editData : nullptr;
if (parentEditData)
{
// Dig through the class elements in the parent structure looking for groups. Apply the last group created
// to this node
const AZ::Edit::ElementData* groupData = nullptr;
for (const AZ::Edit::ElementData& elementData : parentEditData->m_elements)
{
if (node->m_elementEditData == &elementData) // this element matches this node
{
// Record the last found group data
node->m_groupElementData = groupData;
break;
}
else if (elementData.IsClassElement() && elementData.m_elementId == AZ::Edit::ClassElements::Group)
{
if (!elementData.m_description || !elementData.m_description[0])
{ // close the group
groupData = nullptr;
}
else
{
groupData = &elementData;
}
}
}
}
m_curParentNode = node;
return true;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::EndNode()
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
AZ_Assert(m_curParentNode, "EndEnum called without a matching BeginNode call!");
if (!m_nodeDiscarded)
{
if (m_isMerging)
{
for (NodeContainer::iterator it = m_curParentNode->m_children.begin(); it != m_curParentNode->m_children.end(); )
{
// If we are merging and we did not match this node, remove it from the hierarchy.
if (!it->m_matched)
{
it = m_curParentNode->m_children.erase(it);
}
else
{
++it;
}
}
}
// if the node we are leaving pushed an edit data override, then pop it.
if (!m_editDataOverrides.empty() && m_editDataOverrides.back().m_overridingNode == m_curParentNode)
{
m_editDataOverrides.pop_back();
}
m_curParentNode = m_curParentNode->m_parent;
}
m_nodeDiscarded = false;
return true;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::RefreshComparisonData(unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
if (!m_root || m_comparisonInstances.empty())
{
return false;
}
bool allDataMatches = true;
// Clear comparison data.
AZStd::vector<InstanceDataNode*> stack;
stack.reserve(32);
stack.push_back(this);
while (!stack.empty())
{
InstanceDataNode* node = stack.back();
stack.pop_back();
node->ClearComparisonData();
for (auto childIterator = node->m_children.begin(); childIterator != node->m_children.end();)
{
// Remove any fake nodes that have been added
if (childIterator->IsRemovedVersusComparison())
{
childIterator = node->m_children.erase(childIterator);
}
else
{
stack.push_back(&(*childIterator));
++childIterator;
}
}
}
// Generate a hierarchy for the comparison instance.
m_comparisonHierarchies.clear();
for (const InstanceData& comparisonInstance : m_comparisonInstances)
{
AZ_Assert(comparisonInstance.m_classId == m_rootInstances[0].m_classId, "Compare instance type does not match root instance type.");
m_comparisonHierarchies.emplace_back(aznew InstanceDataHierarchy());
auto& comparisonHierarchy = m_comparisonHierarchies.back();
comparisonHierarchy->AddRootInstance(comparisonInstance.m_instance, comparisonInstance.m_classId);
comparisonHierarchy->Build(m_root->GetSerializeContext(), accessFlags, dynamicEditDataProvider);
// Compare the two hierarchies...
if (comparisonHierarchy->m_root)
{
AZStd::vector<AZ::u8> sourceBuffer, targetBuffer;
CompareHierarchies(comparisonHierarchy->m_root, m_root, sourceBuffer, targetBuffer, m_valueComparisonFunction, m_root->GetSerializeContext(),
// New node
[&allDataMatches](InstanceDataNode* targetNode, AZStd::vector<AZ::u8>& data)
{
(void)data;
if (!targetNode->IsNewVersusComparison())
{
targetNode->MarkNewVersusComparison();
allDataMatches = false;
}
},
// Removed node (container element).
[&allDataMatches](const InstanceDataNode* sourceNode, InstanceDataNode* targetNodeParent)
{
(void)sourceNode;
// Mark the parent as modified.
if (targetNodeParent)
{
// Insert a node to mark the removed element, with no data, but relating to the node in the source hierarchy.
targetNodeParent->m_children.push_back();
InstanceDataNode& removedMarker = targetNodeParent->m_children.back();
removedMarker = *sourceNode;
removedMarker.m_instances.clear();
removedMarker.m_children.clear();
removedMarker.m_comparisonNode = sourceNode;
removedMarker.m_parent = targetNodeParent;
removedMarker.m_root = targetNodeParent->m_root;
removedMarker.m_context = targetNodeParent->m_context;
removedMarker.MarkRemovedVersusComparison();
targetNodeParent->MarkDifferentVersusComparison();
}
allDataMatches = false;
},
// Changed node
[&allDataMatches](const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
AZStd::vector<AZ::u8>& sourceData, AZStd::vector<AZ::u8>& targetData)
{
(void)sourceData;
(void)targetData;
if (!targetNode->IsDifferentVersusComparison())
{
targetNode->m_comparisonNode = sourceNode;
targetNode->MarkDifferentVersusComparison();
}
allDataMatches = false;
}
);
}
}
return allDataMatches;
}
//-----------------------------------------------------------------------------
InstanceDataNode* InstanceDataHierarchy::FindNodeByAddress(const InstanceDataNode::Address& address) const
{
if (m_root && !address.empty())
{
if (m_root->m_identifier != address.back())
{
// If this hierarchy's root isn't the same as the root in the address (the last entry), not going to find it here
return nullptr;
}
else if (address.size() == 1)
{
// The only address in the list is the root node, matches root node
return m_root;
}
InstanceDataNode* currentNode = m_root;
size_t addressIndex = address.size() - 2;
while (currentNode)
{
InstanceDataNode* parent = currentNode;
currentNode = nullptr;
for (InstanceDataNode& child : parent->m_children)
{
if (child.m_identifier == address[addressIndex])
{
currentNode = &child;
if (addressIndex > 0)
{
--addressIndex;
break;
}
else
{
return currentNode;
}
}
}
}
}
return nullptr;
}
/// Locate a node by partial address (bfs to find closest match)
InstanceDataNode* InstanceDataHierarchy::FindNodeByPartialAddress(const InstanceDataNode::Address& address) const
{
// ensure we have atleast a root and a valid address to search
if (m_root && !address.empty())
{
AZStd::queue<InstanceDataNode*> children;
children.push(m_root);
// work our way down the hierarchy in a bfs search
size_t addressIndex = address.size() - 1;
while (children.size() > 0)
{
InstanceDataNode* curr = children.front();
children.pop();
// if we find property - move down the hierarchy
if (curr->m_identifier == address[addressIndex])
{
if (addressIndex > 0)
{
// clear existing list as we don't care about
// these elements anymore
while (!children.empty())
{
children.pop();
}
children.push(curr);
--addressIndex;
}
else
{
return curr;
}
}
// build fifo list of children to search
for (InstanceDataNode& child : curr->m_children)
{
children.push(&child);
}
}
}
return nullptr;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::DefaultValueComparisonFunction(const InstanceDataNode* sourceNode, const InstanceDataNode* targetNode)
{
// special case - while its possible for instance comparisons to differ, if one has an instance, and the other does not, they are definitely
// not equal!
if (sourceNode->GetNumInstances() == 0)
{
if (targetNode->GetNumInstances() == 0)
{
return true;
}
return false;
}
else if (targetNode->GetNumInstances() == 0)
{
return false;
}
else if (!targetNode->m_classData || !sourceNode->m_classData)
{
return targetNode->m_classData == sourceNode->m_classData;
}
return targetNode->m_classData->m_serializer->CompareValueData(sourceNode->FirstInstance(), targetNode->FirstInstance());
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::SetValueComparisonFunction(const ValueComparisonFunction& function)
{
m_valueComparisonFunction = function ? function : DefaultValueComparisonFunction;
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::CompareHierarchies(const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
const ValueComparisonFunction& valueComparisonFunction,
AZ::SerializeContext* context,
NewNodeCB newNodeCallback,
RemovedNodeCB removedNodeCallback,
ChangedNodeCB changedNodeCallback)
{
AZ_Assert(sourceNode->GetSerializeContext() == targetNode->GetSerializeContext(),
"Attempting to compare hierarchies from different serialization contexts.");
AZStd::vector<AZ::u8> sourceBuffer, targetBuffer;
CompareHierarchies(sourceNode, targetNode, sourceBuffer, targetBuffer, valueComparisonFunction, context, newNodeCallback, removedNodeCallback, changedNodeCallback);
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::CompareHierarchies(const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
AZStd::vector<AZ::u8>& tempSourceBuffer,
AZStd::vector<AZ::u8>& tempTargetBuffer,
const ValueComparisonFunction& valueComparisonFunction,
AZ::SerializeContext* context,
NewNodeCB newNodeCallback,
RemovedNodeCB removedNodeCallback,
ChangedNodeCB changedNodeCallback)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
targetNode->m_comparisonNode = sourceNode;
if (!targetNode->m_classData || !sourceNode->m_classData)
{
return;
}
else if (targetNode->m_classData->m_typeId == sourceNode->m_classData->m_typeId)
{
if (targetNode->m_classData->m_container)
{
// Find elements in the container that have been added or modified.
for (InstanceDataNode& targetElementNode : targetNode->m_children)
{
if (targetElementNode.IsRemovedVersusComparison())
{
continue; // Don't compare removal placeholders.
}
const InstanceDataNode* sourceNodeMatch = nullptr;
for (const InstanceDataNode& sourceElementNode : sourceNode->m_children)
{
if (sourceElementNode.m_identifier == targetElementNode.m_identifier)
{
sourceNodeMatch = &sourceElementNode;
break;
}
}
if (sourceNodeMatch)
{
// The element exists, drill down.
CompareHierarchies(sourceNodeMatch, &targetElementNode, tempSourceBuffer, tempTargetBuffer, valueComparisonFunction, context,
newNodeCallback, removedNodeCallback, changedNodeCallback);
}
else
{
// This is a new element in the container.
AZStd::vector<AZ::u8> buffer;
AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8> > stream(&buffer);
if (!AZ::Utils::SaveObjectToStream(stream, AZ::ObjectStream::ST_BINARY, targetElementNode.GetInstance(0), targetElementNode.m_classData->m_typeId, context, targetElementNode.m_classData))
{
AZ_Assert(false, "Unable to serialize class %s, SaveObjectToStream() failed.", targetElementNode.m_classData->m_name);
}
// Mark targetElementNode and all of its children, and their children, and their... as new
AZStd::vector<InstanceDataNode*> stack;
stack.reserve(32);
stack.push_back(&targetElementNode);
while (!stack.empty())
{
InstanceDataNode* node = stack.back();
stack.pop_back();
newNodeCallback(node, buffer);
// Don't do the children if the current node represents a component since it will add as one whole thing
if (!node->GetClassMetadata() || !node->GetClassMetadata()->m_azRtti || !node->GetClassMetadata()->m_azRtti->IsTypeOf(AZ::Component::RTTI_Type()))
{
for (InstanceDataNode& child : node->m_children)
{
stack.push_back(&child);
}
}
}
}
}
// Find elements that've been removed.
for (const InstanceDataNode& sourceElementNode : sourceNode->m_children)
{
bool isRemoved = true;
for (InstanceDataNode& targetElementNode : targetNode->m_children)
{
if (sourceElementNode.m_identifier == targetElementNode.m_identifier)
{
isRemoved = false;
break;
}
}
if (isRemoved)
{
removedNodeCallback(&sourceElementNode, targetNode);
}
}
}
else if (targetNode->m_classData->m_serializer)
{
AZ_Assert(targetNode->m_classData == sourceNode->m_classData, "Comparison raw data for mismatched types.");
if (!valueComparisonFunction(sourceNode, targetNode))
{
// This is a leaf element (has a direct serializer), so it's a data change.
tempSourceBuffer.clear();
tempTargetBuffer.clear();
AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8> > sourceStream(&tempSourceBuffer), targetStream(&tempTargetBuffer);
targetNode->m_classData->m_serializer->Save(targetNode->GetInstance(0), targetStream);
sourceNode->m_classData->m_serializer->Save(sourceNode->GetInstance(0), sourceStream);
changedNodeCallback(sourceNode, targetNode, tempSourceBuffer, tempTargetBuffer);
}
}
else
{
// This isn't a container; just drill down on child elements.
if (targetNode->m_children.size() == sourceNode->m_children.size())
{
auto targetElementIt = targetNode->m_children.begin();
auto sourceElementIt = sourceNode->m_children.begin();
while (targetElementIt != targetNode->m_children.end())
{
CompareHierarchies(&(*sourceElementIt), &(*targetElementIt), tempSourceBuffer, tempTargetBuffer, valueComparisonFunction, context,
newNodeCallback, removedNodeCallback, changedNodeCallback);
++sourceElementIt;
++targetElementIt;
}
}
else
{
AZ_Error("Serializer", targetNode->m_children.size() == sourceNode->m_children.size(),
"Non-container elements have mismatched sub-element counts. This a recoverable error, "
"but the entire sub-hierarchy will be considered differing as no further drill-down is possible.");
tempSourceBuffer.clear();
tempTargetBuffer.clear();
changedNodeCallback(sourceNode, targetNode, tempSourceBuffer, tempTargetBuffer);
}
}
}
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::CopyInstanceData(const InstanceDataNode* sourceNode,
InstanceDataNode* targetNode,
AZ::SerializeContext* context,
ContainerChildNodeBeingRemovedCB containerChildNodeBeingRemovedCB,
ContainerChildNodeBeingCreatedCB containerChildNodeBeingCreatedCB,
const InstanceDataNode::Address& filterElementAddress)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
if (sourceNode->ShouldComparisonBeIgnored())
{
return true;
}
if (!context)
{
AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
AZ_Assert(context, "Failed to retrieve application serialization context");
}
const AZ::SerializeContext::ClassData* sourceClass = sourceNode->GetClassMetadata();
const AZ::SerializeContext::ClassData* targetClass = targetNode->GetClassMetadata();
if (!sourceClass || !targetClass)
{
return false;
}
if (sourceClass->m_typeId == targetClass->m_typeId)
{
// Drill down and apply adds/removes/copies as we go.
bool result = true;
if (targetClass->m_eventHandler)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
targetClass->m_eventHandler->OnWriteBegin(targetNode->GetInstance(i));
}
}
if (sourceClass->m_serializer)
{
// These are leaf elements, we can just copy directly.
AZStd::vector<AZ::u8> sourceBuffer;
AZ::IO::ByteContainerStream<decltype(sourceBuffer)> sourceStream(&sourceBuffer);
sourceClass->m_serializer->Save(sourceNode->GetInstance(0), sourceStream);
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
sourceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
targetClass->m_serializer->Load(targetNode->GetInstance(i), sourceStream, sourceClass->m_version);
}
}
else
{
// Storage to track elements to be added or removed to reflect differences between
// source and target container contents.
using InstancePair = AZStd::pair<void*, void*>;
AZStd::vector<InstancePair> elementsToRemove;
AZStd::vector<const InstanceDataNode*> elementsToAdd;
// If we're operating on a container, we need to identify any items in the target
// node that don't exist in the source, and remove them.
if (sourceClass->m_container)
{
for (auto targetChildIter = targetNode->GetChildren().begin(); targetChildIter != targetNode->GetChildren().end(); )
{
InstanceDataNode& targetChild = *targetChildIter;
// Skip placeholders, or if we're filtering for a different element.
if ((targetChild.IsRemovedVersusComparison()) ||
(!filterElementAddress.empty() && filterElementAddress != targetChild.ComputeAddress()))
{
++targetChildIter;
continue;
}
bool sourceFound = false;
bool removedElement = false;
for (const InstanceDataNode& sourceChild : sourceNode->GetChildren())
{
if (sourceChild.IsRemovedVersusComparison())
{
continue;
}
if (sourceChild.m_identifier == targetChild.m_identifier)
{
sourceFound = true;
break;
}
}
if (!sourceFound)
{
AZ_Assert(targetClass->m_container, "Hierarchy mismatch occurred, but not on a container element.");
if (targetClass->m_container)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
elementsToRemove.push_back(AZStd::make_pair(targetNode->GetInstance(i), targetChild.m_instances[i]));
}
if (containerChildNodeBeingRemovedCB)
{
containerChildNodeBeingRemovedCB(&targetChild);
}
// The child hierarchy node can be deleted. We'll free the actual container elements in a safe manner below.
targetChildIter = targetNode->GetChildren().erase(targetChildIter);
removedElement = true;
}
}
if (!removedElement)
{
++targetChildIter;
}
}
}
// Recursively deep-copy any differences.
for (const InstanceDataNode& sourceChild : sourceNode->GetChildren())
{
bool matchedChild = false;
// Skip placeholders, or if we're filtering for an element that isn't the sourceChild or one of it's descendants.
if ((sourceChild.IsRemovedVersusComparison()) ||
(!filterElementAddress.empty() && filterElementAddress != sourceChild.ComputeAddress() && !sourceChild.ChildMatchesAddress(filterElementAddress)))
{
continue;
}
// For each source child, locate the respective target child and drill down.
for (InstanceDataNode& targetChild : targetNode->GetChildren())
{
if (targetChild.IsRemovedVersusComparison())
{
continue;
}
if (targetChild.m_identifier == sourceChild.m_identifier)
{
matchedChild = true;
const AZ::SerializeContext::ClassData* targetClassData = targetChild.GetClassMetadata();
const AZ::SerializeContext::ClassData* sourceClassData = sourceChild.GetClassMetadata();
// are these proxy nodes?
if (!targetClassData && !sourceClassData)
{
continue;
}
else if (targetClassData->m_typeId != sourceClassData->m_typeId)
{
AZStd::string sourceTypeId;
AZStd::string targetTypeId;
sourceClassData->m_typeId.ToString(sourceTypeId);
targetClassData->m_typeId.ToString(targetTypeId);
AZ_Error("Serializer", false, "Nodes with same identifier are not of the same serializable type: types \"%s\" : %s and \"%s\" : %s.",
sourceClassData->m_name, sourceTypeId.c_str(), targetClassData->m_name, targetTypeId.c_str());
return false;
}
// Recurse on child elements.
if (!CopyInstanceData(&sourceChild, &targetChild, context, containerChildNodeBeingRemovedCB, containerChildNodeBeingCreatedCB, filterElementAddress))
{
result = false;
break;
}
}
}
if (matchedChild)
{
continue;
}
// The target node was not found.
// This occurs if the source is a container, and contains an element that the target does not.
AZ_Assert(targetClass->m_container, "Hierarchy mismatch occurred, but not on a container element.");
if (result && targetClass->m_container)
{
elementsToAdd.push_back(&sourceChild);
}
}
// After iterating through all children to apply changes, it's now safe to commit element removals and additions.
// Containers may grow during additions, or shift during removals, so we can't do it while iterating and recursing
// on elements to apply data differences.
//
// Apply element removals.
//
// Sort element removals in reverse memory order for compatibility with contiguous-memory containers.
AZStd::sort(elementsToRemove.begin(), elementsToRemove.end(),
[](const InstancePair& lhs, const InstancePair& rhs)
{
return rhs.second < lhs.second;
}
);
// Finally, remove elements from the target container that weren't present in the source.
for (const auto& pair : elementsToRemove)
{
targetClass->m_container->RemoveElement(pair.first, pair.second, context);
}
//
// Apply element additions.
//
// After iterating through all children to apply changes, it's now safe to commit element additions.
// Containers may grow/reallocate, so we can't do it while iterating.
for (const InstanceDataNode* sourceChildToAdd : elementsToAdd)
{
if (containerChildNodeBeingCreatedCB)
{
containerChildNodeBeingCreatedCB(sourceChildToAdd, targetNode);
}
// Serialize out the entire source element.
AZStd::vector<AZ::u8> sourceBuffer;
AZ::IO::ByteContainerStream<decltype(sourceBuffer)> sourceStream(&sourceBuffer);
bool savedToStream = AZ::Utils::SaveObjectToStream(
sourceStream, AZ::DataStream::ST_BINARY, sourceChildToAdd->GetInstance(0), context, sourceChildToAdd->GetClassMetadata());
(void)savedToStream;
AZ_Assert(savedToStream, "Failed to save source element to data stream.");
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
// Add a new element to the target container.
void* targetInstance = targetNode->GetInstance(i);
void* targetPointer = targetClass->m_container->ReserveElement(targetInstance, sourceChildToAdd->m_classElement);
AZ_Assert(targetPointer, "Failed to allocate container element");
if (sourceChildToAdd->GetClassMetadata() && sourceChildToAdd->m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// It's a container of pointers, so allocate a new target class instance.
AZ_Assert(sourceChildToAdd->GetClassMetadata()->m_factory != nullptr, "We are attempting to create '%s', but no factory is provided! Either provide factory or change data member '%s' to value not pointer!", sourceNode->m_classData->m_name, sourceNode->m_classElement->m_name);
void* newTargetPointer = sourceChildToAdd->m_classData->m_factory->Create(sourceChildToAdd->m_classData->m_name);
(void)newTargetPointer;
void* basePtr = context->DownCast(
newTargetPointer,
sourceChildToAdd->m_classData->m_typeId,
sourceChildToAdd->m_classElement->m_typeId,
sourceChildToAdd->m_classData->m_azRtti,
sourceChildToAdd->m_classElement->m_azRtti);
AZ_Assert(basePtr != nullptr, sourceClass->m_container
? "Can't cast container element %s(0x%x) to %s, make sure classes are registered in the system and not generics!"
: "Can't cast %s(0x%x) to %s, make sure classes are registered in the system and not generics!"
, sourceChildToAdd->m_classElement->m_name ? sourceChildToAdd->m_classElement->m_name : "NULL"
, sourceChildToAdd->m_classElement->m_nameCrc
, sourceChildToAdd->m_classData->m_name);
// Store ptr to the new instance in the container element.
*reinterpret_cast<void**>(targetPointer) = basePtr;
targetPointer = newTargetPointer;
}
// Deserialize in-place.
sourceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
bool loadedFromStream = AZ::Utils::LoadObjectFromStreamInPlace(
sourceStream, context, sourceChildToAdd->GetClassMetadata(), targetPointer, AZ::ObjectStream::FilterDescriptor(AZ::Data::AssetFilterNoAssetLoading));
(void)loadedFromStream;
AZ_Assert(loadedFromStream, "Failed to copy element to target.");
// Some containers, such as AZStd::map require you to call StoreElement to actually consider the element part of the structure
// Since the container is unable to put an uninitialized element into its tree until the key is known
targetClass->m_container->StoreElement(targetInstance, targetPointer);
}
}
}
if (targetClass->m_eventHandler)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
targetClass->m_eventHandler->OnWriteEnd(targetNode->GetInstance(i));
}
}
return result;
}
return false;
}
//-----------------------------------------------------------------------------
} // namespace Property System
| 44.097748 | 304 | 0.527325 |
283d232e0cebdcfedf5e47e2e5af2153ff8b129a | 7,202 | cpp | C++ | inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | null | null | null | inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 16 | 2021-04-19T13:03:04.000Z | 2022-02-21T13:06:50.000Z | inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <fstream>
#include <ie_core.hpp>
#include <ie_layouts.h>
#include "shared_test_classes/base/layer_test_utils.hpp"
#include "functional_test_utils/blob_utils.hpp"
#include "ngraph_functions/utils/ngraph_helpers.hpp"
#include "ngraph_functions/builders.hpp"
typedef std::tuple<
std::vector<size_t>, // Input shape
InferenceEngine::Precision, // Network Precision
std::string, // Target Device
std::map<std::string, std::string>, // Export Configuration
std::map<std::string, std::string> // Import Configuration
> exportImportNetworkParams;
namespace LayerTestsDefinitions {
class ImportActConvActTest : public testing::WithParamInterface<exportImportNetworkParams>,
public LayerTestsUtils::LayerTestsCommon {
public:
static std::string getTestCaseName(testing::TestParamInfo<exportImportNetworkParams> obj) {
std::vector<size_t> inputShape;
InferenceEngine::Precision netPrecision;
std::string targetDevice;
std::map<std::string, std::string> exportConfiguration;
std::map<std::string, std::string> importConfiguration;
std::tie(inputShape, netPrecision, targetDevice, exportConfiguration, importConfiguration) = obj.param;
std::ostringstream result;
result << "netPRC=" << netPrecision.name() << "_";
result << "targetDevice=" << targetDevice << "_";
for (auto const &configItem : exportConfiguration) {
result << "_exportConfigItem=" << configItem.first << "_" << configItem.second;
}
for (auto const &configItem : importConfiguration) {
result << "_importConfigItem=" << configItem.first << "_" << configItem.second;
}
result << CommonTestUtils::vec2str(inputShape);
return result.str();
}
void Run() override {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
configuration.insert(exportConfiguration.begin(), exportConfiguration.end());
LoadNetwork();
GenerateInputs();
Infer();
executableNetwork.Export("exported_model.blob");
for (auto const &configItem : importConfiguration) {
configuration[configItem.first] = configItem.second;
}
std::fstream inputStream("exported_model.blob", std::ios_base::in | std::ios_base::binary);
if (inputStream.fail()) {
FAIL() << "Cannot open file to import model: exported_model.blob";
}
auto importedNetwork = core->ImportNetwork(inputStream, targetDevice, configuration);
// Generate inputs
std::vector<InferenceEngine::Blob::Ptr> inputs;
auto inputsInfo = importedNetwork.GetInputsInfo();
auto functionParams = function->get_parameters();
for (int i = 0; i < functionParams.size(); ++i) {
const auto& param = functionParams[i];
const auto infoIt = inputsInfo.find(param->get_friendly_name());
GTEST_ASSERT_NE(infoIt, inputsInfo.cend());
const auto& info = infoIt->second;
auto blob = GenerateInput(*info);
inputs.push_back(blob);
}
// Infer imported network
InferenceEngine::InferRequest importInfer = importedNetwork.CreateInferRequest();
inputsInfo = importedNetwork.GetInputsInfo();
functionParams = function->get_parameters();
for (int i = 0; i < functionParams.size(); ++i) {
const auto& param = functionParams[i];
const auto infoIt = inputsInfo.find(param->get_friendly_name());
GTEST_ASSERT_NE(infoIt, inputsInfo.cend());
const auto& info = infoIt->second;
auto blob = inputs[i];
importInfer.SetBlob(info->name(), blob);
}
importInfer.Infer();
// Validate
auto expectedOutputs = CalculateRefs();
auto actualOutputs = std::vector<InferenceEngine::Blob::Ptr>{};
for (const auto &output : importedNetwork.GetOutputsInfo()) {
const auto &name = output.first;
actualOutputs.push_back(importInfer.GetBlob(name));
}
IE_ASSERT(actualOutputs.size() == expectedOutputs.size())
<< "nGraph interpreter has " << expectedOutputs.size() << " outputs, while IE " << actualOutputs.size();
Compare(expectedOutputs, actualOutputs);
}
protected:
void SetUp() override {
std::vector<size_t> inputShape;
InferenceEngine::Precision netPrecision;
std::tie(inputShape, netPrecision, targetDevice, exportConfiguration, importConfiguration) = this->GetParam();
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto params = ngraph::builder::makeParams(ngPrc, {inputShape});
auto relu1 = std::make_shared<ngraph::opset1::Relu>(params[0]);
size_t num_out_channels = 8;
size_t kernel_size = 8;
std::vector<float> filter_weights = CommonTestUtils::generate_float_numbers(num_out_channels * inputShape[1] * kernel_size,
-0.2f, 0.2f);
auto conv = ngraph::builder::makeConvolution(relu1, ngPrc, { 1, kernel_size }, { 1, 1 }, { 0, 0 }, { 0, 0 }, { 1, 1 },
ngraph::op::PadType::VALID, num_out_channels, true, filter_weights);
auto relu2 = std::make_shared<ngraph::opset1::Relu>(conv);
ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(relu2)};
function = std::make_shared<ngraph::Function>(results, params, "ExportImportNetwork");
}
private:
std::map<std::string, std::string> exportConfiguration;
std::map<std::string, std::string> importConfiguration;
};
TEST_P(ImportActConvActTest, CompareWithRefImpl) {
Run();
};
const std::vector<std::vector<size_t>> inputShape = {
{1, 1, 1, 240},
{1, 1, 1, 160},
{1, 2, 1, 80}
};
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16
};
const std::vector<std::map<std::string, std::string>> exportConfigs = {
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"}
}
};
const std::vector<std::map<std::string, std::string>> importConfigs = {
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"}
}
};
INSTANTIATE_TEST_CASE_P(smoke_ImportActConvAct, ImportActConvActTest,
::testing::Combine(
::testing::ValuesIn(inputShape),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_GNA),
::testing::ValuesIn(exportConfigs),
::testing::ValuesIn(importConfigs)),
ImportActConvActTest::getTestCaseName);
} // namespace LayerTestsDefinitions
| 40.234637 | 131 | 0.620383 |
2841971e0bff9a57c920a04ac25df9ef4a1e9c4d | 5,126 | cpp | C++ | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | #include "GEvent.h"
GEvent::GEvent() {
}
GEvent::~GEvent() {
//Do nothing
}
void GEvent::OnEvent(SDL_Event* event) {
switch(event->type) {
case SDL_KEYDOWN: {
OnKeyDown(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_KEYUP: {
OnKeyUp(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_MOUSEMOTION: {
OnMouseMove(event->motion.x,event->motion.y,event->motion.xrel,event->motion.yrel,(event->motion.state&SDL_BUTTON(SDL_BUTTON_LEFT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_RIGHT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_MIDDLE))!=0);
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonDown(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonUp(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_JOYAXISMOTION: {
OnJoyAxis(event->jaxis.which,event->jaxis.axis,event->jaxis.value);
break;
}
case SDL_JOYBALLMOTION: {
OnJoyBall(event->jball.which,event->jball.ball,event->jball.xrel,event->jball.yrel);
break;
}
case SDL_JOYHATMOTION: {
OnJoyHat(event->jhat.which,event->jhat.hat,event->jhat.value);
break;
}
case SDL_JOYBUTTONDOWN: {
OnJoyButtonDown(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_JOYBUTTONUP: {
OnJoyButtonUp(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_QUIT: {
OnExit();
break;
}
case SDL_SYSWMEVENT: {
//Ignore
break;
}
// case SDL_VIDEORESIZE: {
// OnResize(event->resize.w,event->resize.h);
// break;
// }
// case SDL_VIDEOEXPOSE: {
// OnExpose();
// break;
// }
default: {
OnUser(event->user.type,event->user.code,event->user.data1,event->user.data2);
break;
}
}
}
void GEvent::OnInputFocus() {
//Pure virtual, do nothing
}
void GEvent::OnInputBlur() {
//Pure virtual, do nothing
}
void GEvent::OnKeyDown(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnKeyUp(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnMouseFocus() {
//Pure virtual, do nothing
}
void GEvent::OnMouseBlur() {
//Pure virtual, do nothing
}
void GEvent::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle) {
//Pure virtual, do nothing
}
void GEvent::OnMouseWheel(bool Up, bool Down) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnJoyAxis(Uint8 which,Uint8 axis,Sint16 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonDown(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonUp(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyHat(Uint8 which,Uint8 hat,Uint8 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyBall(Uint8 which,Uint8 ball,Sint16 xrel,Sint16 yrel) {
//Pure virtual, do nothing
}
void GEvent::OnMinimize() {
//Pure virtual, do nothing
}
void GEvent::OnRestore() {
//Pure virtual, do nothing
}
void GEvent::OnResize(int w,int h) {
//Pure virtual, do nothing
}
void GEvent::OnExpose() {
//Pure virtual, do nothing
}
void GEvent::OnExit() {
//Pure virtual, do nothing
}
void GEvent::OnUser(Uint8 type, int code, void* data1, void* data2) {
//Pure virtual, do nothing
}
| 23.953271 | 257 | 0.558525 |
2842442eca960d8309112fd16fcafecfcf29aab9 | 21,655 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/EmilyWindow.cc,v 1.6 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: EmilyWindow.cc,v $
* Revision 1.6 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
* Revision 1.13 1992/02/19 17:31:05 sterling
* enabled setclasinfo when in surtomize mode
*
* Revision 1.11 1992/02/18 01:11:37 lewis
* Use new version support.
*
* Revision 1.9 1992/02/04 22:55:26 lewis
* Use GetShell().GetExtent (), not just GetExtent () for wiundows.
* (maybe should be referencing mainview??).
*
* Revision 1.6 1992/01/31 18:21:58 sterling
* Bootstrapped
*
*/
#include <fstream.h>
#include "Debug.hh"
#include "StreamUtils.hh"
#include "Version.hh"
#include "CommandNumbers.hh"
#include "Dialog.hh"
#include "NumberText.hh"
#include "MenuOwner.hh"
#include "Shell.hh"
#include "CheckBox.hh"
#include "DeskTop.hh"
#include "Language.hh"
#include "EmilyApplication.hh"
#include "ItemPallet.hh"
#include "EmilyWindow.hh"
#include "MainGroupItem.hh"
#include "ClassInfo.hh"
#if qMacUI
CommandNumber EmilyWindow::sCurrentGUI = eMacUI;
#elif qMotifUI
CommandNumber EmilyWindow::sCurrentGUI = eMotifUI;
#elif qWindowsGUI
CommandNumber EmilyWindow::sCurrentGUI = eWindowsGUI;
#endif
CommandNumber EmilyWindow::sCurrentLanguage = eEnglish;
Boolean EmilyWindow::sCustomizeOnly = False;
/*
********************************************************************************
*********************************** EmilyWindow ********************************
********************************************************************************
*/
EmilyWindow::EmilyWindow (EmilyDocument& document):
Window (),
Saveable (1),
fDocument (document),
fClassName ("foo"),
fBaseClass ("View"),
fHeaderPrepend (kEmptyString),
fHeaderAppend (kEmptyString),
fSourcePrepend (kEmptyString),
fSourceAppend (kEmptyString),
fDataPrepend (kEmptyString),
fStringCount (1),
fGrid (EmilyApplication::Get ().GetGrid ()),
fGridVisible (EmilyApplication::Get ().GetGridVisible ()),
#if qMacUI
fGUI (eMacUI),
#elif qMotifUI
fGUI (eMotifUI),
#elif qWindowsGUI
fGUI (eWindowsGUI),
#endif
fLanguage (eEnglish)
{
fMainGroup = new MainGroupItem (*this);
SetMainViewAndTargets (fMainGroup, fMainGroup, fMainGroup);
SetWindowController (&fDocument);
fMainGroup->ResetCustomizeOnly ();
}
EmilyWindow::~EmilyWindow ()
{
SetMainViewAndTargets (Nil, Nil, Nil);
}
EmilyDocument& EmilyWindow::GetDocument ()
{
return (fDocument);
}
void EmilyWindow::PrintPage (PageNumber /*pageNumber*/, class Printer& printer)
{
RequireNotNil (GetMainView ());
printer.DrawView (*GetMainView (), kZeroPoint);
}
void EmilyWindow::CalcPages (PageNumber& userStart, PageNumber& userEnd, const Rect& /*pageRect*/)
{
userStart = 1;
userEnd = 1;
}
PageNumber EmilyWindow::CalcAllPages (const Rect& /*pageRect*/)
{
return (1);
}
void EmilyWindow::DoSetupMenus ()
{
Window::DoSetupMenus ();
SetOn (GetGUI (), True);
SetOn (GetLanguage (), True);
SetOn (eCustomizeOnly, sCustomizeOnly);
EnableCommand (eSetClassInfo);
EnableCommand (eCustomizeOnly);
EnableCommand (eArrow);
EnableCommand (eThumb);
if (ItemPallet::GetEditMode () and (not sCustomizeOnly)) {
for (CommandNumber cmd = eFirstBuildItem; cmd <= eLastBuildItem; cmd++) {
EnableCommand (cmd, ItemPallet::ShouldEnable (cmd));
}
}
#if !qUseCustomMenu
if (ItemPallet::GetSelectedItem () != Nil) {
ItemPallet::GetSelectedItem ()->SetOn (Toggle::kOn, Panel::eNoUpdate);
}
#endif
}
class SetClassInfoCommand : public Command {
public:
SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info);
~SetClassInfoCommand ();
override void DoIt ();
override void UnDoIt ();
private:
EmilyWindow& fWindow;
String fNewClassName;
String fOldClassName;
String fNewBaseClassName;
String fOldBaseClassName;
Point fNewSize;
Point fOldSize;
String fNewHelp;
String fOldHelp;
const Font* fNewFont;
const Font* fOldFont;
Boolean fOldAutoSize;
Boolean fNewAutoSize;
};
SetClassInfoCommand::SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info) :
Command (eSetClassInfo, kUndoable),
fWindow (window),
fNewClassName (info.GetClassNameField ().GetText ()),
fOldClassName (window.fClassName),
fNewBaseClassName (info.GetBaseClassNameField ().GetText ()),
fOldBaseClassName (window.fBaseClass),
fNewSize (Point (info.GetSizeVField ().GetValue (), info.GetSizeHField ().GetValue ())),
fOldSize (window.GetMainGroup ().GetScrollSize ()),
fNewHelp (info.GetHelpField ().GetText ()),
fOldHelp (window.GetMainGroup ().GetHelp ()),
fNewFont (info.fFont),
fOldFont (window.GetMainGroup ().GetFont ()),
fOldAutoSize (window.GetMainGroup ().GetAutoSize ()),
fNewAutoSize (info.GetAutoSizeField ().GetOn ())
{
if (fNewFont != Nil) {
fNewFont = new Font (*fNewFont);
}
if (fOldFont != Nil) {
fOldFont = new Font (*fOldFont);
}
}
SetClassInfoCommand::~SetClassInfoCommand ()
{
delete fNewFont;
delete fOldFont;
}
void SetClassInfoCommand::DoIt ()
{
fWindow.fClassName = fNewClassName;
fWindow.fBaseClass = fNewBaseClassName;
fWindow.GetMainGroup ().SetHelp (fNewHelp);
if (fNewSize != fOldSize) {
if (not fNewAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fNewSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fNewFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().SetAutoSize (fNewAutoSize);
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::DoIt ();
}
void SetClassInfoCommand::UnDoIt ()
{
fWindow.fClassName = fOldClassName;
fWindow.fBaseClass = fOldBaseClassName;
fWindow.GetMainGroup ().SetHelp (fOldHelp);
fWindow.GetMainGroup ().SetAutoSize (fOldAutoSize);
if ((fNewSize != fOldSize) or (fNewAutoSize != fOldAutoSize)) {
if (not fOldAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fOldSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fOldFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::UnDoIt ();
}
Boolean EmilyWindow::DoCommand (const CommandSelection& selection)
{
switch (selection.GetCommandNumber ()) {
case eSetClassInfo:
{
ClassInfo info = ClassInfo (GetMainGroup ());
info.GetClassNameField ().SetText (fClassName);
info.GetBaseClassNameField ().SetText (fBaseClass);
info.GetSizeVField ().SetValue (GetMainGroup ().GetScrollSize ().GetV ());
info.GetSizeHField ().SetValue (GetMainGroup ().GetScrollSize ().GetH ());
info.GetHelpField ().SetText (GetMainGroup ().GetHelp ());
info.GetAutoSizeField ().SetOn (GetMainGroup ().GetAutoSize ());
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetClassInfoCommand (*this, info));
PostCommand (new DocumentDirtier (GetDocument ()));
}
}
return (True);
case eMacUI:
case eMotifUI:
case eWindowsGUI:
SetGUI (selection.GetCommandNumber ());
return (True);
case eEnglish:
case eFrench:
case eGerman:
case eItalian:
case eSpanish:
case eJapanese:
SetLanguage (selection.GetCommandNumber ());
return (True);
case eCustomizeOnly:
if (sCustomizeOnly) {
SetLanguage (fLanguage);
SetGUI (fGUI);
}
SetCustomizeOnly (not sCustomizeOnly);
return (True);
default:
return (Window::DoCommand (selection));
}
}
MainGroupItem& EmilyWindow::GetMainGroup () const
{
RequireNotNil (fMainGroup);
return (*fMainGroup);
}
static const String kMachineCodeStartString = "// text before here will be retained: Do not remove or modify this line!!!";
static const String kMachineCodeEndString = "// text past here will be retained: Do not remove or modify this line!!!";
void EmilyWindow::DoRead_ (class istream& from)
{
char bigBuf [1000];
fDataPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fDataPrepend += s;
fDataPrepend += "\n";
}
}
char c;
from >> c;
from.putback (c);
if (c == 'D') {
// read off data file creation tag
from.getline (bigBuf, sizeof (bigBuf));
from.getline (bigBuf, sizeof (bigBuf));
}
Saveable::DoRead_ (from);
Rect extent = kZeroRect;
from >> extent;
WindowShellHints hints = GetShell ().GetWindowShellHints ();
#if 0
if (extent.GetOrigin () < DeskTop::Get ().GetBounds ().GetBounds ().GetOrigin ()) {
hints.SetDesiredOrigin (extent.GetOrigin ());
}
#endif
hints.SetDesiredSize (extent.GetSize ());
GetShell ().SetWindowShellHints (hints);
ReadString (from, fClassName);
ReadString (from, fBaseClass);
sCustomizeOnly = True;
GetMainGroup ().DoRead (from);
sCustomizeOnly = False;
GetMainGroup ().ResetCustomizeOnly ();
}
void EmilyWindow::DoWrite_ (class ostream& to, int tabCount) const
{
if (fDataPrepend != kEmptyString) {
to << fDataPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String appLongVersion = kApplicationVersion.GetLongVersionString ();
Assert (appLongVersion != kEmptyString);
to << "Data file written by " << appLongVersion << "." << newline;
to << newline << newline;
Saveable::DoWrite_ (to, tabCount);
to << newline;
to << GetShell ().GetExtent () << newline << newline;
WriteString (to, fClassName);
WriteString (to, fBaseClass);
GetMainGroup ().ResetFieldCounter ();
GetMainGroup ().DoWrite (to, tabCount);
to << newline;
}
void EmilyWindow::ReadHeaderFile (class istream& from)
{
char bigBuf [1000];
fHeaderPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fHeaderPrepend += s;
fHeaderPrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fHeaderAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fHeaderAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteHeaderFile (class ostream& to)
{
if (fHeaderPrepend != kEmptyString) {
to << fHeaderPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String compilationVariable = "__" + fClassName + "__";
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#ifndef " << compilationVariable << newline;
to << "#define " << compilationVariable << newline << newline;
}
static const String kViewString = "View";
static const String kGroupViewString = "GroupView";
static const String kLabelGroupString = "LabeledGroup";
Boolean generateBaseClasses = Boolean ((fBaseClass == kViewString) or (fBaseClass == kGroupViewString) or (fBaseClass == kLabelGroupString));
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << "#include " << quote << "Button.hh" << quote << newline;
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << "#include " << quote << "FocusItem.hh" << quote << newline;
}
if (GetMainGroup ().IsSlider ()) {
to << "#include " << quote << "Slider.hh" << quote << newline;
}
if (GetMainGroup ().IsText ()) {
to << "#include " << quote << "TextEdit.hh" << quote << newline;
}
to << "#include " << quote << "View.hh" << quote << newline;
to << newline;
}
GetMainGroup ().WriteIncludes (to, 0);
to << newline << newline;
to << "class "<< fClassName << " : public " << fBaseClass;
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << ", public ButtonController";
}
if (GetMainGroup ().IsSlider ()) {
to << ", public SliderController";
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << ", public FocusOwner";
}
if (GetMainGroup ().IsText ()) {
to << ", public TextController";
}
}
to << " {" << newline << tab << "public:" << newline;
// declare constructor
to << tab (2) << fClassName << " ();" << newline;
// declare destructor
to << tab (2) << "~" << fClassName << " ();" << newline << newline;
// declare CalcDefaultSize method
to << tab (2) << "override" << tab << "Point" << tab << "CalcDefaultSize_ (const Point& defaultSize) const;" << newline << newline;
// declare layout method
to << tab << "protected:" << newline;
to << tab (2) << "override" << tab << "void" << tab << "Layout ();" << newline << newline;
// declare fields
GetMainGroup ().WriteDeclaration (to, 2);
to << newline << tab << "private:" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab (2) << "nonvirtual void" << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << newline;
to << "};" << newline << newline;
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#endif /* " << compilationVariable << " */" << newline;
}
to << newline << newline << kMachineCodeEndString << newline;
if (fHeaderAppend != kEmptyString) {
to << fHeaderAppend;
}
}
void EmilyWindow::ReadSourceFile (class istream& from)
{
char bigBuf [1000];
fSourcePrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fSourcePrepend += s;
fSourcePrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fSourceAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fSourceAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteSourceFile (class ostream& to)
{
if (fSourcePrepend != kEmptyString) {
to << fSourcePrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline << newline;
to << "#include " << quote << "Language.hh" << quote << newline;
to << "#include " << quote << "Shape.hh" << quote << newline;
to << newline;
to << "#include " << quote << fDocument.GetHeaderFilePathName ().GetFileName () << quote << newline << newline << newline;
// define constructor
to << fClassName << "::" << fClassName << " ()";
// init fields to zero, in case of exception so we do right thing freeing them...
StringStream tempTo; // we use a stringstream to nuke the trailing comma
tempTo << " :" << newline;
GetMainGroup ().WriteBuilder (tempTo, 1);
String initializers = String (tempTo);
if (initializers.GetLength () > 2) {
// still have bad stream bug where zero length returns -1
initializers.SetLength (initializers.GetLength () -2); // one for comma, one for newline
}
else {
initializers.SetLength (0);
}
to << initializers << newline;
to << "{" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define destructor
to << fClassName << "::~" << fClassName << " ()" << newline;
to << "{" << newline;
GetMainGroup ().WriteDestructor (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
// define GUI builders
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << newline;
to << "#elif q";
}
to << directive << newline << newline;
to << "void" << tab << fClassName << "::BuildFor" << directive << " ()" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, gui);
to << "}" << newline;
}
}
Assert (not first); // must have at least one gui
to << newline << "#else" << newline << newline;
to << "void" << tab << fClassName << "::BuildForUnknownGUI ();" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
to << "#endif /* GUI */" << newline << newline;
// define CalcDefaultSize method
to << "Point" << tab << fClassName << "::CalcDefaultSize_ (const Point& /*defaultSize*/) const" << newline << "{" << newline;
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q" << directive << newline;
first = False;
}
else {
to << "#elif q" << directive << newline;
}
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), gui);
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
}
}
Assert (not first);
to << "#else" << newline;
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), GetMainGroup ().GetBaseGUI ());
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define layout method
to << "void" << tab << fClassName << "::Layout ()" << newline << "{" << newline;
GetMainGroup ().WriteLayout (to, 1);
to << tab << fBaseClass << "::Layout ();" << newline;
to << "}" << newline;
to << newline << newline << kMachineCodeEndString << newline;
if (fSourceAppend != kEmptyString) {
to << fSourceAppend;
}
}
void EmilyWindow::EditModeChanged (Boolean newEditMode)
{
MenuOwner::SetMenusOutOfDate ();
GetMainGroup ().EditModeChanged (newEditMode);
}
CommandNumber EmilyWindow::GetGUI ()
{
return (sCurrentGUI);
}
void EmilyWindow::SetGUI (CommandNumber gui)
{
if (sCurrentGUI != gui) {
CommandNumber oldGUI = sCurrentGUI;
sCurrentGUI = gui;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentGUI == eMacUI) {
SetBackground (&kWhiteTile);
}
else if (sCurrentGUI == eMotifUI) {
Tile t = PalletManager::Get ().MakeTileFromColor (kGrayColor);
SetBackground (&t);
}
else if (sCurrentGUI == eWindowsGUI) {
SetBackground (&kWhiteTile);
}
GetMainGroup ().GUIChanged (oldGUI, sCurrentGUI);
GetMainGroup ().Refresh ();
SetMainView (fMainGroup); // what a ridiculous hack to get it to resize stuff!!!
GetMainGroup ().Refresh ();
Update ();
}
}
CommandNumber EmilyWindow::GetLanguage ()
{
return (sCurrentLanguage);
}
void EmilyWindow::SetLanguage (CommandNumber language)
{
if (sCurrentLanguage != language) {
CommandNumber oldLanguage = sCurrentLanguage;
sCurrentLanguage = language;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentLanguage != fLanguage) {
SetCustomizeOnly (True);
}
else if (sCurrentGUI == fGUI) {
SetCustomizeOnly (False);
}
GetMainGroup ().LanguageChanged (oldLanguage, sCurrentLanguage);
}
}
Boolean EmilyWindow::GetCustomizeOnly ()
{
return (sCustomizeOnly);
}
Boolean EmilyWindow::GetFullEditing ()
{
return (not sCustomizeOnly);
}
void EmilyWindow::SetCustomizeOnly (Boolean customizeOnly)
{
if (sCustomizeOnly != customizeOnly) {
sCustomizeOnly = customizeOnly;
MenuOwner::SetMenusOutOfDate ();
}
}
String GetGUICompilationDirective (CommandNumber gui)
{
switch (gui) {
case eMacUI:
return ("MacUI");
case eMotifUI:
return ("MotifUI");
case eWindowsGUI:
return ("WindowsGUI");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
String GetLanguageCompilationDirective (CommandNumber language)
{
switch (language) {
case eEnglish:
return ("English");
case eFrench:
return ("French");
case eGerman:
return ("German");
case eItalian:
return ("Italian");
case eSpanish:
return ("Spanish");
case eJapanese:
return ("Japanese");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
| 27.136591 | 142 | 0.652274 |
2842d743a10cb05257b9106962481d8d684edc81 | 626 | cpp | C++ | LGPUtil/LGPExitSystem.cpp | chen0040/cpp-linear-genetic-programming | 8b0bc8701110af0b7506546e527bd03f57d972fe | [
"MIT"
] | 3 | 2018-01-09T06:03:23.000Z | 2020-12-29T20:09:44.000Z | LGPUtil/LGPExitSystem.cpp | chen0040/cpp-linear-genetic-programming | 8b0bc8701110af0b7506546e527bd03f57d972fe | [
"MIT"
] | 1 | 2017-11-15T04:24:43.000Z | 2017-11-18T02:17:12.000Z | LGPUtil/LGPExitSystem.cpp | chen0040/cpp-linear-genetic-programming | 8b0bc8701110af0b7506546e527bd03f57d972fe | [
"MIT"
] | 2 | 2017-09-17T04:24:24.000Z | 2020-01-29T05:35:49.000Z | #include "LGPExitSystem.h"
#include <cstdlib>
#include <iostream>
#include "LGPLogger.h"
#include "../LGPConstants/LGPFlags.h"
#include <cassert>
void LGPExitSystem(const char* fname, const char* ename)
{
std::cout << "An error has occurred in the LGP System..." << std::endl;
std::cout << "Source: " << fname << std::endl;
std::cout << "Error: " << ename << std::endl;
lgpLogger.err << "An error has occurred in the LGP System..." << std::endl;
lgpLogger.err << "Source: " << fname << std::endl;
lgpLogger.err << "Error: " << ename << std::endl;
#ifdef LGP_BUILD_DEBUG
assert(false);
#else
std::exit(0);
#endif
} | 25.04 | 76 | 0.65016 |
2843f15a5aaff39464478839a47483251844600c | 998 | cpp | C++ | out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp | bluey-crypto/Hacktoberfest | c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba | [
"MIT"
] | 4 | 2019-10-12T13:54:20.000Z | 2021-07-06T22:41:12.000Z | out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp | bluey-crypto/Hacktoberfest | c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba | [
"MIT"
] | 1 | 2020-10-01T18:03:45.000Z | 2020-10-01T18:03:45.000Z | out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp | bluey-crypto/Hacktoberfest | c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba | [
"MIT"
] | 8 | 2019-10-14T17:20:09.000Z | 2020-10-03T17:27:49.000Z | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=0;j<n-i;j++)
cout<<" ";
for(int j=i;j<=2*i-1;j++)
cout<<j;
for(int j=i;j)
cout<<j;
cout<<endl;
}
}
/* #include <iostream>
using namespace std;
int main()
{
int rows, count = 0, count1 = 0, k = 0;
cin >> rows;
for(int i = 1; i <= rows; ++i)
{
for(int space = 1; space <= rows-i; ++space)
{
cout << " ";
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
cout << i+k << " ";
++count;
}
else
{
++count1;
cout << i+k-2*count1 << " ";
}
++k;
}
count1 = count = k = 0;
cout << endl;
}
return 0;
}*/
| 16.360656 | 52 | 0.316633 |
2845626b754d5b1438c031a49a8a2ce15d1f8187 | 1,098 | cpp | C++ | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | 41 | 2021-06-25T14:20:29.000Z | 2022-01-16T02:50:50.000Z | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | /*! \file
\brief A node constraint element.
Copyright (C) 2019-2022 kaoru https://www.tetengo.org/
*/
#include <memory>
#include <utility>
#include <boost/core/noncopyable.hpp>
#include <tetengo/lattice/node.hpp>
#include <tetengo/lattice/node_constraint_element.hpp>
namespace tetengo::lattice
{
class node_constraint_element::impl : private boost::noncopyable
{
public:
// constructors and destructor
explicit impl(node node_) : m_node{ std::move(node_) } {}
// functions
int matches_impl(const node& node_) const
{
return node_ == m_node ? 0 : -1;
}
private:
// variables
const node m_node;
};
node_constraint_element::node_constraint_element(node node_) : m_p_impl{ std::make_unique<impl>(std::move(node_)) }
{}
node_constraint_element::~node_constraint_element() = default;
int node_constraint_element::matches_impl(const node& node_) const
{
return m_p_impl->matches_impl(node_);
}
}
| 20.716981 | 120 | 0.618397 |
284919a0184a7378e69887339cc4337bee738d8b | 3,664 | cpp | C++ | src/software/sensor_fusion/filter/robot_team_filter_test.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | src/software/sensor_fusion/filter/robot_team_filter_test.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | src/software/sensor_fusion/filter/robot_team_filter_test.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | /**
* This file contains the unit tests for the implementation of RobotTeamFilter class
*/
#include "software/sensor_fusion/filter/robot_team_filter.h"
#include <gtest/gtest.h>
#include <string.h>
TEST(RobotTeamFilterTest, one_robot_detection_update_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
// old team starts with a robot with id = 0
old_team.updateRobots(
{Robot(0, Point(0, 1), Vector(-1, -2), Angle::half(),
AngularVelocity::threeQuarter(), Timestamp::fromSeconds(0))});
robot_detection.id = 0;
robot_detection.position = Point(1.0, -2.5);
robot_detection.orientation = Angle::fromRadians(0.5);
robot_detection.confidence = 1.0;
robot_detection.timestamp = Timestamp::fromSeconds(1);
robot_detections.push_back(robot_detection);
// robot detection also has id = 0
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
auto robots = new_team.getAllRobots();
EXPECT_EQ(1, robots.size());
EXPECT_EQ(robot_detection.position, robots[0].currentState().robotState().position());
EXPECT_EQ(robot_detection.orientation,
robots[0].currentState().robotState().orientation());
EXPECT_EQ(robot_detection.timestamp, robots[0].currentState().timestamp());
}
TEST(RobotTeamFilterTest, detections_with_same_timestamp_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
unsigned int num_robots = 6;
for (unsigned int i = 0; i < num_robots; i++)
{
robot_detection.id = i;
robot_detection.position = Point(Vector(0.5, -0.25) * i);
robot_detection.orientation = Angle::fromRadians(0.1 * i);
robot_detection.confidence = i / ((double)num_robots);
robot_detection.timestamp = Timestamp::fromSeconds(.5);
robot_detections.push_back(robot_detection);
}
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
EXPECT_EQ(num_robots, new_team.numRobots());
for (unsigned int i = 0; i < num_robots; i++)
{
EXPECT_NE(std::nullopt, new_team.getRobotById(i));
Robot robot = *new_team.getRobotById(i);
EXPECT_EQ(robot_detections[i].position,
robot.currentState().robotState().position());
EXPECT_EQ(robot_detections[i].orientation,
robot.currentState().robotState().orientation());
EXPECT_EQ(robot_detections[i].timestamp, robot.currentState().timestamp());
}
}
TEST(RobotTeamFilterTest, detections_with_different_times_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
unsigned int num_robots = 6;
for (unsigned int i = 0; i < num_robots; i++)
{
robot_detection.id = i;
robot_detection.position = Point(Vector(0.5, -0.25) * i);
robot_detection.orientation = Angle::fromRadians(0.1 * i);
robot_detection.confidence = i / ((double)num_robots);
// use different timestamps for each detection
robot_detection.timestamp = Timestamp::fromSeconds(i);
robot_detections.push_back(robot_detection);
}
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
EXPECT_EQ(1, new_team.numRobots());
}
| 37.387755 | 90 | 0.692959 |
284adc7198c21a8493c908069d40743f3fb42d30 | 73,997 | cpp | C++ | catboost/libs/model/model.cpp | notimesea/catboost | 1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce | [
"Apache-2.0"
] | null | null | null | catboost/libs/model/model.cpp | notimesea/catboost | 1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce | [
"Apache-2.0"
] | null | null | null | catboost/libs/model/model.cpp | notimesea/catboost | 1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce | [
"Apache-2.0"
] | null | null | null | #include "model.h"
#include "flatbuffers_serializer_helper.h"
#include "model_import_interface.h"
#include "model_build_helper.h"
#include "static_ctr_provider.h"
#include <catboost/libs/model/flatbuffers/model.fbs.h>
#include <catboost/libs/cat_feature/cat_feature.h>
#include <catboost/libs/helpers/borders_io.h>
#include <catboost/libs/logging/logging.h>
#include <catboost/private/libs/options/enum_helpers.h>
#include <catboost/private/libs/options/json_helper.h>
#include <catboost/private/libs/options/loss_description.h>
#include <catboost/private/libs/options/class_label_options.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/dbg_output/dump.h>
#include <library/cpp/dbg_output/auto.h>
#include <util/generic/algorithm.h>
#include <util/generic/cast.h>
#include <util/generic/fwd.h>
#include <util/generic/guid.h>
#include <util/generic/variant.h>
#include <util/generic/xrange.h>
#include <util/generic/ylimits.h>
#include <util/generic/ymath.h>
#include <util/string/builder.h>
#include <util/stream/str.h>
static const char MODEL_FILE_DESCRIPTOR_CHARS[4] = {'C', 'B', 'M', '1'};
static void ReferenceMainFactoryRegistrators() {
// We HAVE TO manually reference some pointers to make factory registrators work. Blessed static linking!
CB_ENSURE(NCB::NModelEvaluation::CPUEvaluationBackendRegistratorPointer);
CB_ENSURE(NCB::BinaryModelLoaderRegistratorPointer);
}
static ui32 GetModelFormatDescriptor() {
return *reinterpret_cast<const ui32*>(MODEL_FILE_DESCRIPTOR_CHARS);
}
static const char* CURRENT_CORE_FORMAT_STRING = "FlabuffersModel_v1";
void OutputModel(const TFullModel& model, IOutputStream* const out) {
Save(out, model);
}
void OutputModel(const TFullModel& model, const TStringBuf modelFile) {
TOFStream f(TString{modelFile}); // {} because of the most vexing parse
OutputModel(model, &f);
}
bool IsDeserializableModelFormat(EModelType format) {
return NCB::TModelLoaderFactory::Has(format);
}
static void CheckFormat(EModelType format) {
ReferenceMainFactoryRegistrators();
CB_ENSURE(
NCB::TModelLoaderFactory::Has(format),
"Model format " << format << " deserialization not supported or missing. Link with catboost/libs/model/model_export if you need CoreML or JSON"
);
}
TFullModel ReadModel(const TString& modelFile, EModelType format) {
CheckFormat(format);
THolder<NCB::IModelLoader> modelLoader(NCB::TModelLoaderFactory::Construct(format));
return modelLoader->ReadModel(modelFile);
}
TFullModel ReadModel(const void* binaryBuffer, size_t binaryBufferSize, EModelType format) {
CheckFormat(format);
THolder<NCB::IModelLoader> modelLoader(NCB::TModelLoaderFactory::Construct(format));
return modelLoader->ReadModel(binaryBuffer, binaryBufferSize);
}
TFullModel ReadZeroCopyModel(const void* binaryBuffer, size_t binaryBufferSize) {
TFullModel model;
model.InitNonOwning(binaryBuffer, binaryBufferSize);
return model;
}
TString SerializeModel(const TFullModel& model) {
TStringStream ss;
OutputModel(model, &ss);
return ss.Str();
}
TFullModel DeserializeModel(TMemoryInput serializedModel) {
TFullModel model;
Load(&serializedModel, model);
return model;
}
TFullModel DeserializeModel(const TString& serializedModel) {
return DeserializeModel(TMemoryInput{serializedModel.data(), serializedModel.size()});
}
struct TSolidModelTree : IModelTreeData {
TConstArrayRef<int> GetTreeSplits() const override;
TConstArrayRef<int> GetTreeSizes() const override;
TConstArrayRef<int> GetTreeStartOffsets() const override;
TConstArrayRef<TNonSymmetricTreeStepNode> GetNonSymmetricStepNodes() const override;
TConstArrayRef<ui32> GetNonSymmetricNodeIdToLeafId() const override;
TConstArrayRef<double> GetLeafValues() const override;
TConstArrayRef<double> GetLeafWeights() const override;
THolder<IModelTreeData> Clone(ECloningPolicy policy) const override;
void SetTreeSplits(const TVector<int>&) override;
void SetTreeSizes(const TVector<int>&) override;
void SetTreeStartOffsets(const TVector<int>&) override;
void SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) override;
void SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) override;
void SetLeafValues(const TVector<double>&) override;
void SetLeafWeights(const TVector<double>&) override;
TVector<int> TreeSplits;
TVector<int> TreeSizes;
TVector<int> TreeStartOffsets;
TVector<TNonSymmetricTreeStepNode> NonSymmetricStepNodes;
TVector<ui32> NonSymmetricNodeIdToLeafId;
TVector<double> LeafValues;
TVector<double> LeafWeights;
};
static TSolidModelTree* CastToSolidTree(const TModelTrees& trees) {
auto ptr = dynamic_cast<TSolidModelTree*>(trees.GetModelTreeData().Get());
CB_ENSURE(ptr, "Only solid models are modifiable");
return ptr;
}
struct TOpaqueModelTree : IModelTreeData {
TConstArrayRef<int> GetTreeSplits() const override;
TConstArrayRef<int> GetTreeSizes() const override;
TConstArrayRef<int> GetTreeStartOffsets() const override;
TConstArrayRef<TNonSymmetricTreeStepNode> GetNonSymmetricStepNodes() const override;
TConstArrayRef<ui32> GetNonSymmetricNodeIdToLeafId() const override;
TConstArrayRef<double> GetLeafValues() const override;
TConstArrayRef<double> GetLeafWeights() const override;
THolder<IModelTreeData> Clone(ECloningPolicy policy) const override;
void SetTreeSplits(const TVector<int>&) override;
void SetTreeSizes(const TVector<int>&) override;
void SetTreeStartOffsets(const TVector<int>&) override;
void SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) override;
void SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) override;
void SetLeafValues(const TVector<double>&) override;
void SetLeafWeights(const TVector<double>&) override;
TConstArrayRef<int> TreeSplits;
TConstArrayRef<int> TreeSizes;
TConstArrayRef<int> TreeStartOffsets;
TConstArrayRef<TNonSymmetricTreeStepNode> NonSymmetricStepNodes;
TConstArrayRef<ui32> NonSymmetricNodeIdToLeafId;
TConstArrayRef<double> LeafValues;
TConstArrayRef<double> LeafWeights;
};
static TOpaqueModelTree* CastToOpaqueTree(const TModelTrees& trees) {
auto ptr = dynamic_cast<TOpaqueModelTree*>(trees.GetModelTreeData().Get());
CB_ENSURE(ptr, "Not an opaque model");
return ptr;
}
TModelTrees::TModelTrees() {
ModelTreeData = MakeHolder<TSolidModelTree>();
UpdateRuntimeData();
}
void TModelTrees::ProcessSplitsSet(
const TSet<TModelSplit>& modelSplitSet,
const TVector<size_t>& floatFeaturesInternalIndexesMap,
const TVector<size_t>& catFeaturesInternalIndexesMap,
const TVector<size_t>& textFeaturesInternalIndexesMap,
const TVector<size_t>& embeddingFeaturesInternalIndexesMap
) {
THashSet<int> usedCatFeatureIndexes;
THashSet<int> usedTextFeatureIndexes;
THashSet<int> usedEmbeddingFeatureIndexes;
for (const auto& split : modelSplitSet) {
if (split.Type == ESplitType::FloatFeature) {
const size_t internalFloatIndex = floatFeaturesInternalIndexesMap.at((size_t)split.FloatFeature.FloatFeature);
FloatFeatures.at(internalFloatIndex).Borders.push_back(split.FloatFeature.Split);
} else if (split.Type == ESplitType::EstimatedFeature) {
const TEstimatedFeatureSplit estimatedFeatureSplit = split.EstimatedFeature;
EEstimatedSourceFeatureType featureType;
if (std::find(textFeaturesInternalIndexesMap.begin(),
textFeaturesInternalIndexesMap.end(),
estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId) !=
textFeaturesInternalIndexesMap.end()) {
usedTextFeatureIndexes.insert(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId);
featureType = EEstimatedSourceFeatureType::Text;
} else {
usedEmbeddingFeatureIndexes.insert(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId);
featureType = EEstimatedSourceFeatureType::Embedding;
}
if (EstimatedFeatures.empty() ||
EstimatedFeatures.back().ModelEstimatedFeature != estimatedFeatureSplit.ModelEstimatedFeature
) {
TEstimatedFeature estimatedFeature(estimatedFeatureSplit.ModelEstimatedFeature);
Y_ASSERT(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureType == featureType);
EstimatedFeatures.emplace_back(estimatedFeature);
}
EstimatedFeatures.back().Borders.push_back(estimatedFeatureSplit.Split);
} else if (split.Type == ESplitType::OneHotFeature) {
usedCatFeatureIndexes.insert(split.OneHotFeature.CatFeatureIdx);
if (OneHotFeatures.empty() || OneHotFeatures.back().CatFeatureIndex != split.OneHotFeature.CatFeatureIdx) {
auto& ref = OneHotFeatures.emplace_back();
ref.CatFeatureIndex = split.OneHotFeature.CatFeatureIdx;
}
OneHotFeatures.back().Values.push_back(split.OneHotFeature.Value);
} else {
const auto& projection = split.OnlineCtr.Ctr.Base.Projection;
usedCatFeatureIndexes.insert(projection.CatFeatures.begin(), projection.CatFeatures.end());
if (CtrFeatures.empty() || CtrFeatures.back().Ctr != split.OnlineCtr.Ctr) {
CtrFeatures.emplace_back();
CtrFeatures.back().Ctr = split.OnlineCtr.Ctr;
}
CtrFeatures.back().Borders.push_back(split.OnlineCtr.Border);
}
}
for (const int usedCatFeatureIdx : usedCatFeatureIndexes) {
CatFeatures[catFeaturesInternalIndexesMap.at(usedCatFeatureIdx)].SetUsedInModel(true);
}
for (const int usedTextFeatureIdx : usedTextFeatureIndexes) {
TextFeatures[textFeaturesInternalIndexesMap.at(usedTextFeatureIdx)].SetUsedInModel(true);
}
for (const int usedEmbeddingFeatureIdx : usedEmbeddingFeatureIndexes) {
EmbeddingFeatures[embeddingFeaturesInternalIndexesMap.at(usedEmbeddingFeatureIdx)].SetUsedInModel(true);
}
}
void TModelTrees::AddBinTree(const TVector<int>& binSplits) {
auto& data = *CastToSolidTree(*this);
Y_ASSERT(data.TreeSizes.size() == data.TreeStartOffsets.size() && data.TreeSplits.empty() == data.TreeSizes.empty());
data.TreeSplits.insert(data.TreeSplits.end(), binSplits.begin(), binSplits.end());
if (data.TreeStartOffsets.empty()) {
data.TreeStartOffsets.push_back(0);
} else {
data.TreeStartOffsets.push_back(data.TreeStartOffsets.back() + data.TreeSizes.back());
}
data.TreeSizes.push_back(binSplits.ysize());
}
void TModelTrees::ClearLeafWeights() {
CastToSolidTree(*this)->LeafWeights.clear();
}
void TModelTrees::AddTreeSplit(int treeSplit) {
CastToSolidTree(*this)->TreeSplits.push_back(treeSplit);
}
void TModelTrees::AddTreeSize(int treeSize) {
auto& data = *CastToSolidTree(*this);
if (data.TreeStartOffsets.empty()) {
data.TreeStartOffsets.push_back(0);
} else {
data.TreeStartOffsets.push_back(data.TreeStartOffsets.back() + data.TreeSizes.back());
}
data.TreeSizes.push_back(treeSize);
}
void TModelTrees::AddLeafValue(double leafValue) {
CastToSolidTree(*this)->LeafValues.push_back(leafValue);
}
void TModelTrees::AddLeafWeight(double leafWeight) {
CastToSolidTree(*this)->LeafWeights.push_back(leafWeight);
}
bool TModelTrees::IsSolid() const {
return dynamic_cast<TSolidModelTree*>(ModelTreeData.Get());
}
void TModelTrees::TruncateTrees(size_t begin, size_t end) {
//TODO(eermishkina): support non symmetric trees
CB_ENSURE(IsOblivious(), "Truncate support only symmetric trees");
CB_ENSURE(begin <= end, "begin tree index should be not greater than end tree index.");
CB_ENSURE(end <= GetModelTreeData()->GetTreeSplits().size(), "end tree index should be not greater than tree count.");
auto savedScaleAndBias = GetScaleAndBias();
TObliviousTreeBuilder builder(FloatFeatures,
CatFeatures,
TextFeatures,
EmbeddingFeatures,
ApproxDimension);
auto applyData = GetApplyData();
const auto& leafOffsets = applyData->TreeFirstLeafOffsets;
const auto treeSizes = GetModelTreeData()->GetTreeSizes();
const auto treeSplits = GetModelTreeData()->GetTreeSplits();
const auto leafValues = GetModelTreeData()->GetLeafValues();
const auto leafWeights = GetModelTreeData()->GetLeafWeights();
const auto treeStartOffsets = GetModelTreeData()->GetTreeStartOffsets();
for (size_t treeIdx = begin; treeIdx < end; ++treeIdx) {
TVector<TModelSplit> modelSplits;
for (int splitIdx = treeStartOffsets[treeIdx];
splitIdx < treeStartOffsets[treeIdx] + treeSizes[treeIdx];
++splitIdx)
{
modelSplits.push_back(GetBinFeatures()[treeSplits[splitIdx]]);
}
TConstArrayRef<double> leafValuesRef(
leafValues.begin() + leafOffsets[treeIdx],
leafValues.begin() + leafOffsets[treeIdx] + ApproxDimension * (1u << treeSizes[treeIdx])
);
builder.AddTree(
modelSplits,
leafValuesRef,
leafWeights.empty() ? TConstArrayRef<double>() : TConstArrayRef<double>(
leafWeights.begin() + leafOffsets[treeIdx] / ApproxDimension,
leafWeights.begin() + leafOffsets[treeIdx] / ApproxDimension + (1ull << treeSizes[treeIdx])
)
);
}
builder.Build(this);
this->SetScaleAndBias(savedScaleAndBias);
}
flatbuffers::Offset<NCatBoostFbs::TModelTrees>
TModelTrees::FBSerialize(TModelPartsCachingSerializer& serializer) const {
auto& builder = serializer.FlatbufBuilder;
std::vector<flatbuffers::Offset<NCatBoostFbs::TCatFeature>> catFeaturesOffsets;
for (const auto& catFeature : CatFeatures) {
catFeaturesOffsets.push_back(catFeature.FBSerialize(builder));
}
auto fbsCatFeaturesOffsets = builder.CreateVector(catFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TFloatFeature>> floatFeaturesOffsets;
for (const auto& floatFeature : FloatFeatures) {
floatFeaturesOffsets.push_back(floatFeature.FBSerialize(builder));
}
auto fbsFloatFeaturesOffsets = builder.CreateVector(floatFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TTextFeature>> textFeaturesOffsets;
for (const auto& textFeature : TextFeatures) {
textFeaturesOffsets.push_back(textFeature.FBSerialize(builder));
}
auto fbsTextFeaturesOffsets = builder.CreateVector(textFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TEmbeddingFeature>> embeddingFeaturesOffsets;
for (const auto& embeddingFeature : EmbeddingFeatures) {
embeddingFeaturesOffsets.push_back(embeddingFeature.FBSerialize(builder));
}
auto fbsEmbeddingFeaturesOffsets = builder.CreateVector(embeddingFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TEstimatedFeature>> estimatedFeaturesOffsets;
for (const auto& estimatedFeature : EstimatedFeatures) {
estimatedFeaturesOffsets.push_back(estimatedFeature.FBSerialize(builder));
}
auto fbsEstimatedFeaturesOffsets = builder.CreateVector(estimatedFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TOneHotFeature>> oneHotFeaturesOffsets;
for (const auto& oneHotFeature : OneHotFeatures) {
oneHotFeaturesOffsets.push_back(oneHotFeature.FBSerialize(builder));
}
auto fbsOneHotFeaturesOffsets = builder.CreateVector(oneHotFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TCtrFeature>> ctrFeaturesOffsets;
for (const auto& ctrFeature : CtrFeatures) {
ctrFeaturesOffsets.push_back(ctrFeature.FBSerialize(serializer));
}
auto fbsCtrFeaturesOffsets = builder.CreateVector(ctrFeaturesOffsets);
TVector<NCatBoostFbs::TNonSymmetricTreeStepNode> nonSymmetricTreeStepNode;
nonSymmetricTreeStepNode.reserve(GetModelTreeData()->GetNonSymmetricStepNodes().size());
for (const auto& nonSymmetricStep: GetModelTreeData()->GetNonSymmetricStepNodes()) {
nonSymmetricTreeStepNode.emplace_back(NCatBoostFbs::TNonSymmetricTreeStepNode{
nonSymmetricStep.LeftSubtreeDiff,
nonSymmetricStep.RightSubtreeDiff
});
}
auto fbsNonSymmetricTreeStepNode = builder.CreateVectorOfStructs(nonSymmetricTreeStepNode);
TVector<NCatBoostFbs::TRepackedBin> repackedBins;
repackedBins.reserve(GetRepackedBins().size());
for (const auto& repackedBin: GetRepackedBins()) {
repackedBins.emplace_back(NCatBoostFbs::TRepackedBin{
repackedBin.FeatureIndex,
repackedBin.XorMask,
repackedBin.SplitIdx
});
}
auto fbsRepackedBins = builder.CreateVectorOfStructs(repackedBins);
auto& data = GetModelTreeData();
auto fbsTreeSplits = builder.CreateVector(data->GetTreeSplits().data(), data->GetTreeSplits().size());
auto fbsTreeSizes = builder.CreateVector(data->GetTreeSizes().data(), data->GetTreeSizes().size());
auto fbsTreeStartOffsets = builder.CreateVector(data->GetTreeStartOffsets().data(), data->GetTreeStartOffsets().size());
auto fbsLeafValues = builder.CreateVector(data->GetLeafValues().data(), data->GetLeafValues().size());
auto fbsLeafWeights = builder.CreateVector(data->GetLeafWeights().data(), data->GetLeafWeights().size());
auto fbsNonSymmetricNodeIdToLeafId = builder.CreateVector(data->GetNonSymmetricNodeIdToLeafId().data(), data->GetNonSymmetricNodeIdToLeafId().size());
auto bias = GetScaleAndBias().GetBiasRef();
auto fbsBias = builder.CreateVector(bias.data(), bias.size());
return NCatBoostFbs::CreateTModelTrees(
builder,
ApproxDimension,
fbsTreeSplits,
fbsTreeSizes,
fbsTreeStartOffsets,
fbsCatFeaturesOffsets,
fbsFloatFeaturesOffsets,
fbsOneHotFeaturesOffsets,
fbsCtrFeaturesOffsets,
fbsLeafValues,
fbsLeafWeights,
fbsNonSymmetricTreeStepNode,
fbsNonSymmetricNodeIdToLeafId,
fbsTextFeaturesOffsets,
fbsEstimatedFeaturesOffsets,
GetScaleAndBias().Scale,
0,
fbsBias,
fbsRepackedBins,
fbsEmbeddingFeaturesOffsets
);
}
static_assert(sizeof(TRepackedBin) == sizeof(NCatBoostFbs::TRepackedBin));
void TModelTrees::UpdateRuntimeData() {
CalcForApplyData();
CalcBinFeatures();
}
void TModelTrees::ProcessFloatFeatures() {
for (const auto& feature : FloatFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedFloatFeaturesCount;
ApplyData->MinimalSufficientFloatFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessCatFeatures() {
for (const auto& feature : CatFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedCatFeaturesCount;
ApplyData->MinimalSufficientCatFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessTextFeatures() {
for (const auto& feature : TextFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedTextFeaturesCount;
ApplyData->MinimalSufficientTextFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessEmbeddingFeatures() {
for (const auto& feature : TextFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedEmbeddingFeaturesCount;
ApplyData->MinimalSufficientEmbeddingFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessEstimatedFeatures() {
ApplyData->UsedEstimatedFeaturesCount = EstimatedFeatures.size();
}
void TModelTrees::CalcBinFeatures() {
auto runtimeData = MakeAtomicShared<TRuntimeData>();
struct TFeatureSplitId {
ui32 FeatureIdx = 0;
ui32 SplitIdx = 0;
};
TVector<TFeatureSplitId> splitIds;
auto& ref = *runtimeData;
for (const auto& feature : FloatFeatures) {
if (!feature.UsedInModel()) {
continue;
}
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TFloatSplit fs{feature.Position.Index, feature.Borders[borderId]};
ref.BinFeatures.emplace_back(fs);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (const auto& feature : EstimatedFeatures) {
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TEstimatedFeatureSplit split{
feature.ModelEstimatedFeature,
feature.Borders[borderId]
};
ref.BinFeatures.emplace_back(split);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (const auto& feature : OneHotFeatures) {
for (int valueId = 0; valueId < feature.Values.ysize(); ++valueId) {
TOneHotSplit oh{feature.CatFeatureIndex, feature.Values[valueId]};
ref.BinFeatures.emplace_back(oh);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + valueId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (valueId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Values.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (size_t i = 0; i < CtrFeatures.size(); ++i) {
const auto& feature = CtrFeatures[i];
if (i > 0) {
Y_ASSERT(CtrFeatures[i - 1] < feature);
}
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TModelCtrSplit ctrSplit;
ctrSplit.Ctr = feature.Ctr;
ctrSplit.Border = feature.Borders[borderId];
ref.BinFeatures.emplace_back(std::move(ctrSplit));
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
RuntimeData = runtimeData;
TVector<TRepackedBin> repackedBins;
auto treeSplits = GetModelTreeData()->GetTreeSplits();
for (const auto& binSplit : treeSplits) {
const auto& feature = ref.BinFeatures[binSplit];
const auto& featureIndex = splitIds[binSplit];
Y_ENSURE(
featureIndex.FeatureIdx <= 0xffff,
"Too many features in model, ask catboost team for support"
);
TRepackedBin rb;
rb.FeatureIndex = featureIndex.FeatureIdx;
if (feature.Type != ESplitType::OneHotFeature) {
rb.SplitIdx = featureIndex.SplitIdx;
} else {
rb.XorMask = ((~featureIndex.SplitIdx) & 0xff);
rb.SplitIdx = 0xff;
}
repackedBins.push_back(rb);
}
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateOwning(std::move(repackedBins));
}
void TModelTrees::CalcUsedModelCtrs() {
auto& ref = ApplyData->UsedModelCtrs;
for (const auto& ctrFeature : CtrFeatures) {
ref.push_back(ctrFeature.Ctr);
}
}
void TModelTrees::CalcFirstLeafOffsets() {
auto treeSizes = GetModelTreeData()->GetTreeSizes();
auto treeStartOffsets = GetModelTreeData()->GetTreeStartOffsets();
auto& ref = ApplyData->TreeFirstLeafOffsets;
ref.resize(treeSizes.size());
if (IsOblivious()) {
size_t currentOffset = 0;
for (size_t i = 0; i < treeSizes.size(); ++i) {
ref[i] = currentOffset;
currentOffset += (1 << treeSizes[i]) * ApproxDimension;
}
} else {
for (size_t treeId = 0; treeId < treeSizes.size(); ++treeId) {
const int treeNodesStart = treeStartOffsets[treeId];
const int treeNodesEnd = treeNodesStart + treeSizes[treeId];
ui32 minLeafValueIndex = Max();
ui32 maxLeafValueIndex = 0;
ui32 valueNodeCount = 0; // count of nodes with values
for (auto nodeIndex = treeNodesStart; nodeIndex < treeNodesEnd; ++nodeIndex) {
const auto &node = GetModelTreeData()->GetNonSymmetricStepNodes()[nodeIndex];
if (node.LeftSubtreeDiff == 0 || node.RightSubtreeDiff == 0) {
const ui32 leafValueIndex = GetModelTreeData()->GetNonSymmetricNodeIdToLeafId()[nodeIndex];
Y_ASSERT(leafValueIndex != Max<ui32>());
Y_VERIFY_DEBUG(
leafValueIndex % ApproxDimension == 0,
"Expect that leaf values are aligned."
);
minLeafValueIndex = Min(minLeafValueIndex, leafValueIndex);
maxLeafValueIndex = Max(maxLeafValueIndex, leafValueIndex);
++valueNodeCount;
}
}
Y_ASSERT(valueNodeCount > 0);
Y_ASSERT(maxLeafValueIndex == minLeafValueIndex + (valueNodeCount - 1) * ApproxDimension);
ref[treeId] = minLeafValueIndex;
}
}
}
void TModelTrees::DropUnusedFeatures() {
EraseIf(FloatFeatures, [](const TFloatFeature& feature) { return !feature.UsedInModel();});
EraseIf(CatFeatures, [](const TCatFeature& feature) { return !feature.UsedInModel(); });
EraseIf(TextFeatures, [](const TTextFeature& feature) { return !feature.UsedInModel(); });
EraseIf(EmbeddingFeatures, [](const TEmbeddingFeature& feature) { return !feature.UsedInModel(); });
UpdateRuntimeData();
}
void TModelTrees::ConvertObliviousToAsymmetric() {
if (!IsOblivious() || !IsSolid()) {
return;
}
TVector<int> treeSplits;
TVector<int> treeSizes;
TVector<int> treeStartOffsets;
TVector<TNonSymmetricTreeStepNode> nonSymmetricStepNodes;
TVector<ui32> nonSymmetricNodeIdToLeafId;
size_t leafStartOffset = 0;
auto& data = *CastToSolidTree(*this);
for (size_t treeId = 0; treeId < data.TreeSizes.size(); ++treeId) {
size_t treeSize = 0;
treeStartOffsets.push_back(treeSplits.size());
for (int depth = 0; depth < data.TreeSizes[treeId]; ++depth) {
const auto split = data.TreeSplits[data.TreeStartOffsets[treeId] + data.TreeSizes[treeId] - 1 - depth];
for (size_t cloneId = 0; cloneId < (1ull << depth); ++cloneId) {
treeSplits.push_back(split);
nonSymmetricNodeIdToLeafId.push_back(Max<ui32>());
nonSymmetricStepNodes.emplace_back(TNonSymmetricTreeStepNode{static_cast<ui16>(treeSize + 1), static_cast<ui16>(treeSize + 2)});
++treeSize;
}
}
for (size_t cloneId = 0; cloneId < (1ull << data.TreeSizes[treeId]); ++cloneId) {
treeSplits.push_back(0);
nonSymmetricNodeIdToLeafId.push_back((leafStartOffset + cloneId) * ApproxDimension);
nonSymmetricStepNodes.emplace_back(TNonSymmetricTreeStepNode{0, 0});
++treeSize;
}
leafStartOffset += (1ull << data.TreeSizes[treeId]);
treeSizes.push_back(treeSize);
}
data.TreeSplits = std::move(treeSplits);
data.TreeSizes = std::move(treeSizes);
data.TreeStartOffsets = std::move(treeStartOffsets);
data.NonSymmetricStepNodes = std::move(nonSymmetricStepNodes);
data.NonSymmetricNodeIdToLeafId = std::move(nonSymmetricNodeIdToLeafId);
UpdateRuntimeData();
}
TVector<ui32> TModelTrees::GetTreeLeafCounts() const {
auto applyData = GetApplyData();
const auto& firstLeafOfsets = applyData->TreeFirstLeafOffsets;
Y_ASSERT(IsSorted(firstLeafOfsets.begin(), firstLeafOfsets.end()));
TVector<ui32> treeLeafCounts;
treeLeafCounts.reserve(GetTreeCount());
for (size_t treeNum = 0; treeNum < GetTreeCount(); ++treeNum) {
const size_t currTreeLeafValuesEnd = (
treeNum + 1 < GetTreeCount()
? firstLeafOfsets[treeNum + 1]
: GetModelTreeData()->GetLeafValues().size()
);
const size_t currTreeLeafValuesCount = currTreeLeafValuesEnd - firstLeafOfsets[treeNum];
Y_ASSERT(currTreeLeafValuesCount % ApproxDimension == 0);
treeLeafCounts.push_back(currTreeLeafValuesCount / ApproxDimension);
}
return treeLeafCounts;
}
void TModelTrees::SetScaleAndBias(const TScaleAndBias& scaleAndBias) {
CB_ENSURE(IsValidFloat(scaleAndBias.Scale), "Invalid scale " << scaleAndBias.Scale);
TVector<double> bias = scaleAndBias.GetBiasRef();
for (auto b: bias) {
CB_ENSURE(IsValidFloat(b), "Invalid bias " << b);
}
if (bias.empty()) {
bias.resize(GetDimensionsCount(), 0);
}
CB_ENSURE(
GetDimensionsCount() == bias.size(),
"Inappropraite dimension of bias, should be " << GetDimensionsCount() << " found " << bias.size());
ScaleAndBias = TScaleAndBias(scaleAndBias.Scale, bias);
}
void TModelTrees::SetScaleAndBias(const NCatBoostFbs::TModelTrees* fbObj) {
ApproxDimension = fbObj->ApproxDimension();
TVector<double> bias;
if (fbObj->MultiBias() && fbObj->MultiBias()->size()) {
bias.assign(fbObj->MultiBias()->data(), fbObj->MultiBias()->data() + fbObj->MultiBias()->size());
} else {
CB_ENSURE(ApproxDimension == 1 || fbObj->Bias() == 0,
"Inappropraite dimension of bias, should be " << GetDimensionsCount() << " found 1");
bias.resize(ApproxDimension, fbObj->Bias());
}
SetScaleAndBias({fbObj->Scale(), bias});
}
void TModelTrees::DeserializeFeatures(const NCatBoostFbs::TModelTrees* fbObj) {
#define FBS_ARRAY_DESERIALIZER(var) \
if (fbObj->var()) {\
var.resize(fbObj->var()->size());\
for (size_t i = 0; i < fbObj->var()->size(); ++i) {\
var[i].FBDeserialize(fbObj->var()->Get(i));\
}\
}
FBS_ARRAY_DESERIALIZER(CatFeatures)
FBS_ARRAY_DESERIALIZER(FloatFeatures)
FBS_ARRAY_DESERIALIZER(TextFeatures)
FBS_ARRAY_DESERIALIZER(EmbeddingFeatures)
FBS_ARRAY_DESERIALIZER(EstimatedFeatures)
FBS_ARRAY_DESERIALIZER(OneHotFeatures)
FBS_ARRAY_DESERIALIZER(CtrFeatures)
#undef FBS_ARRAY_DESERIALIZER
}
void TModelTrees::FBDeserializeOwning(const NCatBoostFbs::TModelTrees* fbObj) {
ApproxDimension = fbObj->ApproxDimension();
SetScaleAndBias(fbObj);
auto& data = *CastToSolidTree(*this);
if (fbObj->TreeSplits()) {
data.TreeSplits.assign(fbObj->TreeSplits()->begin(), fbObj->TreeSplits()->end());
}
if (fbObj->TreeSizes()) {
data.TreeSizes.assign(fbObj->TreeSizes()->begin(), fbObj->TreeSizes()->end());
}
if (fbObj->TreeStartOffsets()) {
data.TreeStartOffsets.assign(fbObj->TreeStartOffsets()->begin(), fbObj->TreeStartOffsets()->end());
}
if (fbObj->LeafValues()) {
data.LeafValues.assign(
fbObj->LeafValues()->data(),
fbObj->LeafValues()->data() + fbObj->LeafValues()->size()
);
}
if (fbObj->NonSymmetricStepNodes()) {
data.NonSymmetricStepNodes.resize(fbObj->NonSymmetricStepNodes()->size());
std::copy(
fbObj->NonSymmetricStepNodes()->begin(),
fbObj->NonSymmetricStepNodes()->end(),
data.NonSymmetricStepNodes.begin()
);
}
if (fbObj->NonSymmetricNodeIdToLeafId()) {
data.NonSymmetricNodeIdToLeafId.assign(
fbObj->NonSymmetricNodeIdToLeafId()->begin(), fbObj->NonSymmetricNodeIdToLeafId()->end()
);
}
if (fbObj->LeafWeights() && fbObj->LeafWeights()->size() > 0) {
data.LeafWeights.assign(
fbObj->LeafWeights()->data(),
fbObj->LeafWeights()->data() + fbObj->LeafWeights()->size()
);
}
if (fbObj->RepackedBins()) {
TVector<TRepackedBin> repackedBins(fbObj->RepackedBins()->size());
std::copy(
fbObj->RepackedBins()->begin(),
fbObj->RepackedBins()->end(),
repackedBins.begin()
);
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateOwning(std::move(repackedBins));
}
DeserializeFeatures(fbObj);
}
void TModelTrees::FBDeserializeNonOwning(const NCatBoostFbs::TModelTrees* fbObj) {
ModelTreeData = MakeHolder<TOpaqueModelTree>();
ApproxDimension = fbObj->ApproxDimension();
SetScaleAndBias(fbObj);
DeserializeFeatures(fbObj);
auto& data = *CastToOpaqueTree(*this);
if (fbObj->TreeSplits()) {
data.TreeSplits = TConstArrayRef<int>(fbObj->TreeSplits()->data(), fbObj->TreeSplits()->size());
}
if (fbObj->TreeSizes()) {
data.TreeSizes = TConstArrayRef<int>(fbObj->TreeSizes()->data(), fbObj->TreeSizes()->size());
}
if (fbObj->TreeStartOffsets()) {
data.TreeStartOffsets = TConstArrayRef<int>(fbObj->TreeStartOffsets()->data(), fbObj->TreeStartOffsets()->size());
}
if (fbObj->LeafValues()) {
data.LeafValues = TConstArrayRef<double>(fbObj->LeafValues()->data(), fbObj->LeafValues()->size());
}
if (fbObj->NonSymmetricStepNodes()) {
static_assert(sizeof(TNonSymmetricTreeStepNode) == sizeof(NCatBoostFbs::TNonSymmetricTreeStepNode));
auto ptr = reinterpret_cast<const TNonSymmetricTreeStepNode*>(fbObj->NonSymmetricStepNodes()->data());
data.NonSymmetricStepNodes = TConstArrayRef<TNonSymmetricTreeStepNode>(ptr, fbObj->NonSymmetricStepNodes()->size());
}
if (fbObj->NonSymmetricNodeIdToLeafId()) {
data.NonSymmetricNodeIdToLeafId = TConstArrayRef<ui32>(fbObj->NonSymmetricNodeIdToLeafId()->data(), fbObj->NonSymmetricNodeIdToLeafId()->size());
}
if (fbObj->LeafWeights() && fbObj->LeafWeights()->size() > 0) {
data.LeafWeights = TConstArrayRef<double>(fbObj->LeafWeights()->data(), fbObj->LeafWeights()->size());
}
if (fbObj->RepackedBins()) {
auto ptr = reinterpret_cast<const TRepackedBin*>(fbObj->RepackedBins()->data());
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateNonOwning(TArrayRef(ptr, fbObj->RepackedBins()->size()));
}
}
TConstArrayRef<int> TSolidModelTree::GetTreeSplits() const {
return TreeSplits;
}
TConstArrayRef<int> TSolidModelTree::GetTreeSizes() const {
return TreeSizes;
}
TConstArrayRef<int> TSolidModelTree::GetTreeStartOffsets() const {
return TreeStartOffsets;
}
TConstArrayRef<TNonSymmetricTreeStepNode> TSolidModelTree::GetNonSymmetricStepNodes() const {
return NonSymmetricStepNodes;
}
TConstArrayRef<ui32> TSolidModelTree::GetNonSymmetricNodeIdToLeafId() const {
return NonSymmetricNodeIdToLeafId;
}
TConstArrayRef<double> TSolidModelTree::GetLeafValues() const {
return LeafValues;
}
TConstArrayRef<double> TSolidModelTree::GetLeafWeights() const {
return LeafWeights;
}
THolder<IModelTreeData> TSolidModelTree::Clone(ECloningPolicy policy) const {
switch (policy) {
case ECloningPolicy::CloneAsOpaque: {
auto holder = MakeHolder<TOpaqueModelTree>();
holder->LeafValues = TConstArrayRef<double>(LeafValues.data(), LeafValues.size());
holder->LeafWeights = TConstArrayRef<double>(LeafWeights.data(), LeafWeights.size());
holder->NonSymmetricNodeIdToLeafId = TConstArrayRef<ui32>(NonSymmetricNodeIdToLeafId.data(), NonSymmetricNodeIdToLeafId.size());
holder->NonSymmetricStepNodes = TConstArrayRef<TNonSymmetricTreeStepNode>(NonSymmetricStepNodes.data(), NonSymmetricStepNodes.size());
holder->TreeSizes = TConstArrayRef<int>(TreeSizes.data(), TreeSizes.size());
holder->TreeSplits = TConstArrayRef<int>(TreeSplits.data(), TreeSplits.size());
holder->TreeStartOffsets = TConstArrayRef<int>(TreeStartOffsets.data(), TreeStartOffsets.size());
return holder;
}
default:
return MakeHolder<TSolidModelTree>(*this);
}
}
void TSolidModelTree::SetTreeSplits(const TVector<int> &v) {
TreeSplits = v;
}
void TSolidModelTree::SetTreeSizes(const TVector<int> &v) {
TreeSizes = v;
}
void TSolidModelTree::SetTreeStartOffsets(const TVector<int> &v) {
TreeStartOffsets = v;
}
void TSolidModelTree::SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode> &v) {
NonSymmetricStepNodes = v;
}
void TSolidModelTree::SetNonSymmetricNodeIdToLeafId(const TVector<ui32> &v) {
NonSymmetricNodeIdToLeafId = v;
}
void TSolidModelTree::SetLeafValues(const TVector<double> &v) {
LeafValues = v;
}
void TSolidModelTree::SetLeafWeights(const TVector<double> &v) {
LeafWeights = v;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeSplits() const {
return TreeSplits;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeSizes() const {
return TreeSizes;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeStartOffsets() const {
return TreeStartOffsets;
}
TConstArrayRef<TNonSymmetricTreeStepNode> TOpaqueModelTree::GetNonSymmetricStepNodes() const {
return NonSymmetricStepNodes;
}
TConstArrayRef<ui32> TOpaqueModelTree::GetNonSymmetricNodeIdToLeafId() const {
return NonSymmetricNodeIdToLeafId;
}
TConstArrayRef<double> TOpaqueModelTree::GetLeafValues() const {
return LeafValues;
}
TConstArrayRef<double> TOpaqueModelTree::GetLeafWeights() const {
return LeafWeights;
}
THolder<IModelTreeData> TOpaqueModelTree::Clone(ECloningPolicy policy) const {
switch (policy) {
case ECloningPolicy::CloneAsSolid: {
auto holder = MakeHolder<TSolidModelTree>();
holder->TreeSplits = TVector<int>(TreeSplits.begin(), TreeSplits.end());
holder->TreeSizes = TVector<int>(TreeSizes.begin(), TreeSizes.end());
holder->TreeStartOffsets = TVector<int>(TreeStartOffsets.begin(), TreeStartOffsets.end());
holder->NonSymmetricStepNodes = TVector<TNonSymmetricTreeStepNode>(NonSymmetricStepNodes.begin(), NonSymmetricStepNodes.end());
holder->NonSymmetricNodeIdToLeafId = TVector<ui32>(NonSymmetricNodeIdToLeafId.begin(), NonSymmetricNodeIdToLeafId.end());
holder->LeafValues = TVector<double>(LeafValues.begin(), LeafValues.end());
holder->LeafWeights = TVector<double>(LeafWeights.begin(), LeafWeights.end());
return holder;
}
default:
return MakeHolder<TOpaqueModelTree>(*this);
}
}
void TOpaqueModelTree::SetTreeSplits(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetTreeSizes(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetTreeStartOffsets(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetLeafValues(const TVector<double>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetLeafWeights(const TVector<double>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TFullModel::CalcFlat(
TConstArrayRef<TConstArrayRef<float>> features,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlat(features, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcFlatSingle(
TConstArrayRef<float> features,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlatSingle(features, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcFlatTransposed(
TConstArrayRef<TConstArrayRef<float>> transposedFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlatTransposed(transposedFeatures, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TConstArrayRef<int>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->Calc(floatFeatures, catFeatures, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TVector<TStringBuf>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
TVector<TConstArrayRef<TStringBuf>> stringbufVecRefs{catFeatures.begin(), catFeatures.end()};
GetCurrentEvaluator()->Calc(floatFeatures, stringbufVecRefs, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TVector<TStringBuf>> catFeatures,
TConstArrayRef<TVector<TStringBuf>> textFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
TVector<TConstArrayRef<TStringBuf>> stringbufCatVecRefs{catFeatures.begin(), catFeatures.end()};
TVector<TConstArrayRef<TStringBuf>> stringbufTextVecRefs{textFeatures.begin(), textFeatures.end()};
GetCurrentEvaluator()->Calc(floatFeatures, stringbufCatVecRefs, stringbufTextVecRefs, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcLeafIndexesSingle(
TConstArrayRef<float> floatFeatures,
TConstArrayRef<TStringBuf> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<ui32> indexes,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->CalcLeafIndexesSingle(floatFeatures, catFeatures, treeStart, treeEnd, indexes, featureInfo);
}
void TFullModel::CalcLeafIndexes(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TConstArrayRef<TStringBuf>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<ui32> indexes,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->CalcLeafIndexes(floatFeatures, catFeatures, treeStart, treeEnd, indexes, featureInfo);
}
void TFullModel::Save(IOutputStream* s) const {
using namespace flatbuffers;
using namespace NCatBoostFbs;
::Save(s, GetModelFormatDescriptor());
TModelPartsCachingSerializer serializer;
auto modelTreesOffset = ModelTrees->FBSerialize(serializer);
std::vector<flatbuffers::Offset<TKeyValue>> infoMap;
for (const auto& key_value : ModelInfo) {
auto keyValueOffset = CreateTKeyValue(
serializer.FlatbufBuilder,
serializer.FlatbufBuilder.CreateString(
key_value.first.c_str(),
key_value.first.size()
),
serializer.FlatbufBuilder.CreateString(
key_value.second.c_str(),
key_value.second.size()
)
);
infoMap.push_back(keyValueOffset);
}
std::vector<flatbuffers::Offset<flatbuffers::String>> modelPartIds;
if (!!CtrProvider && CtrProvider->IsSerializable()) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(CtrProvider->ModelPartIdentifier()));
}
if (!!TextProcessingCollection) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(TextProcessingCollection->GetStringIdentifier()));
}
if (!!EmbeddingProcessingCollection) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(EmbeddingProcessingCollection->GetStringIdentifier()));
}
auto coreOffset = CreateTModelCoreDirect(
serializer.FlatbufBuilder,
CURRENT_CORE_FORMAT_STRING,
modelTreesOffset,
infoMap.empty() ? nullptr : &infoMap,
modelPartIds.empty() ? nullptr : &modelPartIds
);
serializer.FlatbufBuilder.Finish(coreOffset);
SaveSize(s, serializer.FlatbufBuilder.GetSize());
s->Write(serializer.FlatbufBuilder.GetBufferPointer(), serializer.FlatbufBuilder.GetSize());
if (!!CtrProvider && CtrProvider->IsSerializable()) {
CtrProvider->Save(s);
}
if (!!TextProcessingCollection) {
TextProcessingCollection->Save(s);
}
if (!!EmbeddingProcessingCollection) {
EmbeddingProcessingCollection->Save(s);
}
}
void TFullModel::DefaultFullModelInit(const NCatBoostFbs::TModelCore* fbModelCore) {
CB_ENSURE(
fbModelCore->FormatVersion() && fbModelCore->FormatVersion()->str() == CURRENT_CORE_FORMAT_STRING,
"Unsupported model format: " << fbModelCore->FormatVersion()->str()
);
ModelInfo.clear();
if (fbModelCore->InfoMap()) {
for (auto keyVal : *fbModelCore->InfoMap()) {
ModelInfo[keyVal->Key()->str()] = keyVal->Value()->str();
}
}
}
void TFullModel::Load(IInputStream* s) {
ReferenceMainFactoryRegistrators();
using namespace flatbuffers;
using namespace NCatBoostFbs;
ui32 fileDescriptor;
::Load(s, fileDescriptor);
CB_ENSURE(fileDescriptor == GetModelFormatDescriptor(), "Incorrect model file descriptor");
auto coreSize = ::LoadSize(s);
TArrayHolder<ui8> arrayHolder(new ui8[coreSize]);
s->LoadOrFail(arrayHolder.Get(), coreSize);
{
flatbuffers::Verifier verifier(arrayHolder.Get(), coreSize, 64 /* max depth */, 256000000 /* max tables */);
CB_ENSURE(VerifyTModelCoreBuffer(verifier), "Flatbuffers model verification failed");
}
auto fbModelCore = GetTModelCore(arrayHolder.Get());
DefaultFullModelInit(fbModelCore);
if (fbModelCore->ModelTrees()) {
ModelTrees.GetMutable()->FBDeserializeOwning(fbModelCore->ModelTrees());
}
TVector<TString> modelParts;
if (fbModelCore->ModelPartIds()) {
for (auto part : *fbModelCore->ModelPartIds()) {
modelParts.emplace_back(part->str());
}
}
if (!modelParts.empty()) {
for (const auto& modelPartId : modelParts) {
if (modelPartId == TStaticCtrProvider::ModelPartId()) {
CtrProvider = new TStaticCtrProvider;
CtrProvider->Load(s);
} else if (modelPartId == NCB::TTextProcessingCollection::GetStringIdentifier()) {
TextProcessingCollection = new NCB::TTextProcessingCollection();
TextProcessingCollection->Load(s);
} else if (modelPartId == NCB::TEmbeddingProcessingCollection::GetStringIdentifier()) {
EmbeddingProcessingCollection = new NCB::TEmbeddingProcessingCollection();
EmbeddingProcessingCollection->Load(s);
} else {
CB_ENSURE(
false,
"Got unknown partId = " << modelPartId << " via deserialization"
<< "only static ctr and text processing collection model parts are supported"
);
}
}
}
UpdateDynamicData();
}
void TFullModel::InitNonOwning(const void* binaryBuffer, size_t binarySize) {
using namespace flatbuffers;
using namespace NCatBoostFbs;
TMemoryInput in(binaryBuffer, binarySize);
ui32 fileDescriptor;
::Load(&in, fileDescriptor);
CB_ENSURE(fileDescriptor == GetModelFormatDescriptor(), "Incorrect model file descriptor");
size_t coreSize = ::LoadSize(&in);
const ui8* fbPtr = reinterpret_cast<const ui8*>(in.Buf());
in.Skip(coreSize);
{
flatbuffers::Verifier verifier(fbPtr, coreSize, 64 /* max depth */, 256000000 /* max tables */);
CB_ENSURE(VerifyTModelCoreBuffer(verifier), "Flatbuffers model verification failed");
}
auto fbModelCore = GetTModelCore(fbPtr);
DefaultFullModelInit(fbModelCore);
if (fbModelCore->ModelTrees()) {
ModelTrees.GetMutable()->FBDeserializeNonOwning(fbModelCore->ModelTrees());
}
TVector<TString> modelParts;
if (fbModelCore->ModelPartIds()) {
for (auto part : *fbModelCore->ModelPartIds()) {
modelParts.emplace_back(part->str());
}
}
if (!modelParts.empty()) {
for (const auto& modelPartId : modelParts) {
if (modelPartId == TStaticCtrProvider::ModelPartId()) {
auto ptr = new TStaticCtrProvider;
CtrProvider = ptr;
ptr->LoadNonOwning(&in);
} else if (modelPartId == NCB::TTextProcessingCollection::GetStringIdentifier()) {
TextProcessingCollection = new NCB::TTextProcessingCollection();
TextProcessingCollection->LoadNonOwning(&in);
} else if (modelPartId == NCB::TEmbeddingProcessingCollection::GetStringIdentifier()) {
EmbeddingProcessingCollection = new NCB::TEmbeddingProcessingCollection();
EmbeddingProcessingCollection->LoadNonOwning(&in);
} else {
CB_ENSURE(
false,
"Got unknown partId = " << modelPartId << " via deserialization"
<< "only static ctr and text processing collection model parts are supported"
);
}
}
}
UpdateDynamicData();
}
void TFullModel::UpdateDynamicData() {
ModelTrees.GetMutable()->UpdateRuntimeData();
if (CtrProvider) {
CtrProvider->SetupBinFeatureIndexes(
ModelTrees->GetFloatFeatures(),
ModelTrees->GetOneHotFeatures(),
ModelTrees->GetCatFeatures());
}
with_lock(CurrentEvaluatorLock) {
Evaluator.Reset();
}
}
TVector<TString> GetModelUsedFeaturesNames(const TFullModel& model) {
TVector<int> featuresIdxs;
TVector<TString> featuresNames;
const TModelTrees& forest = *model.ModelTrees;
for (const TFloatFeature& feature : forest.GetFloatFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TCatFeature& feature : forest.GetCatFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TTextFeature& feature : forest.GetTextFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TEmbeddingFeature& feature : forest.GetEmbeddingFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
TVector<int> featuresOrder(featuresIdxs.size());
Iota(featuresOrder.begin(), featuresOrder.end(), 0);
Sort(featuresOrder.begin(), featuresOrder.end(),
[featuresIdxs](int index1, int index2) {
return featuresIdxs[index1] < featuresIdxs[index2];
}
);
TVector<TString> result(featuresNames.size());
for (int featureIdx = 0; featureIdx < featuresNames.ysize(); ++featureIdx) {
result[featureIdx] = featuresNames[featuresOrder[featureIdx]];
}
return result;
}
void SetModelExternalFeatureNames(const TVector<TString>& featureNames, TFullModel* model) {
TModelTrees& forest = *(model->ModelTrees.GetMutable());
CB_ENSURE(
(forest.GetFloatFeatures().empty() || featureNames.ysize() > forest.GetFloatFeatures().back().Position.FlatIndex) &&
(forest.GetCatFeatures().empty() || featureNames.ysize() > forest.GetCatFeatures().back().Position.FlatIndex),
"Features in model not corresponds to features names array length not correspond");
forest.ApplyFeatureNames(featureNames);
}
static TMaybe<NCatboostOptions::TLossDescription> GetLossDescription(const TFullModel& model) {
TMaybe<NCatboostOptions::TLossDescription> lossDescription;
if (model.ModelInfo.contains("loss_function")) {
lossDescription.ConstructInPlace();
lossDescription->Load(ReadTJsonValue(model.ModelInfo.at("loss_function")));
}
if (model.ModelInfo.contains("params")) {
const auto& params = ReadTJsonValue(model.ModelInfo.at("params"));
if (params.Has("loss_function")) {
lossDescription.ConstructInPlace();
lossDescription->Load(params["loss_function"]);
}
}
return lossDescription;
}
TString TFullModel::GetLossFunctionName() const {
const TMaybe<NCatboostOptions::TLossDescription> lossDescription = GetLossDescription(*this);
if (lossDescription.Defined()) {
return ToString(lossDescription->GetLossFunction());
}
return {};
}
static TVector<NJson::TJsonValue> GetSequentialIntegerClassLabels(size_t classCount) {
TVector<NJson::TJsonValue> classLabels;
classLabels.reserve(classCount);
for (int classIdx : xrange(SafeIntegerCast<int>(classCount))) {
classLabels.emplace_back(classIdx);
}
return classLabels;
}
TVector<NJson::TJsonValue> TFullModel::GetModelClassLabels() const {
TVector<NJson::TJsonValue> classLabels;
TMaybe<TClassLabelOptions> classOptions;
// "class_params" is new, more generic option, used for binclass as well
for (const auto& paramName : {"class_params", "multiclass_params"}) {
if (ModelInfo.contains(paramName)) {
classOptions.ConstructInPlace();
classOptions->Load(ReadTJsonValue(ModelInfo.at(paramName)));
break;
}
}
if (classOptions.Defined()) {
if (classOptions->ClassLabels.IsSet()) {
classLabels = classOptions->ClassLabels.Get();
if (!classLabels.empty()) {
return classLabels;
}
}
if (classOptions->ClassesCount.IsSet()) {
const size_t classesCount = SafeIntegerCast<size_t>(classOptions->ClassesCount.Get());
if (classesCount) {
return GetSequentialIntegerClassLabels(classesCount);
}
}
if (classOptions->ClassToLabel.IsSet()) {
classLabels.reserve(classOptions->ClassToLabel->size());
for (float label : classOptions->ClassToLabel.Get()) {
classLabels.emplace_back(int(label));
}
return classLabels;
}
}
if (ModelInfo.contains("params")) {
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
if (paramsJson.Has("data_processing_options")
&& paramsJson["data_processing_options"].Has("class_names")) {
const NJson::TJsonValue::TArray& classLabelsJsonArray
= paramsJson["data_processing_options"]["class_names"].GetArraySafe();
if (!classLabelsJsonArray.empty()) {
classLabels.assign(classLabelsJsonArray.begin(), classLabelsJsonArray.end());
return classLabels;
}
}
}
const TMaybe<NCatboostOptions::TLossDescription> lossDescription = GetLossDescription(*this);
if (lossDescription.Defined() && IsClassificationObjective(lossDescription->GetLossFunction())) {
const size_t dimensionsCount = GetDimensionsCount();
return GetSequentialIntegerClassLabels((dimensionsCount == 1) ? 2 : dimensionsCount);
}
return classLabels;
}
void TFullModel::UpdateEstimatedFeaturesIndices(TVector<TEstimatedFeature>&& newEstimatedFeatures) {
CB_ENSURE(
TextProcessingCollection || EmbeddingProcessingCollection,
"UpdateEstimatedFeatureIndices called when ProcessingCollections aren't defined"
);
ModelTrees.GetMutable()->SetEstimatedFeatures(std::move(newEstimatedFeatures));
ModelTrees.GetMutable()->UpdateRuntimeData();
}
bool TFullModel::IsPosteriorSamplingModel() const {
if (ModelInfo.contains("params")) {
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
if (paramsJson.Has("boosting_options") && paramsJson["boosting_options"].Has("posterior_sampling")) {
return paramsJson["boosting_options"]["posterior_sampling"].GetBoolean();
}
}
return false;
}
float TFullModel::GetActualShrinkCoef() const {
CB_ENSURE(ModelInfo.contains("params"), "No params in model");
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
CB_ENSURE(paramsJson.Has("boosting_options"), "No boosting_options parameters in model");
CB_ENSURE(paramsJson["boosting_options"].Has("learning_rate"),
"No parameter learning_rate in model boosting_options");
CB_ENSURE(paramsJson["boosting_options"].Has("model_shrink_rate"),
"No parameter model_shrink_rate in model boosting_options");
return paramsJson["boosting_options"]["learning_rate"].GetDouble() * paramsJson["boosting_options"]["model_shrink_rate"].GetDouble();
}
namespace {
struct TUnknownFeature {};
struct TFlatFeature {
TVariant<TUnknownFeature, TFloatFeature, TCatFeature> FeatureVariant;
public:
TFlatFeature() = default;
template <class TFeatureType>
void SetOrCheck(const TFeatureType& other) {
if (HoldsAlternative<TUnknownFeature>(FeatureVariant)) {
FeatureVariant = other;
}
CB_ENSURE(HoldsAlternative<TFeatureType>(FeatureVariant),
"Feature type mismatch: Categorical != Float for flat feature index: " <<
other.Position.FlatIndex
);
TFeatureType& feature = Get<TFeatureType>(FeatureVariant);
CB_ENSURE(feature.Position.FlatIndex == other.Position.FlatIndex);
CB_ENSURE(
feature.Position.Index == other.Position.Index,
"Internal feature index mismatch: " << feature.Position.Index << " != "
<< other.Position.Index << " flat feature index: " << feature.Position.FlatIndex
);
CB_ENSURE(
feature.FeatureId.empty() || feature.FeatureId == other.FeatureId,
"Feature name mismatch: " << feature.FeatureId << " != " << other.FeatureId
<< " flat feature index: " << feature.Position.FlatIndex
);
feature.FeatureId = other.FeatureId;
if constexpr (std::is_same_v<TFeatureType, TFloatFeature>) {
constexpr auto asFalse = TFloatFeature::ENanValueTreatment::AsFalse;
constexpr auto asIs = TFloatFeature::ENanValueTreatment::AsIs;
if (
(feature.NanValueTreatment == asIs && other.NanValueTreatment == asFalse) ||
(feature.NanValueTreatment == asFalse && other.NanValueTreatment == asIs)
) {
// We can relax Nan treatmen comparison as nans within AsIs strategy are always treated like AsFalse
// TODO(kirillovs): later implement splitted storage for float feautres with different Nan treatment
feature.NanValueTreatment = asFalse;
} else {
CB_ENSURE(
feature.NanValueTreatment == other.NanValueTreatment,
"Nan value treatment differs: " << (int) feature.NanValueTreatment << " != " <<
(int) other.NanValueTreatment
);
}
feature.HasNans |= other.HasNans;
}
}
};
struct TFlatFeatureMergerVisitor {
void operator()(TUnknownFeature&) {
}
void operator()(TFloatFeature& s) {
MergedFloatFeatures.push_back(s);
}
void operator()(TCatFeature& x) {
MergedCatFeatures.push_back(x);
}
TVector<TFloatFeature> MergedFloatFeatures;
TVector<TCatFeature> MergedCatFeatures;
};
}
static void StreamModelTreesWithoutScaleAndBiasToBuilder(
const TModelTrees& trees,
double leafMultiplier,
TObliviousTreeBuilder* builder,
bool streamLeafWeights)
{
auto& data = trees.GetModelTreeData();
const auto& binFeatures = trees.GetBinFeatures();
auto applyData = trees.GetApplyData();
const auto& leafOffsets = applyData->TreeFirstLeafOffsets;
for (size_t treeIdx = 0; treeIdx < data->GetTreeSizes().size(); ++treeIdx) {
TVector<TModelSplit> modelSplits;
for (int splitIdx = data->GetTreeStartOffsets()[treeIdx];
splitIdx < data->GetTreeStartOffsets()[treeIdx] + data->GetTreeSizes()[treeIdx];
++splitIdx)
{
modelSplits.push_back(binFeatures[data->GetTreeSplits()[splitIdx]]);
}
if (leafMultiplier == 1.0) {
TConstArrayRef<double> leafValuesRef(
data->GetLeafValues().begin() + leafOffsets[treeIdx],
data->GetLeafValues().begin() + leafOffsets[treeIdx]
+ trees.GetDimensionsCount() * (1ull << data->GetTreeSizes()[treeIdx])
);
builder->AddTree(
modelSplits,
leafValuesRef,
!streamLeafWeights ? TConstArrayRef<double>() : TConstArrayRef<double>(
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount(),
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount()
+ (1ull << data->GetTreeSizes()[treeIdx])
)
);
} else {
TVector<double> leafValues(
data->GetLeafValues().begin() + leafOffsets[treeIdx],
data->GetLeafValues().begin() + leafOffsets[treeIdx]
+ trees.GetDimensionsCount() * (1ull << data->GetTreeSizes()[treeIdx])
);
for (auto& leafValue: leafValues) {
leafValue *= leafMultiplier;
}
builder->AddTree(
modelSplits,
leafValues,
!streamLeafWeights ? TConstArrayRef<double>() : TConstArrayRef<double>(
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount(),
(1ull << data->GetTreeSizes()[treeIdx])
)
);
}
}
}
static void SumModelsParams(
const TVector<const TFullModel*> modelVector,
THashMap<TString, TString>* modelInfo
) {
TMaybe<TString> classParams;
auto dimensionsCount = modelVector.back()->GetDimensionsCount();
for (auto modelIdx : xrange(modelVector.size())) {
const auto& modelInfo = modelVector[modelIdx]->ModelInfo;
bool paramFound = false;
for (const auto& paramName : {"class_params", "multiclass_params"}) {
if (modelInfo.contains(paramName)) {
if (classParams) {
CB_ENSURE(
modelInfo.at(paramName) == *classParams,
"Cannot sum models with different class params"
);
} else if ((modelIdx == 0) || (dimensionsCount == 1)) {
// it is ok only for 1-dimensional models to have only some classParams specified
classParams = modelInfo.at(paramName);
} else {
CB_ENSURE(false, "Cannot sum multidimensional models with and without class params");
}
paramFound = true;
break;
}
}
if ((modelIdx != 0) && classParams && !paramFound && (dimensionsCount > 1)) {
CB_ENSURE(false, "Cannot sum multidimensional models with and without class params");
}
}
if (classParams) {
(*modelInfo)["class_params"] = *classParams;
} else {
/* One-dimensional models.
* If class labels for binary classification are present they must be the same
*/
TMaybe<TVector<NJson::TJsonValue>> sumClassLabels;
for (const TFullModel* model : modelVector) {
TVector<NJson::TJsonValue> classLabels = model->GetModelClassLabels();
if (classLabels) {
Y_VERIFY(classLabels.size() == 2);
if (sumClassLabels) {
CB_ENSURE(classLabels == *sumClassLabels, "Cannot sum models with different class labels");
} else {
sumClassLabels = std::move(classLabels);
}
}
}
if (sumClassLabels) {
TString& paramsString = (*modelInfo)["params"];
NJson::TJsonValue paramsJson;
if (paramsString) {
paramsJson = ReadTJsonValue(paramsString);
}
NJson::TJsonValue classNames;
classNames.AppendValue((*sumClassLabels)[0]);
classNames.AppendValue((*sumClassLabels)[1]);
paramsJson["data_processing_options"]["class_names"] = std::move(classNames);
paramsString = ToString(paramsJson);
}
}
const auto lossDescription = GetLossDescription(*modelVector.back());
if (lossDescription.Defined()) {
const bool allLossesAreSame = AllOf(
modelVector,
[&lossDescription](const TFullModel* model) {
const auto currentLossDescription = GetLossDescription(*model);
return currentLossDescription.Defined() && ((*currentLossDescription) == (*lossDescription));
}
);
if (allLossesAreSame) {
NJson::TJsonValue lossDescriptionJson;
lossDescription->Save(&lossDescriptionJson);
(*modelInfo)["loss_function"] = ToString(lossDescriptionJson);
}
}
if (!AllOf(modelVector, [&](const TFullModel* model) {
return model->GetScaleAndBias().IsIdentity();
}))
{
NJson::TJsonValue summandScaleAndBiases;
for (const auto& model : modelVector) {
NJson::TJsonValue scaleAndBias;
scaleAndBias.InsertValue("scale", model->GetScaleAndBias().Scale);
NJson::TJsonValue biasValue;
auto bias = model->GetScaleAndBias().GetBiasRef();
for (auto b : bias) {
biasValue.AppendValue(b);
}
scaleAndBias.InsertValue("bias", biasValue);
summandScaleAndBiases.AppendValue(scaleAndBias);
}
(*modelInfo)["summand_scale_and_biases"] = summandScaleAndBiases.GetStringRobust();
}
}
TFullModel SumModels(
const TVector<const TFullModel*> modelVector,
const TVector<double>& weights,
ECtrTableMergePolicy ctrMergePolicy)
{
CB_ENSURE(!modelVector.empty(), "empty model vector unexpected");
CB_ENSURE(modelVector.size() == weights.size());
const auto approxDimension = modelVector.back()->GetDimensionsCount();
size_t maxFlatFeatureVectorSize = 0;
TVector<TIntrusivePtr<ICtrProvider>> ctrProviders;
bool allModelsHaveLeafWeights = true;
bool someModelHasLeafWeights = false;
for (const auto& model : modelVector) {
Y_ASSERT(model != nullptr);
//TODO(eermishkina): support non symmetric trees
CB_ENSURE(model->IsOblivious(), "Models summation supported only for symmetric trees");
CB_ENSURE(
model->ModelTrees->GetTextFeatures().empty(),
"Models summation is not supported for models with text features"
);
CB_ENSURE(
model->GetDimensionsCount() == approxDimension,
"Approx dimensions don't match: " << model->GetDimensionsCount() << " != "
<< approxDimension
);
maxFlatFeatureVectorSize = Max(
maxFlatFeatureVectorSize,
model->ModelTrees->GetFlatFeatureVectorExpectedSize()
);
ctrProviders.push_back(model->CtrProvider);
// empty model does not disable LeafWeights:
if (model->ModelTrees->GetModelTreeData()->GetLeafWeights().size() < model->GetTreeCount()) {
allModelsHaveLeafWeights = false;
}
if (!model->ModelTrees->GetModelTreeData()->GetLeafWeights().empty()) {
someModelHasLeafWeights = true;
}
}
if (!allModelsHaveLeafWeights && someModelHasLeafWeights) {
CATBOOST_WARNING_LOG << "Leaf weights for some models are ignored " <<
"because not all models have leaf weights" << Endl;
}
TVector<TFlatFeature> flatFeatureInfoVector(maxFlatFeatureVectorSize);
for (const auto& model : modelVector) {
for (const auto& floatFeature : model->ModelTrees->GetFloatFeatures()) {
flatFeatureInfoVector[floatFeature.Position.FlatIndex].SetOrCheck(floatFeature);
}
for (const auto& catFeature : model->ModelTrees->GetCatFeatures()) {
flatFeatureInfoVector[catFeature.Position.FlatIndex].SetOrCheck(catFeature);
}
}
TFlatFeatureMergerVisitor merger;
for (auto& flatFeature: flatFeatureInfoVector) {
Visit(merger, flatFeature.FeatureVariant);
}
TObliviousTreeBuilder builder(merger.MergedFloatFeatures, merger.MergedCatFeatures, {}, {}, approxDimension);
TVector<double> totalBias(approxDimension);
for (const auto modelId : xrange(modelVector.size())) {
TScaleAndBias normer = modelVector[modelId]->GetScaleAndBias();
auto normerBias = normer.GetBiasRef();
if (!normerBias.empty()) {
CB_ENSURE(totalBias.size() == normerBias.size(), "Bias dimensions missmatch");
for (auto dim : xrange(totalBias.size())) {
totalBias[dim] += weights[modelId] * normerBias[dim];
}
}
StreamModelTreesWithoutScaleAndBiasToBuilder(
*modelVector[modelId]->ModelTrees,
weights[modelId] * normer.Scale,
&builder,
allModelsHaveLeafWeights
);
}
TFullModel result;
builder.Build(result.ModelTrees.GetMutable());
for (const auto modelIdx : xrange(modelVector.size())) {
TStringBuilder keyPrefix;
keyPrefix << "model" << modelIdx << ":";
for (const auto& [key, value]: modelVector[modelIdx]->ModelInfo) {
result.ModelInfo[keyPrefix + key] = value;
}
}
result.CtrProvider = MergeCtrProvidersData(ctrProviders, ctrMergePolicy);
result.UpdateDynamicData();
result.ModelInfo["model_guid"] = CreateGuidAsString();
result.SetScaleAndBias({1, totalBias});
SumModelsParams(modelVector, &result.ModelInfo);
return result;
}
void SaveModelBorders(
const TString& file,
const TFullModel& model) {
TOFStream out(file);
for (const auto& feature : model.ModelTrees->GetFloatFeatures()) {
NCB::OutputFeatureBorders(
feature.Position.FlatIndex,
feature.Borders,
NanValueTreatmentToNanMode(feature.NanValueTreatment),
&out
);
}
}
THashMap<int, TFloatFeature::ENanValueTreatment> GetNanTreatments(const TFullModel& model) {
THashMap<int, TFloatFeature::ENanValueTreatment> nanTreatments;
for (const auto& feature : model.ModelTrees->GetFloatFeatures()) {
nanTreatments[feature.Position.FlatIndex] = feature.NanValueTreatment;
}
return nanTreatments;
}
DEFINE_DUMPER(TRepackedBin, FeatureIndex, XorMask, SplitIdx)
DEFINE_DUMPER(TNonSymmetricTreeStepNode, LeftSubtreeDiff, RightSubtreeDiff)
DEFINE_DUMPER(
TModelTrees::TRuntimeData,
BinFeatures,
EffectiveBinFeaturesBucketCount
)
DEFINE_DUMPER(
TModelTrees::TForApplyData,
UsedFloatFeaturesCount,
UsedCatFeaturesCount,
MinimalSufficientFloatFeaturesVectorSize,
MinimalSufficientCatFeaturesVectorSize,
UsedModelCtrs,
TreeFirstLeafOffsets
)
//DEFINE_DUMPER(TModelTrees),
// TreeSplits, TreeSizes,
// TreeStartOffsets, NonSymmetricStepNodes,
// NonSymmetricNodeIdToLeafId, LeafValues);
TNonSymmetricTreeStepNode& TNonSymmetricTreeStepNode::operator=(const NCatBoostFbs::TNonSymmetricTreeStepNode* stepNode) {
LeftSubtreeDiff = stepNode->LeftSubtreeDiff();
RightSubtreeDiff = stepNode->RightSubtreeDiff();
return *this;
}
TRepackedBin& TRepackedBin::operator=(const NCatBoostFbs::TRepackedBin* repackedBin) {
std::tie(
FeatureIndex,
XorMask,
SplitIdx
) = std::forward_as_tuple(
repackedBin->FeatureIndex(),
repackedBin->XorMask(),
repackedBin->SplitIdx()
);
return *this;
}
| 40.792172 | 154 | 0.672392 |
28524420cfa7183d7514ffa340993f720ee587fe | 4,255 | cc | C++ | quic/quic_transport/quic_transport_stream.cc | fawdlstty/quiche | dfabdfb6884bf8ccd92c6f818aa8764a84f5a984 | [
"BSD-3-Clause"
] | 1 | 2021-10-17T09:43:24.000Z | 2021-10-17T09:43:24.000Z | quic/quic_transport/quic_transport_stream.cc | fawdlstty/quiche | dfabdfb6884bf8ccd92c6f818aa8764a84f5a984 | [
"BSD-3-Clause"
] | null | null | null | quic/quic_transport/quic_transport_stream.cc | fawdlstty/quiche | dfabdfb6884bf8ccd92c6f818aa8764a84f5a984 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/quic_transport/quic_transport_stream.h"
#include <sys/types.h>
#include "net/third_party/quiche/src/quic/core/quic_buffer_allocator.h"
#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
namespace quic {
QuicTransportStream::QuicTransportStream(
QuicStreamId id,
QuicSession* session,
QuicTransportSessionInterface* session_interface)
: QuicStream(id,
session,
/*is_static=*/false,
QuicUtils::GetStreamType(id,
session->connection()->perspective(),
session->IsIncomingStream(id))),
session_interface_(session_interface) {}
size_t QuicTransportStream::Read(char* buffer, size_t buffer_size) {
if (!session_interface_->IsSessionReady()) {
return 0;
}
iovec iov;
iov.iov_base = buffer;
iov.iov_len = buffer_size;
const size_t result = sequencer()->Readv(&iov, 1);
if (sequencer()->IsClosed() && visitor_ != nullptr) {
visitor_->OnFinRead();
}
return result;
}
size_t QuicTransportStream::Read(std::string* output) {
const size_t old_size = output->size();
const size_t bytes_to_read = ReadableBytes();
output->resize(old_size + bytes_to_read);
size_t bytes_read = Read(&(*output)[old_size], bytes_to_read);
DCHECK_EQ(bytes_to_read, bytes_read);
output->resize(old_size + bytes_read);
return bytes_read;
}
bool QuicTransportStream::Write(quiche::QuicheStringPiece data) {
if (!CanWrite()) {
return false;
}
QuicUniqueBufferPtr buffer = MakeUniqueBuffer(
session()->connection()->helper()->GetStreamSendBufferAllocator(),
data.size());
memcpy(buffer.get(), data.data(), data.size());
QuicMemSlice memslice(std::move(buffer), data.size());
QuicConsumedData consumed =
WriteMemSlices(QuicMemSliceSpan(&memslice), /*fin=*/false);
if (consumed.bytes_consumed == data.size()) {
return true;
}
if (consumed.bytes_consumed == 0) {
return false;
}
// QuicTransportStream::Write() is an all-or-nothing write API. To achieve
// that property, it relies on WriteMemSlices() being an all-or-nothing API.
// If WriteMemSlices() fails to provide that guarantee, we have no way to
// communicate a partial write to the caller, and thus it's safer to just
// close the connection.
QUIC_BUG << "WriteMemSlices() unexpectedly partially consumed the input "
"data, provided: "
<< data.size() << ", written: " << consumed.bytes_consumed;
CloseConnectionWithDetails(
QUIC_INTERNAL_ERROR,
"WriteMemSlices() unexpectedly partially consumed the input data");
return false;
}
bool QuicTransportStream::SendFin() {
if (!CanWrite()) {
return false;
}
QuicMemSlice empty;
QuicConsumedData consumed =
WriteMemSlices(QuicMemSliceSpan(&empty), /*fin=*/true);
DCHECK_EQ(consumed.bytes_consumed, 0u);
return consumed.fin_consumed;
}
bool QuicTransportStream::CanWrite() const {
return session_interface_->IsSessionReady() && CanWriteNewData() &&
!write_side_closed();
}
size_t QuicTransportStream::ReadableBytes() const {
if (!session_interface_->IsSessionReady()) {
return 0;
}
return sequencer()->ReadableBytes();
}
void QuicTransportStream::OnDataAvailable() {
if (sequencer()->IsClosed()) {
if (visitor_ != nullptr) {
visitor_->OnFinRead();
}
OnFinRead();
return;
}
if (visitor_ == nullptr) {
return;
}
if (ReadableBytes() == 0) {
return;
}
visitor_->OnCanRead();
}
void QuicTransportStream::OnCanWriteNewData() {
// Ensure the origin check has been completed, as the stream can be notified
// about being writable before that.
if (!CanWrite()) {
return;
}
if (visitor_ != nullptr) {
visitor_->OnCanWrite();
}
}
} // namespace quic
| 29.964789 | 81 | 0.682961 |
28530a40e5accd8f31daea09b54aff0474526fb5 | 3,707 | hpp | C++ | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | null | null | null | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | 4 | 2020-02-25T00:21:58.000Z | 2020-07-03T11:12:03.000Z | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | null | null | null | #pragma once
#include "common/Icon.hpp"
#include <QApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLayout>
#include <config.hpp>
constexpr int ICON_SIZE = 100;
namespace Ui {
class AboutDialog {
public:
QGridLayout *gridLayout;
QLabel *lableTitle;
QLabel *lableIcon;
QLabel *lableDesc;
QDialogButtonBox *buttonBox;
QDialog *parent;
AboutDialog(QDialog *parent)
: gridLayout(new QGridLayout(parent)), lableTitle(new QLabel(parent)),
lableIcon(new QLabel(parent)), lableDesc(new QLabel(parent)),
buttonBox(new QDialogButtonBox(parent)), parent(parent) {}
void setupUi() const {
parent->window()->layout()->setSizeConstraint(
QLayout::SizeConstraint::SetFixedSize);
parent->setWindowFlag(Qt::WindowType::MSWindowsFixedSizeDialogHint, true);
parent->setWindowIcon(getIcon(Icon::HelpAbout));
lableTitle->setText(
QObject::tr("<p><span style=\"font-size: 14pt; "
"font-weight:600;\">%1<span/><p/>"
"<p>Version: %2"
"<br/>Build with: %4 %5, %6"
"<br/>Copyright (c) 2020 Tilmann Meyer<p/>")
.arg(CONFIG_APP_NAME, CONFIG_APP_VERSION, CONFIG_COMPILER,
CONFIG_COMPILER_VERSION, CONFIG_COMPILER_ARCH));
lableDesc->setText(
"Permission is hereby granted, free of charge, to any person "
"obtaining a copy\n"
"of this software and associated documentation files (the "
"\"Software\"), to deal\n"
"in the Software without restriction, including without limitation "
"the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, "
"and/or sell\n"
"copies of the Software, and to permit persons to whom the Software "
"is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be "
"included in all\n"
"copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
"EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
"MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
"SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
"OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
"ARISING FROM,\n"
"OUT OF OR IN CONNECTION WI"
"TH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"
"SOFTWARE\n");
lableIcon->setMaximumSize(QSize(ICON_SIZE, ICON_SIZE));
lableIcon->setPixmap(getIcon(Icon::Logo).pixmap(ICON_SIZE));
lableIcon->setScaledContents(true);
buttonBox->setOrientation(Qt::Orientation::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::StandardButton::Ok);
gridLayout->addWidget(buttonBox, 2, 0, 1, 2);
gridLayout->addWidget(lableIcon, 0, 0, 1, 1);
gridLayout->addWidget(lableDesc, 1, 0, 1, 2);
gridLayout->addWidget(lableTitle, 0, 1, 1, 1);
retranslateUi();
}
void retranslateUi() const {
parent->setWindowTitle(
QCoreApplication::translate("AboutDialog", "About", nullptr));
}
};
} // namespace Ui
class AboutDialog : public QDialog {
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent);
private:
Ui::AboutDialog *ui;
};
| 34.64486 | 80 | 0.626113 |
2853a4fae21d10d113c59f1e5e720e1c399ab643 | 3,304 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 426 | 2015-04-12T10:00:46.000Z | 2022-03-29T11:03:02.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 124 | 2015-05-15T05:51:00.000Z | 2022-02-09T15:25:12.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 214 | 2015-05-06T07:30:37.000Z | 2022-03-26T16:14:04.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcActuatorTypeEnum.h"
// TYPE IfcActuatorTypeEnum = ENUMERATION OF (ELECTRICACTUATOR ,HANDOPERATEDACTUATOR ,HYDRAULICACTUATOR ,PNEUMATICACTUATOR ,THERMOSTATICACTUATOR ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcActuatorTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcActuatorTypeEnum> copy_self( new IfcActuatorTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcActuatorTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCACTUATORTYPEENUM("; }
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: stream << ".ELECTRICACTUATOR."; break;
case ENUM_HANDOPERATEDACTUATOR: stream << ".HANDOPERATEDACTUATOR."; break;
case ENUM_HYDRAULICACTUATOR: stream << ".HYDRAULICACTUATOR."; break;
case ENUM_PNEUMATICACTUATOR: stream << ".PNEUMATICACTUATOR."; break;
case ENUM_THERMOSTATICACTUATOR: stream << ".THERMOSTATICACTUATOR."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcActuatorTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: return L"ELECTRICACTUATOR";
case ENUM_HANDOPERATEDACTUATOR: return L"HANDOPERATEDACTUATOR";
case ENUM_HYDRAULICACTUATOR: return L"HYDRAULICACTUATOR";
case ENUM_PNEUMATICACTUATOR: return L"PNEUMATICACTUATOR";
case ENUM_THERMOSTATICACTUATOR: return L"THERMOSTATICACTUATOR";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcActuatorTypeEnum> IfcActuatorTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
shared_ptr<IfcActuatorTypeEnum> type_object( new IfcActuatorTypeEnum() );
if( std_iequal( arg, L".ELECTRICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_ELECTRICACTUATOR;
}
else if( std_iequal( arg, L".HANDOPERATEDACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HANDOPERATEDACTUATOR;
}
else if( std_iequal( arg, L".HYDRAULICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HYDRAULICACTUATOR;
}
else if( std_iequal( arg, L".PNEUMATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_PNEUMATICACTUATOR;
}
else if( std_iequal( arg, L".THERMOSTATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_THERMOSTATICACTUATOR;
}
else if( std_iequal( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_USERDEFINED;
}
else if( std_iequal( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 39.807229 | 172 | 0.740315 |
2853bc1c7cf0246f945c77713f29bb9cdbda037c | 2,067 | cpp | C++ | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <gtest/gtest.h>
#include <stdexcept>
#include "account.h"
///////////////////////////////////////////////////////////////////
//fixture class for Account
class AccountTestFixtures: public testing::Test
{
public:
AccountTestFixtures();
static void SetUpTestCase();
void SetUp() override;
void TearDown() override;
static void TearDownTestCase();
virtual ~AccountTestFixtures(){
std::cout<<"\n\ndestructor\n\n";
}
protected:
Account accobj;
};
//method implementations
AccountTestFixtures::AccountTestFixtures()
:accobj{"amit", 198}
{
std::cout<<"\n\nconstructor\n\n";
}
void AccountTestFixtures::SetUpTestCase(){
std::cout<<"\n\nsetup test case\n\n";
}
void AccountTestFixtures::SetUp() {
std::cout<<"\n\nsetup\n\n";
accobj.setBalance( 198.0 );
}
void AccountTestFixtures::TearDown() {
std::cout<<"\n\nTearDown\n\n";
}
void AccountTestFixtures::TearDownTestCase(){
std::cout<<"\n\ntear down test case\n\n";
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 1 :: deposit :: normal deposit
TEST_F( AccountTestFixtures, Testdeposit ){
ASSERT_EQ( 188.0, accobj.withdrawl( 10 ));
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 2 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositSmallerThan0 ){
ASSERT_THROW( accobj.withdrawl( -10 ), std::invalid_argument);
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 3 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositNotEnoughBalance ){
ASSERT_THROW( accobj.withdrawl( 2000 ), std::runtime_error);
}
///////////////////////////////////////////////////////////////////
int main( int argc, char* argv[] ){
testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
| 27.197368 | 67 | 0.507499 |
285412303ff4ca73ddb2bcb65033969e40b6acab | 32,986 | cpp | C++ | src/mongo/db/query/lite_parsed_query_test.cpp | joprice/mongo | c8171e7f969519af8b87a43425ae291ee69a0191 | [
"Apache-2.0"
] | 1 | 2015-11-06T05:55:10.000Z | 2015-11-06T05:55:10.000Z | src/mongo/db/query/lite_parsed_query_test.cpp | wujf/mongo | f2f48b749ded0c5585c798c302f6162f19336670 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/lite_parsed_query_test.cpp | wujf/mongo | f2f48b749ded0c5585c798c302f6162f19336670 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2013 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
/**
* This file contains tests for mongo/db/query/list_parsed_query.h
*/
#include "mongo/db/query/lite_parsed_query.h"
#include "mongo/db/json.h"
#include "mongo/unittest/unittest.h"
using namespace mongo;
namespace {
TEST(LiteParsedQueryTest, InitSortOrder) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 1, 0, BSONObj(), BSONObj(),
fromjson("{a: 1}"), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
delete lpq;
}
TEST(LiteParsedQueryTest, InitSortOrderString) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 1, 0, BSONObj(), BSONObj(),
fromjson("{a: \"\"}"), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, GetFilter) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 5, 6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(BSON("x" << 5 ), lpq->getFilter());
delete lpq;
}
TEST(LiteParsedQueryTest, NumToReturn) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 5, 6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(6, lpq->getNumToReturn());
ASSERT(lpq->wantMore());
delete lpq;
lpq = NULL;
result = LiteParsedQuery::make("testns", 5, -6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(6, lpq->getNumToReturn());
ASSERT(!lpq->wantMore());
delete lpq;
}
TEST(LiteParsedQueryTest, MinFieldsNotPrefixOfMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1}"), fromjson("{b: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, MinFieldsMoreThanMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1, b: 1}"), fromjson("{a: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, MinFieldsLessThanMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1}"), fromjson("{a: 1, b: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
// Helper function which returns the Status of creating a LiteParsedQuery object with the given
// parameters.
Status makeLiteParsedQuery(const BSONObj& query, const BSONObj& proj, const BSONObj& sort) {
LiteParsedQuery* lpqRaw;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, query, proj, sort, BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpqRaw);
if (result.isOK()) {
boost::scoped_ptr<LiteParsedQuery> lpq(lpqRaw);
}
return result;
}
//
// Test compatibility of various projection and sort objects.
//
TEST(LiteParsedQueryTest, ValidSortProj) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: 1}"),
fromjson("{a: 1}"));
ASSERT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_OK(result);
}
TEST(LiteParsedQueryTest, ForbidNonMetaSortOnFieldWithMetaProject) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{a: 1}"));
ASSERT_NOT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{b: 1}"));
ASSERT_OK(result);
}
TEST(LiteParsedQueryTest, ForbidMetaSortOnFieldWithoutMetaProject) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: 1}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_NOT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{b: 1}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_NOT_OK(result);
}
//
// Text meta BSON element validation
//
bool isFirstElementTextScoreMeta(const char* sortStr) {
BSONObj sortObj = fromjson(sortStr);
BSONElement elt = sortObj.firstElement();
bool result = LiteParsedQuery::isTextScoreMeta(elt);
return result;
}
// Check validation of $meta expressions
TEST(LiteParsedQueryTest, IsTextScoreMeta) {
// Valid textScore meta sort
ASSERT(isFirstElementTextScoreMeta("{a: {$meta: \"textScore\"}}"));
// Invalid textScore meta sorts
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: 1}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: \"image\"}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$world: \"textScore\"}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: \"textScore\", b: 1}}"));
}
//
// Sort order validation
// In a valid sort order, each element satisfies one of:
// 1. a number with value 1
// 2. a number with value -1
// 3. isTextScoreMeta
//
TEST(LiteParsedQueryTest, ValidateSortOrder) {
// Valid sorts
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: 1}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: -1}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"textScore\"}}")));
// Invalid sorts
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: 100}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: 0}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: -100}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: Infinity}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: -Infinity}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: true}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: false}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: null}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {b: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: []}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: [1, 2, 3]}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: \"\"}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: \"bb\"}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"image\"}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$world: \"textScore\"}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"textScore\","
" b: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{'': 1}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{'': -1}")));
}
//
// Tests for parsing a lite parsed query from a command BSON object.
//
TEST(LiteParsedQueryTest, ParseFromCommandBasic) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 3},"
"sort: {a: 1},"
"projection: {_id: 0, a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandWithOptions) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 3},"
"sort: {a: 1},"
"projection: {_id: 0, a: 1},"
"options: {showDiskLoc: true, maxScan: 1000}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Make sure the values from the command BSON are reflected in the LPQ.
ASSERT(lpq->getOptions().showDiskLoc);
ASSERT_EQUALS(1000, lpq->getMaxScan());
}
TEST(LiteParsedQueryTest, ParseFromCommandHintAsString) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"hint: 'foo_1'}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
ASSERT_EQUALS("foo_1", lpq->getHint().firstElement().str());
}
TEST(LiteParsedQueryTest, ParseFromCommandValidSortProj) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"projection: {a: 1},"
"sort: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandValidSortProjMeta) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {a: {$meta: 'textScore'}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandAllFlagsTrue) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {"
"tailable: true,"
"slaveOk: true,"
"oplogReplay: true,"
"noCursorTimeout: true,"
"awaitData: true,"
"exhaust: true,"
"partial: true"
"}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Test that all the flags got set to true.
ASSERT(lpq->getOptions().tailable);
ASSERT(lpq->getOptions().slaveOk);
ASSERT(lpq->getOptions().oplogReplay);
ASSERT(lpq->getOptions().noCursorTimeout);
ASSERT(lpq->getOptions().awaitData);
ASSERT(lpq->getOptions().exhaust);
ASSERT(lpq->getOptions().partial);
}
TEST(LiteParsedQueryTest, ParseFromCommandCommentWithValidMinMax) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {"
"comment: 'the comment',"
"min: {a: 1},"
"max: {a: 2}"
"}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
ASSERT_EQUALS("the comment", lpq->getOptions().comment);
BSONObj expectedMin = BSON("a" << 1);
ASSERT_EQUALS(0, expectedMin.woCompare(lpq->getMin()));
BSONObj expectedMax = BSON("a" << 2);
ASSERT_EQUALS(0, expectedMax.woCompare(lpq->getMax()));
}
TEST(LiteParsedQueryTest, ParseFromCommandAllNonOptionFields) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"sort: {b: 1},"
"projection: {c: 1},"
"hint: {d: 1},"
"limit: 3,"
"skip: 5,"
"batchSize: 90,"
"singleBatch: false}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Check the values inside the LPQ.
BSONObj expectedQuery = BSON("a" << 1);
ASSERT_EQUALS(0, expectedQuery.woCompare(lpq->getFilter()));
BSONObj expectedSort = BSON("b" << 1);
ASSERT_EQUALS(0, expectedSort.woCompare(lpq->getSort()));
BSONObj expectedProj = BSON("c" << 1);
ASSERT_EQUALS(0, expectedProj.woCompare(lpq->getProj()));
BSONObj expectedHint = BSON("d" << 1);
ASSERT_EQUALS(0, expectedHint.woCompare(lpq->getHint()));
ASSERT_EQUALS(3, lpq->getLimit());
ASSERT_EQUALS(5, lpq->getSkip());
ASSERT_EQUALS(90, lpq->getBatchSize());
ASSERT(lpq->wantMore());
}
//
// Parsing errors where a field has the wrong type.
//
TEST(LiteParsedQueryTest, ParseFromCommandQueryWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: 3}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSortWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"sort: 3}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandProjWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"projection: 'foo'}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSkipWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"skip: '5',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandLimitWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"limit: '5',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSingleBatchWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"singleBatch: 'false',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandOptionsWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: [{snapshot: true}],"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandCommentWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {comment: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxScanWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {maxScan: true, comment: 'foo'}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxTimeMSWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {maxTimeMS: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {max: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMinWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {min: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandReturnKeyWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {returnKey: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandShowDiskLocWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {showDiskLoc: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {snapshot: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandTailableWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {tailable: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSlaveOkWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {slaveOk: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandOplogReplayWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {oplogReplay: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNoCursorTimeoutWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {noCursorTimeout: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandAwaitDataWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {awaitData: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandExhaustWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {exhaust: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandPartialWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {exhaust: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Parsing errors where a field has the right type but a bad value.
//
TEST(LiteParsedQueryTest, ParseFromCommandNegativeSkipError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"skip: -3,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNegativeLimitError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"limit: -3,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNegativeBatchSizeError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"batchSize: -10,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Errors checked in LiteParsedQuery::validate().
//
TEST(LiteParsedQueryTest, ParseFromCommandMinMaxDifferentFieldsError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {min: {a: 3}, max: {b: 4}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotPlusSortError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"sort: {a: 3},"
"options: {snapshot: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotPlusHintError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true},"
"hint: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseCommandForbidNonMetaSortOnFieldWithMetaProject) {
Status status = Status::OK();
BSONObj cmdObj;
cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {b: 1}}");
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseCommandForbidMetaSortOnFieldWithoutMetaProject) {
Status status = Status::OK();
BSONObj cmdObj;
cmdObj = fromjson("{find: 'testns',"
"projection: {a: 1},"
"sort: {a: {$meta: 'textScore'}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
cmdObj = fromjson("{find: 'testns',"
"projection: {b: 1},"
"sort: {a: {$meta: 'textScore'}}}");
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Extra fields cause the parse to fail.
//
TEST(LiteParsedQueryTest, ParseFromCommandForbidExtraField) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true},"
"foo: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandForbidExtraOption) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true, foo: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
} // namespace
| 41.078456 | 99 | 0.518008 |
28547d18f64675f20e099d4d409b3a5608668593 | 2,434 | hpp | C++ | VNFs/DPPD-PROX/tools/flow_extract/stream.hpp | plvisiondevs/samplevnf | ffdcfa6b834d3ad00188ee9805370d6aefc44b4b | [
"Apache-2.0"
] | 19 | 2017-10-13T11:14:19.000Z | 2022-02-13T12:26:42.000Z | VNFs/DPPD-PROX/tools/flow_extract/stream.hpp | plvisiondevs/samplevnf | ffdcfa6b834d3ad00188ee9805370d6aefc44b4b | [
"Apache-2.0"
] | 1 | 2022-01-25T12:33:52.000Z | 2022-01-25T12:33:52.000Z | VNFs/DPPD-PROX/tools/flow_extract/stream.hpp | plvisiondevs/samplevnf | ffdcfa6b834d3ad00188ee9805370d6aefc44b4b | [
"Apache-2.0"
] | 22 | 2017-09-21T01:54:35.000Z | 2021-11-07T06:40:11.000Z | /*
// Copyright (c) 2010-2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifndef _STREAM_H_
#define _STREAM_H_
#include <list>
#include <string>
#include <fstream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <sys/time.h>
#include "pcappktref.hpp"
#include "pcappkt.hpp"
#include "netsocket.hpp"
#include "timestamp.hpp"
#include "halfstream.hpp"
using namespace std;
class PcapReader;
class Stream {
public:
struct Header {
uint32_t streamId;
uint16_t clientHdrLen;
uint32_t clientContentLen;
uint16_t serverHdrLen;
uint32_t serverContentLen;
uint32_t actionCount;
uint32_t clientIP;
uint16_t clientPort;
uint32_t serverIP;
uint16_t serverPort;
double upRate;
double dnRate;
uint8_t protocol;
uint8_t completedTCP;
void toFile(ofstream *f) const;
int fromFile(ifstream *f);
size_t getStreamLen() const;
};
struct ActionEntry {
uint8_t peer;
uint32_t beg;
uint32_t len;
} __attribute__((packed));
Stream(uint32_t id = -1, uint32_t sizeHint = 0);
void addPkt(const PcapPkt &pkt);
void toFile(ofstream *f);
void toPcap(const string& outFile);
double getRate() const;
size_t actionCount() const {return m_actions.size();}
private:
Header getHeader() const;
void actionsToFile(ofstream *f) const;
void clientHdrToFile(ofstream *f) const;
void serverHdrToFile(ofstream *f) const;
void contentsToFile(ofstream *f, bool isClient) const;
bool isClient(const PcapPkt &pkt) const;
size_t pktCount() const;
struct pkt_tuple m_pt;
void setTupleFromPkt(const PcapPkt &pkt);
void addToClient(const PcapPkt &pkt);
void addToServer(const PcapPkt &pkt);
void addAction(HalfStream *half, HalfStream::Action::Part p, bool isClientPkt);
int m_id;
vector<PcapPkt> m_pkts;
vector<HalfStream::Action> m_actions;
HalfStream m_client;
HalfStream m_server;
bool m_prevPktIsClient;
};
#endif /* _STREAM_H_ */
| 25.621053 | 80 | 0.741988 |
2854d4ff3ddbc2c5e17ae5989f6087554f272d9f | 2,183 | hpp | C++ | lib/STL+/containers/matrix.hpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | 65 | 2021-01-06T12:36:22.000Z | 2021-06-21T10:30:09.000Z | deps/stlplus/containers/matrix.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 4 | 2021-12-06T16:00:00.000Z | 2022-03-18T07:40:33.000Z | deps/stlplus/containers/matrix.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 11 | 2021-01-07T02:57:02.000Z | 2021-05-31T06:10:56.000Z | #ifndef STLPLUS_MATRIX
#define STLPLUS_MATRIX
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// General-purpose 2D matrix data structure
////////////////////////////////////////////////////////////////////////////////
#include "containers_fixes.hpp"
#include <stdexcept>
namespace stlplus
{
////////////////////////////////////////////////////////////////////////////////
template<typename T> class matrix
{
public:
matrix(unsigned rows = 0, unsigned cols = 0, const T& fill = T()) ;
~matrix(void) ;
matrix(const matrix&) ;
matrix& operator =(const matrix&) ;
void resize(unsigned rows, unsigned cols, const T& fill = T()) ;
unsigned rows(void) const ;
unsigned columns(void) const ;
void erase(const T& fill = T()) ;
// exceptions: std::out_of_range
void erase(unsigned row, unsigned col, const T& fill = T()) ;
// exceptions: std::out_of_range
void insert(unsigned row, unsigned col, const T&) ;
// exceptions: std::out_of_range
const T& item(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& item(unsigned row, unsigned col) ;
// exceptions: std::out_of_range
const T& operator()(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& operator()(unsigned row, unsigned col) ;
void fill(const T& item = T()) ;
// exceptions: std::out_of_range
void fill_column(unsigned col, const T& item = T()) ;
// exceptions: std::out_of_range
void fill_row(unsigned row, const T& item = T()) ;
void fill_leading_diagonal(const T& item = T()) ;
void fill_trailing_diagonal(const T& item = T()) ;
void make_identity(const T& one, const T& zero = T()) ;
void transpose(void) ;
private:
unsigned m_rows;
unsigned m_cols;
T** m_data;
};
////////////////////////////////////////////////////////////////////////////////
} // end namespace stlplus
#include "matrix.tpp"
#endif
| 30.319444 | 82 | 0.55016 |
2855669ef1d39b987605349694dc6e7653d21e67 | 4,667 | hpp | C++ | src/buffer_cache/evicter.hpp | zadcha/rethinkdb | bb4f5cc28242dc1e29e9a46a8a931ec54420070c | [
"Apache-2.0"
] | 21,684 | 2015-01-01T03:42:20.000Z | 2022-03-30T13:32:44.000Z | src/buffer_cache/evicter.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 4,067 | 2015-01-01T00:04:51.000Z | 2022-03-30T13:42:56.000Z | src/buffer_cache/evicter.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 1,901 | 2015-01-01T21:05:59.000Z | 2022-03-21T08:14:25.000Z | #ifndef BUFFER_CACHE_EVICTER_HPP_
#define BUFFER_CACHE_EVICTER_HPP_
#include <stdint.h>
#include <functional>
#include "buffer_cache/eviction_bag.hpp"
#include "concurrency/auto_drainer.hpp"
#include "concurrency/cache_line_padded.hpp"
#include "concurrency/pubsub.hpp"
#include "threading.hpp"
#include "time.hpp"
class cache_balancer_t;
class alt_txn_throttler_t;
namespace alt {
class page_cache_t;
class evicter_t : public home_thread_mixin_debug_only_t {
public:
void add_not_yet_loaded(page_t *page);
void add_deferred_loaded(page_t *page);
void catch_up_deferred_load(page_t *page);
void add_to_evictable_unbacked(page_t *page);
void add_to_evictable_disk_backed(page_t *page);
bool page_is_in_unevictable_bag(page_t *page) const;
bool page_is_in_evicted_bag(page_t *page) const;
void move_unevictable_to_evictable(page_t *page);
void change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page);
eviction_bag_t *correct_eviction_category(page_t *page);
eviction_bag_t *evicted_category() { return &evicted_; }
void remove_page(page_t *page);
void reloading_page(page_t *page);
// Evicter will be unusable until initialize is called
evicter_t();
~evicter_t();
void initialize(page_cache_t *page_cache,
cache_balancer_t *balancer,
alt_txn_throttler_t *throttler);
void update_memory_limit(uint64_t new_memory_limit,
int64_t bytes_loaded_accounted_for,
uint64_t access_count_accounted_for,
bool read_ahead_ok);
uint64_t next_access_time() {
guarantee_initialized();
return ++access_time_counter_;
}
uint64_t memory_limit() const {
guarantee_initialized();
return memory_limit_;
}
uint64_t access_count() const {
guarantee_initialized();
return access_count_counter_;
}
uint64_t unevictable_size() const {
guarantee_initialized();
return unevictable_.size();
}
uint64_t evictable_disk_backed_size() const {
guarantee_initialized();
return evictable_disk_backed_.size();
}
uint64_t evictable_unbacked_size() const {
guarantee_initialized();
return evictable_unbacked_.size();
}
int64_t get_bytes_loaded() const {
guarantee_initialized();
return bytes_loaded_counter_;
}
uint64_t in_memory_size() const;
// This is decremented past UINT64_MAX to force code to be aware of access time
// rollovers.
static const uint64_t INITIAL_ACCESS_TIME = UINT64_MAX - 100;
private:
void guarantee_initialized() const {
assert_thread();
guarantee(initialized_);
}
friend class usage_adjuster_t;
// Tells the cache balancer about a page being loaded
void notify_bytes_loading(int64_t ser_buf_change);
// Evicts any evictable pages until under the memory limit
void evict_if_necessary() THROWS_NOTHING;
bool initialized_;
page_cache_t *page_cache_;
cache_balancer_t *balancer_;
bool *balancer_notify_activity_boolean_;
alt_txn_throttler_t *throttler_;
uint64_t memory_limit_;
// These are updated every time a page is loaded, created, or destroyed, and
// cleared when cache memory limits are re-evaluated. This value can go
// negative, if you keep deleting blocks or suddenly drop a snapshot.
int64_t bytes_loaded_counter_;
uint64_t access_count_counter_;
// This gets incremented every time a page is accessed.
uint64_t access_time_counter_;
// This is set to true while `evict_if_necessary()` is active.
// It avoids reentrant calls to that function.
bool evict_if_necessary_active_;
// These track every page's eviction status.
eviction_bag_t unevictable_;
eviction_bag_t evictable_disk_backed_;
eviction_bag_t evictable_unbacked_;
eviction_bag_t evicted_;
ticks_t last_force_flush_time_;
auto_drainer_t drainer_;
DISABLE_COPYING(evicter_t);
};
// This adjusts the memory usage in the destructor, with the _same_ eviction bag the
// page had in the constructor -- its lifespan ends before the page would have its
// eviction bag changed.
class usage_adjuster_t {
public:
usage_adjuster_t(page_cache_t *page_cache, page_t *page);
~usage_adjuster_t();
private:
page_cache_t *const page_cache_;
page_t *const page_;
eviction_bag_t *const eviction_bag_;
const uint32_t original_usage_;
DISABLE_COPYING(usage_adjuster_t);
};
} // namespace alt
#endif // BUFFER_CACHE_EVICTER_HPP_
| 29.726115 | 84 | 0.719091 |
2855cd96d30b58bbd0de294310c725c9e760088b | 6,641 | cc | C++ | mojo/edk/system/dispatcher.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mojo/edk/system/dispatcher.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mojo/edk/system/dispatcher.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/edk/system/dispatcher.h"
#include "base/logging.h"
#include "mojo/edk/system/configuration.h"
#include "mojo/edk/system/data_pipe_consumer_dispatcher.h"
#include "mojo/edk/system/data_pipe_producer_dispatcher.h"
#include "mojo/edk/system/message_pipe_dispatcher.h"
#include "mojo/edk/system/platform_handle_dispatcher.h"
#include "mojo/edk/system/ports/event.h"
#include "mojo/edk/system/shared_buffer_dispatcher.h"
namespace mojo {
namespace edk {
Dispatcher::DispatcherInTransit::DispatcherInTransit() {}
Dispatcher::DispatcherInTransit::DispatcherInTransit(
const DispatcherInTransit& other) = default;
Dispatcher::DispatcherInTransit::~DispatcherInTransit() {}
MojoResult Dispatcher::WatchDispatcher(scoped_refptr<Dispatcher> dispatcher,
MojoHandleSignals signals,
MojoWatchCondition condition,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::CancelWatch(uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::Arm(uint32_t* num_ready_contexts,
uintptr_t* ready_contexts,
MojoResult* ready_results,
MojoHandleSignalsState* ready_signals_states) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::WriteMessage(
std::unique_ptr<ports::UserMessageEvent> message,
MojoWriteMessageFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::ReadMessage(
std::unique_ptr<ports::UserMessageEvent>* message) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::DuplicateBufferHandle(
const MojoDuplicateBufferHandleOptions* options,
scoped_refptr<Dispatcher>* new_dispatcher) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::MapBuffer(
uint64_t offset,
uint64_t num_bytes,
MojoMapBufferFlags flags,
std::unique_ptr<PlatformSharedBufferMapping>* mapping) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::ReadData(void* elements,
uint32_t* num_bytes,
MojoReadDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::BeginReadData(const void** buffer,
uint32_t* buffer_num_bytes,
MojoReadDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::EndReadData(uint32_t num_bytes_read) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::WriteData(const void* elements,
uint32_t* num_bytes,
MojoWriteDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::BeginWriteData(void** buffer,
uint32_t* buffer_num_bytes,
MojoWriteDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::EndWriteData(uint32_t num_bytes_written) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::AddWaitingDispatcher(
const scoped_refptr<Dispatcher>& dispatcher,
MojoHandleSignals signals,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::RemoveWaitingDispatcher(
const scoped_refptr<Dispatcher>& dispatcher) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::GetReadyDispatchers(uint32_t* count,
DispatcherVector* dispatchers,
MojoResult* results,
uintptr_t* contexts) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
HandleSignalsState Dispatcher::GetHandleSignalsState() const {
return HandleSignalsState();
}
MojoResult Dispatcher::AddWatcherRef(
const scoped_refptr<WatcherDispatcher>& watcher,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::RemoveWatcherRef(WatcherDispatcher* watcher,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
void Dispatcher::StartSerialize(uint32_t* num_bytes,
uint32_t* num_ports,
uint32_t* num_platform_handles) {
*num_bytes = 0;
*num_ports = 0;
*num_platform_handles = 0;
}
bool Dispatcher::EndSerialize(void* destination,
ports::PortName* ports,
PlatformHandle* handles) {
LOG(ERROR) << "Attempting to serialize a non-transferrable dispatcher.";
return true;
}
bool Dispatcher::BeginTransit() {
return true;
}
void Dispatcher::CompleteTransitAndClose() {}
void Dispatcher::CancelTransit() {}
// static
scoped_refptr<Dispatcher> Dispatcher::Deserialize(
Type type,
const void* bytes,
size_t num_bytes,
const ports::PortName* ports,
size_t num_ports,
PlatformHandle* platform_handles,
size_t num_platform_handles) {
switch (type) {
case Type::MESSAGE_PIPE:
return MessagePipeDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
case Type::SHARED_BUFFER:
return SharedBufferDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
case Type::DATA_PIPE_CONSUMER:
return DataPipeConsumerDispatcher::Deserialize(
bytes, num_bytes, ports, num_ports, platform_handles,
num_platform_handles);
case Type::DATA_PIPE_PRODUCER:
return DataPipeProducerDispatcher::Deserialize(
bytes, num_bytes, ports, num_ports, platform_handles,
num_platform_handles);
case Type::PLATFORM_HANDLE:
return PlatformHandleDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
default:
LOG(ERROR) << "Deserializing invalid dispatcher type.";
return nullptr;
}
}
Dispatcher::Dispatcher() {}
Dispatcher::~Dispatcher() {}
} // namespace edk
} // namespace mojo
| 33.205 | 79 | 0.660593 |
2857e6515c8cc11801506a908c7252d93ba529c1 | 62 | hpp | C++ | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 4 | 2020-05-04T18:03:59.000Z | 2020-05-06T19:40:27.000Z | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 13 | 2020-05-06T19:02:06.000Z | 2020-08-24T08:16:43.000Z | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 5 | 2020-05-04T18:04:05.000Z | 2020-05-14T16:53:13.000Z | #define COMPONENT JIP
#include "..\..\script_component.hpp"
| 20.666667 | 38 | 0.709677 |
285b157bd91e1f11fa4f4c0c4a349bb4c69b3637 | 1,988 | cpp | C++ | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | #include <opencv2/opencv.hpp>
#include <iostream>
#include <omp.h>
#include <fstream>
#include <string>
#include <filesystem>
#include <chrono>
namespace fs = std::filesystem;
using namespace std;
// goal load a video file and process it with multithearding
vector<string> getFiles(string path){
//cout << "adding " + path << endl;
// this is it for now
vector<string> files;
for(const auto & entry : fs::directory_iterator(path)){
string it = entry.path();
//cout << it << endl;
files.push_back(it);
}
return files;
}
cv::Mat blackWhite(cv::Mat img){
cv::Mat grey;
cv::cvtColor(img, grey, cv::COLOR_BGR2GRAY);
return grey;
}
uint64_t timeSinceEpochMillisec(){
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main(int argc, const char* argv[]){
string path = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/Video/Weeds2/nenuphare/data1595119927.9510028output.avi";
string save = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/dump/";
int64_t start = timeSinceEpochMillisec();
cout << start << endl;
cv::VideoCapture cap(path);
cv::Mat frame;
while (1){
if (!cap.read(frame)){
cout << "al done" << endl;
break;
}
//cout << "test" << endl;
cv::Mat img = blackWhite(frame);
//cout << "OK" << endl;
//string windowName = "display " + to_string(i);
int64_t current = timeSinceEpochMillisec();
string name = save + to_string(current) + "ok.jpg";
cv::imwrite(name, img);
// this code will be a task that may be executed immediately on a different core or deferred for later execution
} // end of while loop and single region
uint64_t end = timeSinceEpochMillisec();
uint64_t total = end - start;
cout << end << endl;
cout << total << endl;
return 0;
}
| 18.238532 | 131 | 0.622233 |
285ba9ea9a30d009e31a5906e49bc6cbc8bb45c0 | 2,203 | cpp | C++ | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 675 | 2019-05-28T19:00:55.000Z | 2022-03-31T16:44:28.000Z | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 13 | 2020-03-29T06:46:32.000Z | 2022-01-29T03:19:30.000Z | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 53 | 2019-06-02T03:04:10.000Z | 2022-03-11T06:17:50.000Z | #include <ncine/common_macros.h>
#include <nctl/ProxyAllocator.h>
namespace nctl {
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
ProxyAllocator::ProxyAllocator(const char *name, IAllocator &allocator)
: IAllocator(name, allocateImpl, reallocateImpl, deallocateImpl, 0, nullptr),
allocator_(allocator)
{
}
ProxyAllocator::~ProxyAllocator()
{
FATAL_ASSERT(usedMemory_ == 0 && numAllocations_ == 0);
}
///////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
///////////////////////////////////////////////////////////
void *ProxyAllocator::allocateImpl(IAllocator *allocator, size_t bytes, uint8_t alignment)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *ptr = subject.allocateFunc_(&subject, bytes, alignment);
if (ptr)
{
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
allocatorImpl->numAllocations_++;
}
return ptr;
}
void *ProxyAllocator::reallocateImpl(IAllocator *allocator, void *ptr, size_t bytes, uint8_t alignment, size_t &oldSize)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *newPtr = subject.reallocateFunc_(&subject, ptr, bytes, alignment, oldSize);
if (newPtr)
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
return newPtr;
}
void ProxyAllocator::deallocateImpl(IAllocator *allocator, void *ptr)
{
if (ptr == nullptr)
return;
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
subject.deallocateFunc_(&subject, ptr);
allocatorImpl->usedMemory_ -= memoryUsedBefore - subject.usedMemory();
FATAL_ASSERT(allocatorImpl->numAllocations_ > 0);
allocatorImpl->numAllocations_--;
}
}
| 29.77027 | 120 | 0.684521 |
286048f8b0629f4e1171e3411031b2ca73a38f01 | 1,784 | cc | C++ | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 16 | 2018-08-30T19:55:43.000Z | 2022-02-16T16:38:06.000Z | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 151 | 2018-05-27T13:01:50.000Z | 2021-08-04T14:50:50.000Z | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 20 | 2018-11-13T13:46:38.000Z | 2022-02-18T17:33:52.000Z | /** @file runtime_test.cc
* @brief Some tests for runtime behavior of certain C++ constructs
*/
#include <iostream>
#include "lf/base/base.h"
static const int N = 10;
static double stat_tmp[N]; // NOLINT
std::vector<double> getData_VEC(double offset) {
std::vector<double> tmp(10);
for (int j = 0; j < N; j++) {
tmp[j] = 1.0 / (j + offset);
}
return tmp;
}
// NOLINTNEXTLINE
void getData_REF(double offset, std::vector<double> &res) {
for (int j = 0; j < N; j++) {
res[j] = 1.0 / (j + offset);
}
}
nonstd::span<const double> getData_SPAN(double offset) {
for (int j = 0; j < N; j++) {
stat_tmp[j] = 1.0 / (j + offset);
}
return {static_cast<double *>(stat_tmp), (stat_tmp + N)};
}
int main(int /*argc*/, const char * /*unused*/[]) {
std::cout << "Runtime test for range access" << std::endl;
const long int reps = 100000000L;
std::cout << "I. Returning std::vector's" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_VEC(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "II. Returning result through reference" << std::endl;
{
lf::base::AutoTimer t;
std::vector<double> res(N);
for (long int i = 0; i < reps; i++) {
getData_REF(static_cast<double>(i), res);
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "III. Returning result through span" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_SPAN(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
return 0;
}
| 22.582278 | 69 | 0.538677 |
28617c6019b7bdfdb91bc6e8d63550ad8afaac6a | 4,390 | hpp | C++ | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | 1 | 2020-01-10T04:13:44.000Z | 2020-01-10T04:13:44.000Z | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | null | null | null | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XWIDGETS_VIDEO_HPP
#define XWIDGETS_VIDEO_HPP
#include <cstddef>
#include <string>
#include <vector>
#include "xmaterialize.hpp"
#include "xmedia.hpp"
namespace xw
{
/*********************
* video declaration *
*********************/
template <class D>
class xvideo : public xmedia<D>
{
public:
using base_type = xmedia<D>;
using derived_type = D;
void serialize_state(nl::json& state, xeus::buffer_sequence&) const;
void apply_patch(const nl::json&, const xeus::buffer_sequence&);
XPROPERTY(std::string, derived_type, format, "mp4");
XPROPERTY(std::string, derived_type, width, "");
XPROPERTY(std::string, derived_type, height, "");
XPROPERTY(bool, derived_type, autoplay, true);
XPROPERTY(bool, derived_type, loop, true);
XPROPERTY(bool, derived_type, controls, true);
protected:
xvideo();
using base_type::base_type;
private:
void set_defaults();
};
using video = xmaterialize<xvideo>;
/*************************
* xvideo implementation *
*************************/
template <class D>
inline void xvideo<D>::serialize_state(nl::json& state, xeus::buffer_sequence& buffers) const
{
base_type::serialize_state(state, buffers);
xwidgets_serialize(format(), state["format"], buffers);
xwidgets_serialize(width(), state["width"], buffers);
xwidgets_serialize(height(), state["height"], buffers);
xwidgets_serialize(autoplay(), state["autoplay"], buffers);
xwidgets_serialize(loop(), state["loop"], buffers);
xwidgets_serialize(controls(), state["controls"], buffers);
}
template <class D>
inline void xvideo<D>::apply_patch(const nl::json& patch, const xeus::buffer_sequence& buffers)
{
base_type::apply_patch(patch, buffers);
set_property_from_patch(format, patch, buffers);
set_property_from_patch(width, patch, buffers);
set_property_from_patch(height, patch, buffers);
set_property_from_patch(autoplay, patch, buffers);
set_property_from_patch(loop, patch, buffers);
set_property_from_patch(controls, patch, buffers);
}
template <class D>
inline xvideo<D>::xvideo()
: base_type()
{
set_defaults();
}
template <class D>
inline void xvideo<D>::set_defaults()
{
this->_model_name() = "VideoModel";
this->_view_name() = "VideoView";
}
/**********************
* custom serializers *
**********************/
inline void set_property_from_patch(decltype(video::value)& property,
const nl::json& patch,
const xeus::buffer_sequence& buffers)
{
auto it = patch.find(property.name());
if (it != patch.end())
{
using value_type = typename decltype(video::value)::value_type;
std::size_t index = buffer_index(patch[property.name()].template get<std::string>());
const auto& value_buffer = buffers[index];
const char* value_buf = value_buffer.data<const char>();
property = value_type(value_buf, value_buf + value_buffer.size());
}
}
inline auto video_from_file(const std::string& filename)
{
return video::initialize().value(read_file(filename));
}
inline auto video_from_url(const std::string& url)
{
std::vector<char> value(url.cbegin(), url.cend());
return video::initialize().value(value).format("url");
}
/*********************
* precompiled types *
*********************/
extern template class xmaterialize<xvideo>;
extern template class xtransport<xmaterialize<xvideo>>;
}
#endif
| 32.043796 | 99 | 0.550797 |
2864b7d13c542879e010c7d2fb375e9f194c14e1 | 4,259 | hxx | C++ | com/ole32/stg/async/layoutui/layoutui.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/stg/async/layoutui/layoutui.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/stg/async/layoutui/layoutui.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1996.
//
// File: layoutui.hxx
//
// Contents: Common header file Layout Tool UI
//
// Classes: CLayoutApp
// COleClientSite
//
// History: 23-Mar-96 SusiA Created
//
//----------------------------------------------------------------------------
#ifndef __LAYOUTUI_HXX__
#define __LAYOUTUI_HXX__
#include <windows.h>
#include <shellapi.h>
#include <commdlg.h>
#include <cderr.h>
#include <winuser.h>
#include "resource.h"
#ifndef STG_E_NONEOPTIMIZED
#define STG_E_NONEOPTIMIZED _HRESULT_TYPEDEF_(0x80030205L)
#endif
#define gdxWndMin 300;
#define gdyWndMin 300;
#define hwndNil NULL;
#define hNil NULL;
#define bMsgHandled 1
#define bMsgNotHandled 0
class CLayoutApp
{
public:
CLayoutApp(HINSTANCE hInst);
BOOL InitApp(void);
INT DoAppMessageLoop(void);
private:
HINSTANCE m_hInst;
HWND m_hwndMain;
HWND m_hwndBtnAdd;
HWND m_hwndBtnRemove;
HWND m_hwndBtnOptimize;
HWND m_hwndListFiles;
HWND m_hwndStaticFiles;
BOOL m_bOptimizing;
BOOL m_bCancelled;
static INT_PTR CALLBACK LayoutDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LONG CALLBACK ListBoxWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LONG CALLBACK ButtonWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static DWORD OptimizeFiles (void *args);
BOOL InitWindow (void);
VOID ReSizeWindow( LPARAM lParam );
VOID AddFiles( void );
VOID RemoveFiles( void );
VOID EnableButtons( BOOL bShowOptimizeBtn = TRUE );
VOID FormFilterString( TCHAR *patcFilter, INT nMaxLen );
VOID WriteFilesToList( TCHAR *patc );
VOID AddFileToListBox( TCHAR *patcFile );
VOID RemoveFileFromListBox( INT nIndex );
VOID SetListBoxExtent( void );
VOID HandleOptimizeReturnCode( SCODE sc );
VOID SetActionButton( UINT uID );
INT DisplayMessage( HWND hWnd,
UINT uMessageID,
UINT uTitleID,
UINT uFlags );
INT DisplayMessageWithFileName(HWND hWnd,
UINT uMessageIDBefore,
UINT uMessageIDAfter,
UINT uTitleID,
UINT uFlags,
TCHAR *patcFileName);
INT CLayoutApp::DisplayMessageWithTwoFileNames(HWND hWnd,
UINT uMessageID,
UINT uTitleID,
UINT uFlags,
TCHAR *patcFirstFileName,
TCHAR *patcLastFileName);
SCODE OptimizeFilesWorker( void );
SCODE DoOptimizeFile( TCHAR *patcFileName, TCHAR *patcTempFile );
OLECHAR *TCharToOleChar(TCHAR *atcSrc, OLECHAR *awcDst, INT nDstLen);
#if DBG==1
BOOL CLayoutApp::IdenticalFiles( TCHAR *patcFileOne,
TCHAR *patcFileTwo);
#endif
};
class COleClientSite : public IOleClientSite
{
public:
TCHAR *m_patcFile;
inline COleClientSite(void);
// IUnknown
STDMETHOD(QueryInterface)(REFIID riid, void** ppObject);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
//IOleClientSite
STDMETHOD (SaveObject)( void);
STDMETHOD (GetMoniker)(
/* [in] */ DWORD dwAssign,
/* [in] */ DWORD dwWhichMoniker,
/* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk);
STDMETHOD (GetContainer)(
/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer);
STDMETHOD (ShowObject)( void);
STDMETHOD (OnShowWindow)(
/* [in] */ BOOL fShow);
STDMETHOD (RequestNewObjectLayout)( void);
private:
LONG _cReferences;
};
inline COleClientSite::COleClientSite(void)
{
_cReferences = 1;
}
#endif // __LAYOUTUI_HXX__
| 26.128834 | 95 | 0.565391 |
28652391a9f68b49c85f7080f7cf3b649c33dabc | 6,641 | cc | C++ | net/base/directory_lister.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/base/directory_lister.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/base/directory_lister.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:23:37.000Z | 2020-11-04T07:23:37.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/directory_lister.h"
#include <algorithm>
#include <vector>
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/i18n/file_util_icu.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "net/base/net_errors.h"
namespace net {
namespace {
bool IsDotDot(const base::FilePath& path) {
return FILE_PATH_LITERAL("..") == path.BaseName().value();
}
// Comparator for sorting lister results. This uses the locale aware filename
// comparison function on the filenames for sorting in the user's locale.
// Static.
bool CompareAlphaDirsFirst(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
// Parent directory before all else.
if (IsDotDot(a.info.GetName()))
return true;
if (IsDotDot(b.info.GetName()))
return false;
// Directories before regular files.
bool a_is_directory = a.info.IsDirectory();
bool b_is_directory = b.info.IsDirectory();
if (a_is_directory != b_is_directory)
return a_is_directory;
return base::i18n::LocaleAwareCompareFilenames(a.info.GetName(),
b.info.GetName());
}
bool CompareDate(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
// Parent directory before all else.
if (IsDotDot(a.info.GetName()))
return true;
if (IsDotDot(b.info.GetName()))
return false;
// Directories before regular files.
bool a_is_directory = a.info.IsDirectory();
bool b_is_directory = b.info.IsDirectory();
if (a_is_directory != b_is_directory)
return a_is_directory;
return a.info.GetLastModifiedTime() > b.info.GetLastModifiedTime();
}
// Comparator for sorting find result by paths. This uses the locale-aware
// comparison function on the filenames for sorting in the user's locale.
// Static.
bool CompareFullPath(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
return base::i18n::LocaleAwareCompareFilenames(a.path, b.path);
}
void SortData(std::vector<DirectoryLister::DirectoryListerData>* data,
DirectoryLister::SortType sort_type) {
// Sort the results. See the TODO below (this sort should be removed and we
// should do it from JS).
if (sort_type == DirectoryLister::DATE)
std::sort(data->begin(), data->end(), CompareDate);
else if (sort_type == DirectoryLister::FULL_PATH)
std::sort(data->begin(), data->end(), CompareFullPath);
else if (sort_type == DirectoryLister::ALPHA_DIRS_FIRST)
std::sort(data->begin(), data->end(), CompareAlphaDirsFirst);
else
DCHECK_EQ(DirectoryLister::NO_SORT, sort_type);
}
} // namespace
DirectoryLister::DirectoryLister(const base::FilePath& dir,
DirectoryListerDelegate* delegate)
: core_(new Core(dir, false, ALPHA_DIRS_FIRST, this)),
delegate_(delegate) {
DCHECK(delegate_);
DCHECK(!dir.value().empty());
}
DirectoryLister::DirectoryLister(const base::FilePath& dir,
bool recursive,
SortType sort,
DirectoryListerDelegate* delegate)
: core_(new Core(dir, recursive, sort, this)),
delegate_(delegate) {
DCHECK(delegate_);
DCHECK(!dir.value().empty());
}
DirectoryLister::~DirectoryLister() {
Cancel();
}
bool DirectoryLister::Start() {
return core_->Start();
}
void DirectoryLister::Cancel() {
return core_->Cancel();
}
DirectoryLister::Core::Core(const base::FilePath& dir,
bool recursive,
SortType sort,
DirectoryLister* lister)
: dir_(dir),
recursive_(recursive),
sort_(sort),
lister_(lister) {
DCHECK(lister_);
}
DirectoryLister::Core::~Core() {}
bool DirectoryLister::Core::Start() {
origin_loop_ = base::MessageLoopProxy::current();
return base::WorkerPool::PostTask(
FROM_HERE, base::Bind(&Core::StartInternal, this), true);
}
void DirectoryLister::Core::Cancel() {
lister_ = NULL;
}
void DirectoryLister::Core::StartInternal() {
if (!base::DirectoryExists(dir_)) {
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::OnDone, this, ERR_FILE_NOT_FOUND));
return;
}
int types = base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES;
if (!recursive_)
types |= base::FileEnumerator::INCLUDE_DOT_DOT;
base::FileEnumerator file_enum(dir_, recursive_, types);
base::FilePath path;
std::vector<DirectoryListerData> file_data;
while (lister_ && !(path = file_enum.Next()).empty()) {
DirectoryListerData data;
data.info = file_enum.GetInfo();
data.path = path;
file_data.push_back(data);
/* TODO(brettw) bug 24107: It would be nice to send incremental updates.
We gather them all so they can be sorted, but eventually the sorting
should be done from JS to give more flexibility in the page. When we do
that, we can uncomment this to send incremental updates to the page.
const int kFilesPerEvent = 8;
if (file_data.size() < kFilesPerEvent)
continue;
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::SendData, file_data));
file_data.clear();
*/
}
SortData(&file_data, sort_);
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::SendData, this, file_data));
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::OnDone, this, OK));
}
void DirectoryLister::Core::SendData(
const std::vector<DirectoryLister::DirectoryListerData>& data) {
DCHECK(origin_loop_->BelongsToCurrentThread());
// We need to check for cancellation (indicated by NULL'ing of |lister_|)
// which can happen during each callback.
for (size_t i = 0; lister_ && i < data.size(); ++i)
lister_->OnReceivedData(data[i]);
}
void DirectoryLister::Core::OnDone(int error) {
DCHECK(origin_loop_->BelongsToCurrentThread());
if (lister_)
lister_->OnDone(error);
}
void DirectoryLister::OnReceivedData(const DirectoryListerData& data) {
delegate_->OnListFile(data);
}
void DirectoryLister::OnDone(int error) {
delegate_->OnListDone(error);
}
} // namespace net
| 30.888372 | 78 | 0.680319 |
286753be0bfc3a1dbe446687ed9cd96437c4a631 | 2,645 | cpp | C++ | ogre-network-receiver/CubicSpline.cpp | sevas/ogre-path-interpolation | 828efa8c0e4878ab1ed9b6c410c14b1e337c6cef | [
"WTFPL"
] | 2 | 2019-09-07T03:48:55.000Z | 2020-01-03T06:59:10.000Z | ogre-network-receiver/CubicSpline.cpp | sevas/ogre-path-interpolation | 828efa8c0e4878ab1ed9b6c410c14b1e337c6cef | [
"WTFPL"
] | null | null | null | ogre-network-receiver/CubicSpline.cpp | sevas/ogre-path-interpolation | 828efa8c0e4878ab1ed9b6c410c14b1e337c6cef | [
"WTFPL"
] | null | null | null | #include "precompiled.h"
#include "CubicSpline.h"
#include <OgreMath.h>
//------------------------------------------------------------------------------
CubicSpline::CubicSpline()
:mPoints(4)
,mStartPoint(2)
,mEndPoint(2)
,mHasControlPoints(false)
{
}
//------------------------------------------------------------------------------
Vector3 CubicSpline::evaluate(float _t)
{
assert(_t>=0 && _t<=1);
Vector3 res;
if(mHasControlPoints)
{
res.x = evaluateF(mXVars[0], mXVars[1], mXVars[2], mXVars[3], _t);
res.y = evaluateF(mYVars[0], mYVars[1], mYVars[2], mYVars[3], _t);
res.z = evaluateF(mZVars[0], mZVars[1], mZVars[2], mZVars[3], _t);
}
else
{
res = Vector3::ZERO;
}
return res;
}
//------------------------------------------------------------------------------
float CubicSpline::evaluateF(float _A, float _B, float _C, float _D, float _t)
{
return _A*Math::Pow(_t, 3) + _B*Math::Pow(_t, 2) + _C*_t + _D;
}
//------------------------------------------------------------------------------
void CubicSpline::setStartPoint(const Vector3 &_pos, const Vector3 &_speed)
{
mHasControlPoints = false;
mStartPoint[0] = _pos;
mStartPoint[1] = _speed;
}
//------------------------------------------------------------------------------
void CubicSpline::setEndPoint(const Vector3 &_pos, const Vector3 &_speed)
{
mHasControlPoints = false;
mEndPoint[0] = _pos;
mEndPoint[1] = _speed;
}
//------------------------------------------------------------------------------
void CubicSpline::calcControlPoints()
{
mPoints[0] = mStartPoint[0];
mPoints[1] = mStartPoint[0] + mStartPoint[1];
mPoints[2] = mEndPoint[0] - mEndPoint[1];
mPoints[3] = mEndPoint[0];
mXVars = _getSplineVariables(mPoints[0].x, mPoints[1].x, mPoints[2].x, mPoints[3].x);
mYVars = _getSplineVariables(mPoints[0].y, mPoints[1].y, mPoints[2].y, mPoints[3].y);
mZVars = _getSplineVariables(mPoints[0].z, mPoints[1].z, mPoints[2].z, mPoints[3].z);
mHasControlPoints = true;
}
//------------------------------------------------------------------------------
Vector4 CubicSpline::_getSplineVariables(float _c0, float _c1, float _c2, float _c3)
{
Vector4 res;
res[0] = _c3 - 3*_c2 + 3*_c1 - _c0;
res[1] = 3*_c2 - 6*_c1 + 3*_c0;
res[2] = 3*_c1 - 3*_c0;
res[3] = _c0;
return res;
}
//------------------------------------------------------------------------------ | 34.350649 | 90 | 0.438185 |
286930b7251bfb77d9c4612c785b52db98fecc5d | 506 | cpp | C++ | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018, Oath Inc. Licensed under the terms of the
* Apache License 2.0. See LICENSE file at the project root for terms.
*/
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char **argv) {
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest() );
bool wasSuccessful = runner.run("", false);
return !wasSuccessful;
}
| 31.625 | 87 | 0.741107 |
286a928b8661ddedc4fa3d34e5e5227d5e0e4d76 | 7,310 | cpp | C++ | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* 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 "components/ui_digital_clock.h"
#include <cstdio>
#include "components/ui_view_group.h"
#include "font/ui_font.h"
#include "gfx_utils/graphic_log.h"
#include "securec.h"
namespace OHOS {
UIDigitalClock::UIDigitalClock()
: timeLabels_{0},
displayMode_(DISPLAY_24_HOUR),
leadingZero_(true),
color_(Color::White()),
prevHour_(0),
prevMinute_(0),
prevSecond_(0),
verticalShow_(false)
{
style_ = &(StyleDefault::GetBackgroundTransparentStyle());
}
void UIDigitalClock::InitTimeLabels()
{
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
if (timeLabels_[i] == nullptr) {
timeLabels_[i] = new UILabel;
if (timeLabels_[i] == nullptr) {
GRAPHIC_LOGE("new UILabel fail");
return;
}
timeLabels_[i]->SetLineBreakMode(UILabel::LINE_BREAK_ADAPT);
timeLabels_[i]->SetStyle(STYLE_BACKGROUND_OPA, OPA_TRANSPARENT);
Add(timeLabels_[i]);
}
}
}
void UIDigitalClock::DisplayLeadingZero(bool displayLeadingZero)
{
leadingZero_ = displayLeadingZero;
UpdateClock(false);
}
void UIDigitalClock::SetOpacity(uint8_t opacity)
{
opaScale_ = opacity;
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetStyle(STYLE_TEXT_OPA, opacity);
}
RefreshTime();
}
uint8_t UIDigitalClock::GetOpacity() const
{
return opaScale_;
}
void UIDigitalClock::SetFontId(uint8_t fontId)
{
SetStyle(STYLE_TEXT_FONT, fontId);
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetFontId(fontId);
}
UpdateClock(false);
}
void UIDigitalClock::SetFont(const char* name, uint8_t size)
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetFont(name, size);
}
UpdateClock(false);
}
void UIDigitalClock::SetColor(ColorType color)
{
color_ = color;
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetStyle(STYLE_TEXT_COLOR, color.full);
}
RefreshTime();
}
void UIDigitalClock::TimeElementRefresh()
{
InitTimeLabels();
if (currentHour_ != prevHour_) {
prevHour_ = currentHour_;
timeLabels_[HOUR_ELEMENT]->Invalidate();
}
if (currentMinute_ != prevMinute_) {
prevMinute_ = currentMinute_;
timeLabels_[MINUTE_ELEMENT]->Invalidate();
}
if (currentSecond_ != prevSecond_) {
prevSecond_ = currentSecond_;
timeLabels_[SECOND_ELEMENT]->Invalidate();
}
}
void UIDigitalClock::RefreshTime()
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->Invalidate();
}
}
void UIDigitalClock::UpdateClock(bool clockInit)
{
char buf[TIME_ELEMENT_COUNT][BUFFER_SIZE] = {{0}};
const char* formatWithColon = leadingZero_ ? "%02d:" : "%d:";
const char* formatWithoutColon = leadingZero_ ? "%02d" : "%d";
const char* format = verticalShow_ ? formatWithoutColon : formatWithColon;
const char* formatForMinute = verticalShow_ ? "%02d" : "%02d:";
switch (displayMode_) {
case DISPLAY_24_HOUR_NO_SECONDS: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, "%02d", currentMinute_) < 0) {
return;
}
break;
}
case DISPLAY_12_HOUR_NO_SECONDS: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_ % HALF_DAY_IN_HOUR) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, "%02d", currentMinute_) < 0) {
return;
}
break;
}
case DISPLAY_12_HOUR: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_ % HALF_DAY_IN_HOUR) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, formatForMinute, currentMinute_) < 0) {
return;
}
if (sprintf_s(buf[SECOND_ELEMENT], BUFFER_SIZE, "%02d", currentSecond_) < 0) {
return;
}
break;
}
case DISPLAY_24_HOUR: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, formatForMinute, currentMinute_) < 0) {
return;
}
if (sprintf_s(buf[SECOND_ELEMENT], BUFFER_SIZE, "%02d", currentSecond_) < 0) {
return;
}
break;
}
default: {
break;
}
}
SetTimeLabels(buf);
}
void UIDigitalClock::SetTimeLabels(const char buf[TIME_ELEMENT_COUNT][BUFFER_SIZE])
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetText(buf[i]);
}
SetTimeLabelsPosition();
TimeElementRefresh();
}
void UIDigitalClock::SetHorizontal()
{
InitTimeLabels();
uint16_t totalWidth = timeLabels_[HOUR_ELEMENT]->GetWidth() + timeLabels_[MINUTE_ELEMENT]->GetWidth() +
timeLabels_[SECOND_ELEMENT]->GetWidth();
UITextLanguageAlignment align = timeLabels_[HOUR_ELEMENT]->GetHorAlign();
int16_t x = 0;
Rect rect = GetContentRect();
if (align == TEXT_ALIGNMENT_CENTER) {
x = (rect.GetWidth() >> 1) - (totalWidth >> 1);
} else if (align == TEXT_ALIGNMENT_RIGHT) {
x = rect.GetRight() - totalWidth;
}
timeLabels_[HOUR_ELEMENT]->SetPosition(x, 0);
int16_t width = timeLabels_[HOUR_ELEMENT]->GetWidth();
for (uint8_t i = 1; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetPosition(x + width, 0);
width += timeLabels_[i]->GetWidth();
}
}
void UIDigitalClock::SetTimeLabelsPosition()
{
if (verticalShow_) {
SetVertical();
} else {
SetHorizontal();
}
}
void UIDigitalClock::SetVertical()
{
InitTimeLabels();
int16_t fontHeight = timeLabels_[HOUR_ELEMENT]->GetHeight();
timeLabels_[HOUR_ELEMENT]->SetPosition(0, 0);
int16_t y = fontHeight;
for (uint8_t i = 1; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetPosition(0, y);
y += fontHeight;
}
}
UIDigitalClock::~UIDigitalClock()
{
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
if (timeLabels_[i] != nullptr) {
delete timeLabels_[i];
timeLabels_[i] = nullptr;
}
}
}
} // namespace OHOS
| 29.24 | 107 | 0.61368 |
286c5ecf38d03a1dd8d219ba69cecda5722795ee | 1,415 | cpp | C++ | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
/************************************************************************************************************
* Problem statement : https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
*
* //Solution :
* //Time complexity :
* //Space complexity :
*
************************************************************************************************************/
//Normal Approach : using the library methods
class Solution1
{
public:
vector<int> reverseString(vector<int> inputString)
{
reverse(inputString.begin(), inputString.end());
}
};
//Without library
class Solution
{
public:
void reverseString(vector<char> inputString)
{
for (int i = 0, j = inputString.size() - 1; i < j; i++, j--)
{
char temp = inputString[i];
inputString[i] = inputString[j];
inputString[j] = temp;
}
}
};
int main()
{
char inputString[5] = {'h', 'e', 'l', 'l', 'o'};
int numberOfElement = sizeof(inputString) / sizeof(inputString[0]);
std::vector<char> string(numberOfElement);
memcpy(&string[0], &inputString[0], numberOfElement * sizeof(int));
Solution solution;
solution.reverseString(string);
}
| 26.203704 | 114 | 0.497527 |
286cb47acae02dcb7f8fce48320957ed50ad5f44 | 16,597 | cpp | C++ | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | /**************************************************************************/
/* */
/* WWIV Initialization Utility Version 5 */
/* Copyright (C)1998-2017, WWIV Software Services */
/* */
/* 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. */
/* */
/**************************************************************************/
#define _DEFINE_GLOBALS_
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <memory>
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#endif
#include <locale.h>
#include <sys/stat.h>
#include "local_io/wconstants.h"
#include "core/command_line.h"
#include "core/datafile.h"
#include "core/file.h"
#include "core/inifile.h"
#include "core/log.h"
#include "core/os.h"
#include "core/strings.h"
#include "core/version.cpp"
#include "core/wwivport.h"
#include "wwivconfig/archivers.h"
#include "wwivconfig/autoval.h"
#include "wwivconfig/convert.h"
#include "wwivconfig/editors.h"
#include "wwivconfig/languages.h"
#include "wwivconfig/levels.h"
#include "wwivconfig/menus.h"
#include "wwivconfig/networks.h"
#include "wwivconfig/newinit.h"
#include "wwivconfig/paths.h"
#include "wwivconfig/protocols.h"
#include "wwivconfig/regcode.h"
#include "wwivconfig/subsdirs.h"
#include "wwivconfig/sysop_account.h"
#include "wwivconfig/system_info.h"
#include "wwivconfig/user_editor.h"
#include "wwivconfig/utility.h"
#include "wwivconfig/wwivconfig.h"
#include "wwivconfig/wwivd_ui.h"
#include "sdk/vardec.h"
#include "localui/curses_io.h"
#include "localui/curses_win.h"
#include "localui/input.h"
#include "localui/listbox.h"
#include "localui/stdio_win.h"
#include "localui/ui_win.h"
#include "localui/wwiv_curses.h"
#include "sdk/config.h"
#include "sdk/filenames.h"
#include "sdk/usermanager.h"
using std::string;
using std::vector;
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::strings;
static bool CreateConfigOvr(const string& bbsdir) {
IniFile oini(WWIV_INI, {"WWIV"});
int num_instances = oini.value("NUM_INSTANCES", 4);
std::vector<legacy_configovrrec_424_t> config_ovr_data;
for (int i = 1; i <= num_instances; i++) {
string instance_tag = StringPrintf("WWIV-%u", i);
IniFile ini("wwiv.ini", {instance_tag, "WWIV"});
string temp_directory = ini.value<string>("TEMP_DIRECTORY");
if (temp_directory.empty()) {
LOG(ERROR) << "TEMP_DIRECTORY is not set! Unable to create CONFIG.OVR";
return false;
}
// TEMP_DIRECTORY is defined in wwiv.ini, therefore use it over config.ovr, also
// default the batch_directory to TEMP_DIRECTORY if BATCH_DIRECTORY does not exist.
string batch_directory(ini.value<string>("BATCH_DIRECTORY", temp_directory));
// Replace %n with instance number value.
const auto instance_num_string = std::to_string(i);
StringReplace(&temp_directory, "%n", instance_num_string);
StringReplace(&batch_directory, "%n", instance_num_string);
File::absolute(bbsdir, &temp_directory);
File::absolute(bbsdir, &batch_directory);
File::EnsureTrailingSlash(&temp_directory);
File::EnsureTrailingSlash(&batch_directory);
legacy_configovrrec_424_t r = {};
r.primaryport = 1;
to_char_array(r.batchdir, batch_directory);
to_char_array(r.tempdir, temp_directory);
config_ovr_data.emplace_back(r);
}
DataFile<legacy_configovrrec_424_t> file(CONFIG_OVR, File::modeBinary | File::modeReadWrite |
File::modeCreateFile |
File::modeTruncate);
if (!file) {
LOG(ERROR) << "Unable to open CONFIG.OVR for writing.";
return false;
}
if (!file.WriteVector(config_ovr_data)) {
LOG(ERROR) << "Unable to write to CONFIG.OVR.";
return false;
}
return true;
}
WInitApp::WInitApp() {}
WInitApp::~WInitApp() {
// Don't leak the localIO (also fix the color when the app exits)
delete out;
out = nullptr;
}
int main(int argc, char* argv[]) {
try {
wwiv::core::Logger::Init(argc, argv);
std::unique_ptr<WInitApp> app(new WInitApp());
return app->main(argc, argv);
} catch (const std::exception& e) {
LOG(INFO) << "Fatal exception launching wwivconfig: " << e.what();
}
}
static bool IsUserDeleted(const User& user) { return user.data.inact & inact_deleted; }
static bool CreateSysopAccountIfNeeded(const std::string& bbsdir) {
Config config(bbsdir);
{
UserManager usermanager(config);
auto num_users = usermanager.num_user_records();
for (int n = 1; n <= num_users; n++) {
User u{};
usermanager.readuser(&u, n);
if (!IsUserDeleted(u)) {
return true;
}
}
}
out->Cls(ACS_CKBOARD);
if (!dialog_yn(out->window(), "Would you like to create a sysop account now?")) {
messagebox(out->window(), "You will need to log in locally and manually create one");
return true;
}
create_sysop_account(config);
return true;
}
enum class ShouldContinue { CONTINUE, EXIT };
static ShouldContinue
read_configdat_and_upgrade_datafiles_if_needed(UIWindow* window, const wwiv::sdk::Config& config) {
// Convert 4.2X to 4.3 format if needed.
configrec cfg;
File file(config.config_filename());
if (file.length() != sizeof(configrec)) {
// TODO(rushfan): make a subwindow here but until this clear the altcharset background.
if (!dialog_yn(out->window(), "Upgrade config.dat from 4.x format?")) {
return ShouldContinue::EXIT;
}
window->Bkgd(' ');
convert_config_424_to_430(window, config);
}
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
// Check for 5.2 config
{
static const std::string expected_sig = "WWIV";
if (expected_sig != cfg.header.header.signature) {
// We don't have a 5.2 header, let's convert.
if (!dialog_yn(out->window(), "Upgrade config.dat to 5.2 format?")) {
return ShouldContinue::EXIT;
}
convert_config_to_52(window, config);
{
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
}
}
ensure_latest_5x_config(window, config, cfg);
}
ensure_offsets_are_updated(window, config);
return ShouldContinue::CONTINUE;
}
static void ShowHelp(CommandLine& cmdline) {
std::cout << cmdline.GetHelp() << std::endl;
exit(1);
}
static bool config_offsets_matches_actual(const Config& config) {
File file(config.config_filename());
if (!file.Open(File::modeBinary | File::modeReadWrite)) {
return false;
}
configrec x{};
file.Read(&x, sizeof(configrec));
// update user info data
int16_t userreclen = static_cast<int16_t>(sizeof(userrec));
int16_t waitingoffset = offsetof(userrec, waiting);
int16_t inactoffset = offsetof(userrec, inact);
int16_t sysstatusoffset = offsetof(userrec, sysstatus);
int16_t fuoffset = offsetof(userrec, forwardusr);
int16_t fsoffset = offsetof(userrec, forwardsys);
int16_t fnoffset = offsetof(userrec, net_num);
if (userreclen != x.userreclen || waitingoffset != x.waitingoffset ||
inactoffset != x.inactoffset || sysstatusoffset != x.sysstatusoffset ||
fuoffset != x.fuoffset || fsoffset != x.fsoffset || fnoffset != x.fnoffset) {
return false;
}
return true;
}
bool legacy_4xx_menu(const Config& config, UIWindow* window) {
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"N. Network Configuration", 'N'},
{"U. User Editor", 'U'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'N':
networks(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
return true;
}
int WInitApp::main(int argc, char** argv) {
setlocale(LC_ALL, "");
CommandLine cmdline(argc, argv, "net");
cmdline.AddStandardArgs();
cmdline.set_no_args_allowed(true);
cmdline.add_argument(BooleanCommandLineArgument(
"initialize", "Initialize the datafiles for the 1st time and exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("user_editor", 'U', "Run the user editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("menu_editor", 'M', "Run the menu editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("network_editor", 'N', "Run the network editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("4xx", '4', "Only run editors that work on WWIV 4.xx.", false));
cmdline.add_argument({"menu_dir", "Override the menu directory when using --menu_editor.", ""});
if (!cmdline.Parse() || cmdline.help_requested()) {
ShowHelp(cmdline);
return 0;
}
auto bbsdir = File::EnsureTrailingSlash(cmdline.bbsdir());
const bool forced_initialize = cmdline.barg("initialize");
UIWindow* window;
if (forced_initialize) {
window = new StdioWindow(nullptr, new ColorScheme());
} else {
CursesIO::Init(StringPrintf("WWIV %s%s Configuration Program.", wwiv_version, beta_version));
window = out->window();
out->Cls(ACS_CKBOARD);
window->SetColor(SchemeId::NORMAL);
}
if (forced_initialize && File::Exists(CONFIG_DAT)) {
messagebox(window, "Unable to use --initialize when CONFIG.DAT exists.");
return 1;
}
bool need_to_initialize = !File::Exists(CONFIG_DAT) || forced_initialize;
if (need_to_initialize) {
window->Bkgd(' ');
if (!new_init(window, bbsdir, need_to_initialize)) {
return 2;
}
}
Config config(bbsdir);
bool legacy_4xx_mode = false;
if (cmdline.barg("menu_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
auto menu_dir = config.menudir();
auto menu_dir_arg = cmdline.sarg("menu_dir");
if (!menu_dir_arg.empty()) {
menu_dir = menu_dir_arg;
}
menus(menu_dir);
return 0;
} else if (cmdline.barg("user_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
user_editor(config);
return 0;
} else if (cmdline.barg("network_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
if (!config_offsets_matches_actual(config)) {
return 1;
}
networks(config);
return 0;
} else if (cmdline.barg("4xx")) {
if (!config_offsets_matches_actual(config)) {
return 1;
}
legacy_4xx_mode = true;
}
if (!legacy_4xx_mode &&
read_configdat_and_upgrade_datafiles_if_needed(window, config) ==
ShouldContinue::EXIT) {
legacy_4xx_mode = true;
}
if (legacy_4xx_mode) {
legacy_4xx_menu(config, window);
return 0;
}
CreateConfigOvr(bbsdir);
{
File archiverfile(FilePath(config.datadir(), ARCHIVER_DAT));
if (!archiverfile.Open(File::modeBinary | File::modeReadOnly)) {
create_arcs(window, config.datadir());
}
}
if (forced_initialize) {
return 0;
}
// GP - We can move this up to after "read_status" if the
// wwivconfig --initialize flow should query the user to make an account.
CreateSysopAccountIfNeeded(bbsdir);
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"G. General System Configuration", 'G'},
{"P. System Paths", 'P'},
{"T. External Transfer Protocol Configuration", 'T'},
{"E. External Editor Configuration", 'E'},
{"S. Security Level Configuration", 'S'},
{"V. Auto-Validation Level Configuration", 'V'},
{"A. Archiver Configuration", 'A'},
{"L. Language Configuration", 'L'},
{"M. Menu Editor", 'M'},
{"N. Network Configuration", 'N'},
{"R. Registration Information", 'R'},
{"U. User Editor", 'U'},
{"X. Update Sub/Directory Maximums", 'X'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'G':
sysinfo1(config);
break;
case 'P':
setpaths(config);
break;
case 'T':
extrn_prots(config.datadir());
break;
case 'E':
extrn_editors(config);
break;
case 'S':
sec_levs(config);
break;
case 'V':
autoval_levs(config);
break;
case 'A':
edit_archivers(config);
break;
case 'L':
edit_languages(config);
break;
case 'N':
networks(config);
break;
case 'M':
menus(config.menudir());
break;
case 'R':
edit_registration_code(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case 'X':
up_subs_dirs(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
config.Save();
return 0;
}
| 31.433712 | 105 | 0.607519 |
286ef9f4e191c1ea6fcfc7ba46470f3ba04df768 | 499 | hpp | C++ | tools/converter/include/cli.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 3 | 2019-12-27T01:10:32.000Z | 2021-05-14T08:10:40.000Z | tools/converter/include/cli.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 10 | 2019-07-04T01:40:13.000Z | 2019-10-30T02:38:42.000Z | tools/converter/include/cli.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1 | 2021-01-15T06:28:11.000Z | 2021-01-15T06:28:11.000Z | //
// cli.hpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef CLI_HPP
#define CLI_HPP
#include <iostream>
#include "config.hpp"
#include "cxxopts.hpp"
class Cli {
public:
static void printProjectBanner();
static cxxopts::Options initializeMNNConvertArgs(modelConfig &modelPath, int argc, char **argv);
};
using namespace std;
class CommonKit {
public:
static bool FileIsExist(string path);
};
#endif // CLI_HPP
| 16.633333 | 100 | 0.709419 |
2870ca201c9d033ac2921ff82a4d3509719167a1 | 2,492 | hpp | C++ | api/CPP/fully_connected_grad_input.hpp | liyuming1978/clDNN | 05e19dd2229dc977c2902ec360f3165ecb925b50 | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | api/CPP/fully_connected_grad_input.hpp | liyuming1978/clDNN | 05e19dd2229dc977c2902ec360f3165ecb925b50 | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | api/CPP/fully_connected_grad_input.hpp | liyuming1978/clDNN | 05e19dd2229dc977c2902ec360f3165ecb925b50 | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2016 Intel Corporation
//
// 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.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "../C/fully_connected_grad_input.h"
#include "primitive.hpp"
namespace cldnn
{
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
/// @brief Performs backward fully connected layer (inner product) for input.
struct fully_connected_grad_input : public primitive_base<fully_connected_grad_input, CLDNN_PRIMITIVE_DESC(fully_connected_grad_input)>
{
CLDNN_DECLARE_PRIMITIVE(fully_connected_grad_input)
/// @brief Constructs fully connected layer grad for input.
/// @param id This primitive id.
/// @param input Input gradient primitive id.
/// @param input Input primitive id.
/// @param weights Primitive id containing weights data.
/// @param bias Primitive id containing bias data. Provide empty string if using Relu without bias.
fully_connected_grad_input(
const primitive_id& id,
const primitive_id& input_grad,
const primitive_id& input,
const primitive_id& weights,
const padding& output_padding = padding()
)
: primitive_base(id, { input_grad, input }, output_padding)
, weights(weights)
{
}
/// @brief Constructs a copy from basic C API @CLDNN_PRIMITIVE_DESC{fully_connected_grad_input}
fully_connected_grad_input(const dto* dto)
:primitive_base(dto)
, weights(dto->weights)
{
}
/// @brief Primitive id containing weights data.
primitive_id weights;
protected:
std::vector<std::reference_wrapper<const primitive_id>> get_dependencies() const override
{
return{ weights };
}
void update_dto(dto& dto) const override
{
dto.weights = weights.c_str();
}
};
/// @}
/// @}
/// @}
} | 31.544304 | 135 | 0.668941 |
2871f2f336d29b14efc4e9ac1c634069e3483785 | 16,900 | cpp | C++ | time.cpp | globalnix/deconz-rest-plugin | be847f397df49e595b801356769c64fbbba1ae45 | [
"BSD-3-Clause"
] | null | null | null | time.cpp | globalnix/deconz-rest-plugin | be847f397df49e595b801356769c64fbbba1ae45 | [
"BSD-3-Clause"
] | null | null | null | time.cpp | globalnix/deconz-rest-plugin | be847f397df49e595b801356769c64fbbba1ae45 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T17:54:10.000Z | 2022-03-24T17:54:10.000Z | /*
* time.cpp
*
* Full implementation of Time cluster server.
* Send ZCL attribute response to read request on Time Cluster attributes.
*
* 0x0000 Time / UTC Time seconds from 1/1/2000
* 0x0001 TimeStatus / Master(bit-0)=1, Superseding(bit-3)= 1, MasterZoneDst(bit-2)=1
* 0x0002 TimeZone / offset seconds from UTC
* 0x0003 DstStart / daylight savings time start
* 0x0004 DstEnd / daylight savings time end
* 0x0005 DstShift / daylight savings offset
* 0x0006 StandardTime / StandardTime = Time + TimeZone
* 0x0007 LocalTime / LocalTime = StandardTime (during winter time)
* LocalTime = StandardTime + DstShift (during summer time)
* 0x0008 LastSetTime
* 0x0009 ValidUnilTime
*
*/
#include <QTimeZone>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
void getTime(quint32 *time, qint32 *tz, quint32 *dstStart, quint32 *dstEnd, qint32 *dstShift, quint32 *standardTime, quint32 *localTime, quint8 mode)
{
const QDateTime now = QDateTime::currentDateTimeUtc();
const QDateTime yearStart(QDate(QDate::currentDate().year(), 1, 1), QTime(0, 0), Qt::UTC);
const QTimeZone timeZone(QTimeZone::systemTimeZoneId());
QDateTime epoch;
DBG_Assert(mode == UNIX_EPOCH || mode == J2000_EPOCH);
if (mode == UNIX_EPOCH)
{
epoch = QDateTime(QDate(1970, 1, 1), QTime(0, 0), Qt::UTC);
}
else if (mode == J2000_EPOCH)
{
epoch = QDateTime(QDate(2000, 1, 1), QTime(0, 0), Qt::UTC);;
}
else
{
return;
}
*time = *standardTime = *localTime = epoch.secsTo(now);
*tz = timeZone.offsetFromUtc(yearStart);
if (timeZone.hasTransitions())
{
const QTimeZone::OffsetData dstStartOffsetData = timeZone.nextTransition(yearStart);
const QTimeZone::OffsetData dstEndOffsetData = timeZone.nextTransition(dstStartOffsetData.atUtc);
*dstStart = epoch.secsTo(dstStartOffsetData.atUtc);
*dstEnd = epoch.secsTo(dstEndOffsetData.atUtc);
*dstShift = dstStartOffsetData.daylightTimeOffset;
*standardTime += *tz;
*localTime += *tz + ((*time >= *dstStart && *time <= *dstEnd) ? *dstShift : 0);
}
}
/*! Handle packets related to the ZCL Time cluster.
\param ind the APS level data indication containing the ZCL packet
\param zclFrame the actual ZCL frame which holds the read attribute request
*/
void DeRestPluginPrivate::handleTimeClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
if (zclFrame.commandId() == deCONZ::ZclReadAttributesId)
{
sendTimeClusterResponse(ind, zclFrame);
}
else
{
Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint(), QLatin1String("ZHATime"));
if (!sensor)
{
DBG_Printf(DBG_INFO, "0x%016llX No sensor having time cluster found for endpoint: 0x%02X\n", ind.srcAddress().ext(), ind.srcEndpoint());
return;
}
bool isReadAttr = false;
bool isReporting = false;
bool isWriteResponse = false;
if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesResponseId)
{
isReadAttr = true;
}
if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId)
{
isReporting = true;
}
if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclWriteAttributesResponseId)
{
isWriteResponse = true;
}
// Read ZCL reporting and ZCL Read Attributes Response
if (isReadAttr || isReporting)
{
const NodeValue::UpdateType updateType = isReadAttr ? NodeValue::UpdateByZclRead : NodeValue::UpdateByZclReport;
bool stateUpdated = false;
const QDateTime epoch = QDateTime(QDate(2000, 1, 1), QTime(0, 0), Qt::UTC);
QDataStream stream(zclFrame.payload());
stream.setByteOrder(QDataStream::LittleEndian);
while (!stream.atEnd())
{
quint16 attrId;
quint8 attrTypeId;
stream >> attrId;
if (isReadAttr)
{
quint8 status;
stream >> status; // Read Attribute Response status
if (status != deCONZ::ZclSuccessStatus)
{
continue;
}
}
stream >> attrTypeId;
deCONZ::ZclAttribute attr(attrId, attrTypeId, QLatin1String(""), deCONZ::ZclRead, false);
if (!attr.readFromStream(stream))
{
continue;
}
switch (attrId)
{
case 0x0000: // Time (utc, in UTC)
{
QDateTime time = epoch.addSecs(attr.numericValue().u32);
ResourceItem *item = sensor->item(RStateUtc);
if (item && item->toVariant().toDateTime().toMSecsSinceEpoch() != time.toMSecsSinceEpoch())
{
item->setValue(time);
enqueueEvent(Event(RSensors, RStateUtc, sensor->id(), item));
stateUpdated = true;
}
const qint32 drift = QDateTime::currentDateTimeUtc().secsTo(time);
DBG_Printf(DBG_INFO, " >>> %s sensor %s: drift %d\n", qPrintable(sensor->type()), qPrintable(sensor->name()), drift);
if (drift < -10 || drift > 10)
{
DBG_Printf(DBG_INFO, " >>> %s sensor %s: drift: %d: set WRITE_TIME\n", qPrintable(sensor->type()), qPrintable(sensor->name()), drift);
sensor->setNextReadTime(WRITE_TIME, queryTime);
sensor->setLastRead(WRITE_TIME, idleTotalCounter);
sensor->enableRead(WRITE_TIME);
queryTime = queryTime.addSecs(1);
}
else
{
DBG_Printf(DBG_INFO, " >>> %s sensor %s: NO CONSIDERABLE TIME DRIFT\n", qPrintable(sensor->type()), qPrintable(sensor->name()));
}
sensor->setZclValue(updateType, ind.srcEndpoint(), TIME_CLUSTER_ID, attrId, attr.numericValue());
}
break;
case 0x0007: // Local Time (u32, in local time)
{
QDateTime time = epoch.addSecs(attr.numericValue().u32 - QDateTime::currentDateTime().offsetFromUtc());
ResourceItem *item = sensor->item(RStateLocaltime);
if (item && item->toVariant().toDateTime().toMSecsSinceEpoch() != time.toMSecsSinceEpoch())
{
item->setValue(time);
enqueueEvent(Event(RSensors, RStateLocaltime, sensor->id(), item));
stateUpdated = true;
}
sensor->setZclValue(updateType, ind.srcEndpoint(), TIME_CLUSTER_ID, attrId, attr.numericValue());
}
break;
case 0x0008: // Last set time (utc, in UTC)
{
QDateTime time = epoch.addSecs(attr.numericValue().u32);
ResourceItem *item = sensor->item(RStateLastSet);
if (item && item->toVariant().toDateTime().toMSecsSinceEpoch() != time.toMSecsSinceEpoch())
{
item->setValue(time);
enqueueEvent(Event(RSensors, RStateLastSet, sensor->id(), item));
stateUpdated = true;
}
sensor->setZclValue(updateType, ind.srcEndpoint(), TIME_CLUSTER_ID, attrId, attr.numericValue());
}
break;
default:
break;
}
}
if (stateUpdated)
{
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(&*sensor);
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
}
// ZCL Write Attributes Response
if (isWriteResponse)
{
DBG_Printf(DBG_INFO, " >>> %s sensor %s: set READ_TIME from handleTimeClusterIndication()\n", qPrintable(sensor->type()), qPrintable(sensor->name()));
sensor->setNextReadTime(READ_TIME, queryTime);
sensor->setLastRead(READ_TIME, idleTotalCounter);
sensor->enableRead(READ_TIME);
queryTime = queryTime.addSecs(1);
}
}
}
/*! Sends read attributes response to Time client.
\param ind the APS level data indication containing the ZCL packet
\param zclFrame the actual ZCL frame which holds the read attributes request
*/
void DeRestPluginPrivate::sendTimeClusterResponse(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
deCONZ::ApsDataRequest req;
deCONZ::ZclFrame outZclFrame;
req.setProfileId(ind.profileId());
req.setClusterId(ind.clusterId());
req.setDstAddressMode(ind.srcAddressMode());
req.dstAddress() = ind.srcAddress();
req.setDstEndpoint(ind.srcEndpoint());
req.setSrcEndpoint(endpoint());
outZclFrame.setSequenceNumber(zclFrame.sequenceNumber());
outZclFrame.setCommandId(deCONZ::ZclReadAttributesResponseId);
outZclFrame.setFrameControl(deCONZ::ZclFCProfileCommand |
deCONZ::ZclFCDirectionServerToClient |
deCONZ::ZclFCDisableDefaultResponse);
quint32 time_now = 0xFFFFFFFF; // id 0x0000 Time
qint8 time_status = 0x0D; // id 0x0001 TimeStatus Master|MasterZoneDst|Superseding
qint32 time_zone = 0xFFFFFFFF; // id 0x0002 TimeZone
quint32 time_dst_start = 0xFFFFFFFF; // id 0x0003 DstStart
quint32 time_dst_end = 0xFFFFFFFF; // id 0x0004 DstEnd
qint32 time_dst_shift = 0xFFFFFFFF; // id 0x0005 DstShift
quint32 time_std_time = 0xFFFFFFFF; // id 0x0006 StandardTime
quint32 time_local_time = 0xFFFFFFFF; // id 0x0007 LocalTime
quint32 time_valid_until_time = 0xFFFFFFFF; // id 0x0009 ValidUntilTime
getTime(&time_now, &time_zone, &time_dst_start, &time_dst_end, &time_dst_shift, &time_std_time, &time_local_time, J2000_EPOCH);
time_valid_until_time = time_now + (3600 * 24 * 30 * 12);
{ // payload
QDataStream stream(&outZclFrame.payload(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
QDataStream instream(zclFrame.payload());
instream.setByteOrder(QDataStream::LittleEndian);
quint8 code = 0x00; // success
quint16 attr;
while (!instream.atEnd())
{
instream >> attr;
stream << attr;
switch(attr)
{
case 0x0000:
stream << code;
stream << (quint8) deCONZ::ZclUtcTime;
stream << time_now;
break;
case 0x0001:
stream << code;
stream << (quint8) deCONZ::Zcl8BitBitMap;
stream << time_status;
break;
case 0x0002:
stream << code;
stream << (quint8) deCONZ::Zcl32BitInt;
stream << time_zone;
break;
case 0x0003:
stream << code;
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_dst_start;
break;
case 0x0004:
stream << code;
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_dst_end;
break;
case 0x0005:
stream << code;
stream << (quint8) deCONZ::Zcl32BitInt;
stream << time_dst_shift;
break;
case 0x0006:
stream << code;
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_std_time;
break;
case 0x0007:
stream << code;
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_local_time;
break;
case 0x0008:
stream << code;
stream << (quint8) deCONZ::ZclUtcTime;
stream << time_now;
break;
case 0x0009:
stream << code;
stream << (quint8) deCONZ::ZclUtcTime;
stream << time_valid_until_time;
break;
default:
{
stream << (quint8) 0x86; // unsupported_attribute
}
break;
}
}
}
{ // ZCL frame
QDataStream stream(&req.asdu(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
outZclFrame.writeToStream(stream);
}
if (apsCtrlWrapper.apsdeDataRequest(req) != deCONZ::Success)
{
DBG_Printf(DBG_INFO, "Time failed to send reponse\n");
}
}
/*! Get all available timezone identifiers.
*/
QVariantList DeRestPluginPrivate::getTimezones()
{
QVariantList list;
const auto tzs = QTimeZone::availableTimeZoneIds();
for (const QByteArray &tz : tzs)
{
list.append(tz);
}
return list;
}
/*! Sync a sensor's on-device real-time clock.
* \param sensor the ZHATime sensor
*/
bool DeRestPluginPrivate::addTaskSyncTime(Sensor *sensor)
{
if (!sensor || !sensor->isAvailable())
{
return false;
}
TaskItem task;
task.taskType = TaskSyncTime;
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
task.req.dstAddress() = sensor->address();
task.req.setClusterId(TIME_CLUSTER_ID);
task.req.setProfileId(HA_PROFILE_ID);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.zclFrame.setSequenceNumber(zclSeq++);
task.zclFrame.setCommandId(deCONZ::ZclWriteAttributesId);
task.zclFrame.setFrameControl(deCONZ::ZclFCProfileCommand |
deCONZ::ZclFCDirectionClientToServer |
deCONZ::ZclFCDisableDefaultResponse);
quint32 time_now = 0xFFFFFFFF; // id 0x0000 Time
qint8 time_status = 0x02; // id 0x0001 TimeStatus Synchronized
qint32 time_zone = 0xFFFFFFFF; // id 0x0002 TimeZone
quint32 time_dst_start = 0xFFFFFFFF; // id 0x0003 DstStart
quint32 time_dst_end = 0xFFFFFFFF; // id 0x0004 DstEnd
qint32 time_dst_shift = 0xFFFFFFFF; // id 0x0005 DstShift
quint32 time_std_time = 0xFFFFFFFF; // id 0x0006 StandardTime
quint32 time_local_time = 0xFFFFFFFF; // id 0x0007 LocalTime
quint32 time_valid_until_time = 0xFFFFFFFF; // id 0x0009 ValidUntilTime
getTime(&time_now, &time_zone, &time_dst_start, &time_dst_end, &time_dst_shift, &time_std_time, &time_local_time, J2000_EPOCH);
time_valid_until_time = time_now + (3600 * 24);
QDataStream stream(&task.zclFrame.payload(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
stream << (quint16) 0x0000; // Time
stream << (quint8) deCONZ::ZclUtcTime;
stream << time_now;
stream << (quint16) 0x0001; // Time Status
stream << (quint8) deCONZ::Zcl8BitBitMap;
stream << time_status;
stream << (quint16) 0x0002; // Time Zone
stream << (quint8) deCONZ::Zcl32BitInt;
stream << time_zone;
stream << (quint16) 0x0003; // Dst Start
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_dst_start;
stream << (quint16) 0x0004; // Dst End
stream << (quint8) deCONZ::Zcl32BitUint;
stream << time_dst_end;
stream << (quint16) 0x0005; // Dst Shift
stream << (quint8) deCONZ::Zcl32BitInt;
stream << time_dst_shift;
stream << (quint16) 0x0009; // Valid Until Time
stream << (quint8) deCONZ::ZclUtcTime;
stream << time_valid_until_time;
{ // ZCL frame
task.req.asdu().clear(); // cleanup old request data if there is any
QDataStream stream(&task.req.asdu(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
task.zclFrame.writeToStream(stream);
}
return addTask(task);
}
| 37.22467 | 163 | 0.574911 |
287383cba67d98a84142fed9f734d6bae19a47fa | 2,432 | hpp | C++ | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
namespace android::os
{
class Handler;
}
namespace android::os
{
class ParcelFileDescriptor;
}
namespace android::os
{
class ProxyFileDescriptorCallback;
}
namespace android::os::storage
{
class OnObbStateChangeListener;
}
namespace android::os::storage
{
class StorageVolume;
}
namespace java::io
{
class File;
}
namespace java::io
{
class FileDescriptor;
}
class JString;
namespace java::util
{
class UUID;
}
namespace android::os::storage
{
class StorageManager : public JObject
{
public:
// Fields
static JString ACTION_MANAGE_STORAGE();
static JString EXTRA_REQUESTED_BYTES();
static JString EXTRA_UUID();
static java::util::UUID UUID_DEFAULT();
// QJniObject forward
template<typename ...Ts> explicit StorageManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
StorageManager(QJniObject obj);
// Constructors
// Methods
void allocateBytes(java::io::FileDescriptor arg0, jlong arg1) const;
void allocateBytes(java::util::UUID arg0, jlong arg1) const;
jlong getAllocatableBytes(java::util::UUID arg0) const;
jlong getCacheQuotaBytes(java::util::UUID arg0) const;
jlong getCacheSizeBytes(java::util::UUID arg0) const;
JString getMountedObbPath(JString arg0) const;
android::os::storage::StorageVolume getPrimaryStorageVolume() const;
android::os::storage::StorageVolume getStorageVolume(java::io::File arg0) const;
JObject getStorageVolumes() const;
java::util::UUID getUuidForPath(java::io::File arg0) const;
jboolean isAllocationSupported(java::io::FileDescriptor arg0) const;
jboolean isCacheBehaviorGroup(java::io::File arg0) const;
jboolean isCacheBehaviorTombstone(java::io::File arg0) const;
jboolean isEncrypted(java::io::File arg0) const;
jboolean isObbMounted(JString arg0) const;
jboolean mountObb(JString arg0, JString arg1, android::os::storage::OnObbStateChangeListener arg2) const;
android::os::ParcelFileDescriptor openProxyFileDescriptor(jint arg0, android::os::ProxyFileDescriptorCallback arg1, android::os::Handler arg2) const;
void setCacheBehaviorGroup(java::io::File arg0, jboolean arg1) const;
void setCacheBehaviorTombstone(java::io::File arg0, jboolean arg1) const;
jboolean unmountObb(JString arg0, jboolean arg1, android::os::storage::OnObbStateChangeListener arg2) const;
};
} // namespace android::os::storage
| 30.4 | 155 | 0.759457 |
2874ba54b9cc00fb38738fe05b1f3ff4d4663b63 | 2,458 | hpp | C++ | include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp | mfkiwl/hipSYCL | baf07483f5f5061b4c5ae73c8ddb0c83786dca3c | [
"BSD-2-Clause"
] | null | null | null | include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp | mfkiwl/hipSYCL | baf07483f5f5061b4c5ae73c8ddb0c83786dca3c | [
"BSD-2-Clause"
] | null | null | null | include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp | mfkiwl/hipSYCL | baf07483f5f5061b4c5ae73c8ddb0c83786dca3c | [
"BSD-2-Clause"
] | null | null | null | /*
* This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP
*
* Copyright (c) 2021 Aksel Alpay and contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HIPSYCL_LOOPSPARALLELMARKER_HPP
#define HIPSYCL_LOOPSPARALLELMARKER_HPP
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
namespace hipsycl {
namespace compiler {
// marks the wi-loops as parallel (vectorizable) and enables vectorization.
class LoopsParallelMarkerPassLegacy : public llvm::FunctionPass {
public:
static char ID;
explicit LoopsParallelMarkerPassLegacy() : llvm::FunctionPass(ID) {}
llvm::StringRef getPassName() const override { return "hipSYCL loop parallel marking pass"; }
void getAnalysisUsage(llvm::AnalysisUsage &AU) const override;
bool runOnFunction(llvm::Function &L) override;
};
class LoopsParallelMarkerPass : public llvm::PassInfoMixin<LoopsParallelMarkerPass> {
public:
explicit LoopsParallelMarkerPass() {}
llvm::PreservedAnalyses run(llvm::Function &F, llvm::FunctionAnalysisManager &AM);
static bool isRequired() { return false; }
};
} // namespace compiler
} // namespace hipsycl
#endif // HIPSYCL_LOOPSPARALLELMARKER_HPP
| 37.815385 | 95 | 0.772986 |
2875d539af4ea6d77cd798d56a8caaa28fc4a3f2 | 878 | cpp | C++ | routing/junction_visitor.cpp | swaitw/organicmaps | ab34d4d405ed22a5af94afa932b841b9ee6f6fd1 | [
"Apache-2.0"
] | null | null | null | routing/junction_visitor.cpp | swaitw/organicmaps | ab34d4d405ed22a5af94afa932b841b9ee6f6fd1 | [
"Apache-2.0"
] | null | null | null | routing/junction_visitor.cpp | swaitw/organicmaps | ab34d4d405ed22a5af94afa932b841b9ee6f6fd1 | [
"Apache-2.0"
] | null | null | null | #include "junction_visitor.hpp"
#include "routing/joint_segment.hpp"
#include "routing/route_weight.hpp"
#include "base/logging.hpp"
namespace routing
{
#ifdef DEBUG
void DebugRoutingState(JointSegment const & vertex, std::optional<JointSegment> const & parent,
RouteWeight const & heuristic, RouteWeight const & distance)
{
// 1. Dump current processing vertex.
// std::cout << DebugPrint(vertex);
// std::cout << std::setprecision(8) << "; H = " << heuristic << "; D = " << distance;
// 2. Dump parent vertex.
// std::cout << "; P = " << (parent ? DebugPrint(*parent) : std::string("NO"));
// std::cout << std::endl;
// 3. Set breakpoint on a specific vertex.
// if (vertex.GetMwmId() == 706 && vertex.GetFeatureId() == 147648 &&
// vertex.GetEndSegmentId() == 75)
// {
// int noop = 0;
// }
}
#endif
} // namespace routing
| 25.823529 | 95 | 0.626424 |
2879a3fc1b975c2fbc4973a52cb65ff5dda06173 | 2,952 | cpp | C++ | framework/src/media/MediaWorker.cpp | akosthekiss/TizenRT | c9bae662fdf3dbbfbd37560c85f71afe1461b1f0 | [
"Apache-2.0"
] | null | null | null | framework/src/media/MediaWorker.cpp | akosthekiss/TizenRT | c9bae662fdf3dbbfbd37560c85f71afe1461b1f0 | [
"Apache-2.0"
] | null | null | null | framework/src/media/MediaWorker.cpp | akosthekiss/TizenRT | c9bae662fdf3dbbfbd37560c85f71afe1461b1f0 | [
"Apache-2.0"
] | null | null | null | /* ****************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* 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 <debug.h>
#include <sched.h>
#include "MediaWorker.h"
namespace media {
MediaWorker::MediaWorker() :
mStacksize(PTHREAD_STACK_DEFAULT),
mPriority(100),
mThreadName("MediaWorker"),
mIsRunning(false),
mRefCnt(0),
mWorkerThread(0)
{
medvdbg("MediaWorker::MediaWorker()\n");
}
MediaWorker::~MediaWorker()
{
medvdbg("MediaWorker::~MediaWorker()\n");
}
void MediaWorker::startWorker()
{
std::unique_lock<std::mutex> lock(mRefMtx);
++mRefCnt;
medvdbg("%s::startWorker() - increase RefCnt : %d\n", mThreadName, mRefCnt);
if (mRefCnt == 1) {
int ret;
struct sched_param sparam;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, mStacksize);
sparam.sched_priority = mPriority;
pthread_attr_setschedparam(&attr, &sparam);
mIsRunning = true;
ret = pthread_create(&mWorkerThread, &attr, static_cast<pthread_startroutine_t>(MediaWorker::mediaLooper), this);
if (ret != OK) {
medvdbg("Fail to create worker thread, return value : %d\n", ret);
--mRefCnt;
mIsRunning = false;
return;
}
pthread_setname_np(mWorkerThread, mThreadName);
}
}
void MediaWorker::stopWorker()
{
std::unique_lock<std::mutex> lock(mRefMtx);
if (mRefCnt > 0) {
--mRefCnt;
}
medvdbg("%s::stopWorker() - decrease RefCnt : %d\n", mThreadName, mRefCnt);
if (mRefCnt <= 0) {
std::atomic<bool> &refBool = mIsRunning;
mWorkerQueue.enQueue([&refBool]() {
refBool = false;
});
pthread_join(mWorkerThread, NULL);
medvdbg("%s::stopWorker() - mWorkerthread exited\n", mThreadName);
}
}
std::function<void()> MediaWorker::deQueue()
{
return mWorkerQueue.deQueue();
}
bool MediaWorker::processLoop()
{
return false;
}
void *MediaWorker::mediaLooper(void *arg)
{
auto worker = static_cast<MediaWorker *>(arg);
medvdbg("MediaWorker : mediaLooper\n");
while (worker->mIsRunning) {
while (worker->processLoop() && worker->mWorkerQueue.isEmpty());
std::function<void()> run = worker->deQueue();
medvdbg("MediaWorker : deQueue\n");
if (run != nullptr) {
run();
}
}
return NULL;
}
bool MediaWorker::isAlive()
{
std::unique_lock<std::mutex> lock(mRefMtx);
return mRefCnt == 0 ? false : true;
}
} // namespace media
| 25.669565 | 115 | 0.670393 |
287a82b966168a85726b83082e51688a7df03935 | 6,669 | cpp | C++ | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | 1 | 2021-03-30T06:28:32.000Z | 2021-03-30T06:28:32.000Z | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////
// Copyright(c) 2016, Lin Koon Wing Macgyver, macgyvercct@yahoo.com.hk //
// //
// Author : Mac Lin //
// Module : Magnum Engine v1.0.0 //
// Date : 14/Jun/2016 //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "Audio.h"
#include "AudioSourceBase.h"
#include "fmod.hpp"
#include "fmod_errors.h"
using namespace Magnum;
AudioSourceBase::AudioSourceBase(Component::Owner &owner_)
: AudioComponent(owner_)
, channelHandle(0)
, paused(false)
, muteEnabled(false)
, bypassEffectsEnabled(false)
, loopEnabled(false)
, priority(128)
, volume(1)
, pitch(1)
, dopplerLevel(1)
, volumeDecayMode(LogorithmRollOff)
, minDistance(1)
, panLevel(1)
, spread(0)
, maxDistance(500)
{
Audio::Manager::instance().audioSources.push() = this;
}
AudioSourceBase::~AudioSourceBase()
{
int idx = Audio::Manager::instance().audioSources.search(this);
if(idx>=0)
{
Audio::Manager::instance().audioSources.remove(idx);
}
}
void AudioSourceBase::stop()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
if(channel)
{
FMOD_RESULT result;
result = channel->stop();
channel = 0;
}
}
void AudioSourceBase::pause()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = true;
if(channel)
channel->setPaused(true);
}
void AudioSourceBase::resume()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = false;
if(channel)
channel->setPaused(false);
}
void AudioSourceBase::setMuteEnable(bool muteEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
muteEnabled = muteEnable_;
if(channel)
{
channel->setMute(muteEnabled);
}
}
void AudioSourceBase::setBypassEffectsEnable(bool bypassEffectsEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
bypassEffectsEnabled = bypassEffectsEnable_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::setLoopEnable(bool loopEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
loopEnabled = loopEnable_;
if(channel)
{
if(loopEnable_)
{
//result = channel->setMode(FMOD_LOOP_NORMAL);
result = channel->setLoopCount(-1);
}
else
{
//result = channel->setMode(FMOD_LOOP_OFF);
result = channel->setLoopCount(0);
}
}
}
void AudioSourceBase::setPriority(int priority_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
priority = priority_;
if(channel)
{
channel->setPriority(priority);
}
}
void AudioSourceBase::setVolume(float volume_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volume = volume_;
if(channel)
{
channel->setVolume(volume);
}
}
void AudioSourceBase::setPitch(float pitch_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
pitch = pitch_;
if(channel)
{
FMOD::Sound *sound;
result = channel->getCurrentSound(&sound);
if(sound)
{
float frequency;
sound->getDefaults(&frequency, 0, 0, 0);
channel->setFrequency(frequency * pitch);
}
}
}
void AudioSourceBase::set3DDopplerLevel(float dopplerLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
dopplerLevel = dopplerLevel_;
if(channel)
{
channel->set3DDopplerLevel(dopplerLevel_);
}
}
void AudioSourceBase::set3DVolumeDecayMode(AudioSourceBase::DecayMode volumeDecayMode_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volumeDecayMode = volumeDecayMode_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::set3DMinDistance(float minDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
minDistance = minDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
void AudioSourceBase::set3DPanLevel(float panLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
panLevel = panLevel_;
if(channel)
{
channel->set3DPanLevel(panLevel);
}
}
void AudioSourceBase::set3DSpread(float spread_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
spread = spread_;
if(channel)
{
channel->set3DSpread(spread);
}
}
void AudioSourceBase::set3DMaxDistance(float maxDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
maxDistance = maxDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
bool AudioSourceBase::isPaused() const
{
return paused;
}
bool AudioSourceBase::isMuteEnabled() const
{
return muteEnabled;
}
bool AudioSourceBase::isBypassEffectsEnabled() const
{
return bypassEffectsEnabled;
}
bool AudioSourceBase::isLoopEnabled() const
{
return loopEnabled;
}
int AudioSourceBase::getPriority() const
{
return priority;
}
float AudioSourceBase::getVolume() const
{
return volume;
}
float AudioSourceBase::getPitch() const
{
return pitch;
}
float AudioSourceBase::get3DDopplerLevel() const
{
return dopplerLevel;
}
AudioSourceBase::DecayMode AudioSourceBase::get3DVolumeDecayMode() const
{
return volumeDecayMode;
}
float AudioSourceBase::get3DMinDistance() const
{
return minDistance;
}
float AudioSourceBase::get3DPanLevel() const
{
return panLevel;
}
float AudioSourceBase::get3DSpread() const
{
return spread;
}
float AudioSourceBase::get3DMaxDistance() const
{
return maxDistance;
}
void *AudioSourceBase::getChannelHandle()
{
return channelHandle;
} | 20.027027 | 87 | 0.690508 |
287b22e519dd780eb231663c37e9b63ca68a8796 | 753 | cpp | C++ | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | #include "light.hpp"
#include "../util/nm_math.hpp"
#include "../system/renderer.hpp"
Light::Light(
Scene *scene, Renderer *renderer, glm::vec3 position, glm::vec3 color
) :
SceneObject(scene, renderer, position), color(color)
{}
void Light::render(bool debug_mode)
{
SceneObject::render(debug_mode);
renderer->render_default(
PRIMITIVE_SPHERE,
color,
glm::scale(
glm::translate(
glm::identity<glm::mat4>(),
position),
glm::vec3(1.f / SCALE)));
}
bool Light::hit(float *t, glm::vec3 origin, glm::vec3 direction)
{
return nm_math::ray_sphere(t, origin, direction, position, 1.f / SCALE);
} | 25.965517 | 77 | 0.564409 |
287d5513210df00735b4bdf41df40e8f8c8b77b1 | 1,399 | cpp | C++ | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | #include "iostream"
#include "stdio.h"
#include "string"
#include "string.h"
#include "algorithm"
#include "math.h"
#include "vector"
#include "map"
#include "queue"
#include "stack"
#include "deque"
#include "set"
using namespace std;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int inf = 1e9;
#define DFS_WHITE -1 // UNVISITED
#define DFS_BLACK 1 // EXPLORED
#define DFS_GRAY 2 // VISTED BUT NOT EXPLORED
vector<vii> AdjList;
int V, E, u, v, s;
void graphUndirected(){
scanf("%d %d", &V, &E);
AdjList.assign(V + 4, vii());
for (int i = 0; i < E; i++) {
scanf("%d %d", &u, &v);
AdjList[u].push_back(ii(v, 0));
AdjList[v].push_back(ii(u, 0));
}
}
vi p;
void printPath(int u) {
if (u == s) { printf("%d", u); return; }
printPath(p[u]);
printf(" %d", u);
}
void bfs(int s){
vi d(V + 4, inf); d[s] = 0;
queue<int> q; q.push(s);
p.assign(V + 4, -1);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int j = 0; j < (int)AdjList[u].size(); j++) {
ii v = AdjList[u][j];
if (d[v.first] == inf) {
d[v.first] = d[u] + 1;
p[v.first] = u;
q.push(v.first);
}
}
}
}
int main(){
graphUndirected();
s = 5, bfs(s);
printPath(7);
printf("\n");
return 0;
}
| 20.573529 | 58 | 0.50965 |
287f40965278d62cc02152fb361085318976bba3 | 26,955 | hpp | C++ | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | 8 | 2020-07-21T01:30:35.000Z | 2022-03-09T15:51:14.000Z | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | 2 | 2022-01-24T20:51:46.000Z | 2022-03-16T23:08:40.000Z | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | null | null | null | // #include <stdexcept>
#include "barray-bones.hpp"
#ifndef BARRY_BARRAY_MEAT_HPP
#define BARRY_BARRAY_MEAT_HPP
#define BARRAY_TYPE() BArray<Cell_Type, Data_Type>
#define BARRAY_TEMPLATE_ARGS() <typename Cell_Type, typename Data_Type>
#define BARRAY_TEMPLATE(a,b) \
template BARRAY_TEMPLATE_ARGS() inline a BARRAY_TYPE()::b
#define ROW(a) this->el_ij[a]
#define COL(a) this->el_ji[a]
template<typename Cell_Type, typename Data_Type>
Cell<Cell_Type> BArray<Cell_Type,Data_Type>::Cell_default = Cell<Cell_Type>();
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
const std::vector< Cell_Type > & value,
bool add
) {
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
bool empty = this->is_empty(source[i], target[i], true);
if (add && !empty) {
ROW(source[i])[target[i]].add(value[i]);
continue;
}
if (!empty)
throw std::logic_error("The value already exists. Use 'add = true'.");
this->insert_cell(source[i], target[i], value[i], false, false);
}
return;
}
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
bool add
) {
std::vector< Cell_Type > value(source.size(), (Cell_Type) 1.0);
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
if ((source[i] >= N_) | (target[i] >= M_))
throw std::range_error("Either source or target point to an element outside of the range by (N,M).");
// Checking if it exists
auto search = ROW(source[i]).find(target[i]);
if (search != ROW(source[i]).end()) {
if (!add)
throw std::logic_error("The value already exists. Use 'add = true'.");
// Increasing the value (this will automatically update the
// other value)
ROW(source[i])[target[i]].add(value[i]);
continue;
}
// Adding the value and creating a pointer to it
ROW(source[i]).emplace(
std::pair<uint, Cell< Cell_Type> >(
target[i],
Cell< Cell_Type >(value[i], visited)
)
);
COL(target[i]).emplace(
source[i],
&ROW(source[i])[target[i]]
);
NCells++;
}
return;
}
BARRAY_TEMPLATE(,BArray) (
const BArray<Cell_Type,Data_Type> & Array_,
bool copy_data
) : N(Array_.N), M(Array_.M)
{
// Dimensions
// el_ij.resize(N);
// el_ji.resize(M);
std::copy(Array_.el_ij.begin(), Array_.el_ij.end(), std::back_inserter(el_ij));
std::copy(Array_.el_ji.begin(), Array_.el_ji.end(), std::back_inserter(el_ji));
// Taking care of the pointers
for (uint i = 0u; i < N; ++i)
{
for (auto& r: row(i, false))
COL(r.first)[i] = &ROW(i)[r.first];
}
this->NCells = Array_.NCells;
this->visited = Array_.visited;
// Data
if (Array_.data != nullptr)
{
if (copy_data)
{
data = new Data_Type(* Array_.data );
delete_data = true;
} else {
data = Array_.data;
delete_data = false;
}
}
return;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
const BArray<Cell_Type,Data_Type> & Array_
) {
// Clearing
if (this != &Array_)
{
this->clear(true);
this->resize(Array_.N, Array_.M);
// Entries
for (uint i = 0u; i < N; ++i)
{
if (Array_.nnozero() == nnozero())
break;
for (auto& r : Array_.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (Array_.data != nullptr)
{
data = new Data_Type(*Array_.data);
delete_data = true;
}
}
return *this;
}
BARRAY_TEMPLATE(,BArray) (
BARRAY_TYPE() && x
) noexcept :
N(0u), M(0u), NCells(0u),
data(nullptr),
delete_data(x.delete_data)
{
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Managing data
if (x.data != nullptr)
{
if (x.delete_data)
{
data = new Data_Type(*x.data);
delete_data = true;
} else {
data = x.data;
delete_data = false;
}
}
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
BARRAY_TYPE() && x
) noexcept {
// Clearing
if (this != &x) {
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (x.data != nullptr)
{
data = new Data_Type( *x.data );
delete_data = true;
}
// x.data = nullptr;
// x.delete_data = false;
}
return *this;
}
BARRAY_TEMPLATE(bool, operator==) (
const BARRAY_TYPE() & Array_
) {
// Dimension and number of cells used
if ((N != Array_.nrow()) | (M != Array_.ncol()) | (NCells != Array_.nnozero()))
return false;
// One holds, and the other doesn't.
if ((!data & Array_.data) | (data & !Array_.data))
return false;
if (this->el_ij != Array_.el_ij)
return false;
return true;
}
BARRAY_TEMPLATE(,~BArray) () {
if (delete_data && (data != nullptr))
delete data;
return;
}
BARRAY_TEMPLATE(void, set_data) (
Data_Type * data_, bool delete_data_
) {
if ((data != nullptr) && delete_data)
delete data;
data = data_;
delete_data = delete_data_;
return;
}
BARRAY_TEMPLATE(Data_Type *, D) ()
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline const Data_Type * BArray<Cell_Type,Data_Type>::D() const
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline void BArray<Cell_Type,Data_Type>::flush_data()
{
if (delete_data)
{
delete data;
delete_data = false;
}
data = nullptr;
return;
}
BARRAY_TEMPLATE(void, out_of_range) (
uint i,
uint j
) const {
if (i >= N)
throw std::range_error("The row is out of range.");
else if (j >= M)
throw std::range_error("The column is out of range.");
return;
}
BARRAY_TEMPLATE(Cell_Type, get_cell) (
uint i,
uint j,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i,j);
if (ROW(i).size() == 0u)
return (Cell_Type) 0.0;
// If it is not empty, then find and return
auto search = ROW(i).find(j);
if (search != ROW(i).end())
return search->second.value;
// This is if it is empty
return (Cell_Type) 0.0;
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_row_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
std::vector< Cell_Type > ans(ncol(), (Cell_Type) false);
for (const auto & iter : row(i, false))
ans[iter.first] = iter.second.value; //this->get_cell(i, iter->first, false);
return ans;
}
BARRAY_TEMPLATE(void, get_row_vec) (
std::vector< Cell_Type > * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
for (const auto & iter : row(i, false))
x->at(iter.first) = iter.second.value; // this->get_cell(i, iter->first, false);
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_col_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
std::vector< Cell_Type > ans(nrow(), (Cell_Type) false);
for (const auto iter : col(i, false))
ans[iter.first] = iter.second->value;//this->get_cell(iter->first, i, false);
return ans;
}
BARRAY_TEMPLATE(void, get_col_vec) (
std::vector<Cell_Type> * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
for (const auto & iter : col(i, false))
x->at(iter.first) = iter.second->value;//this->get_cell(iter->first, i, false);
}
BARRAY_TEMPLATE(const Row_type< Cell_Type > &, row) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, 0u);
return this->el_ij[i];
}
BARRAY_TEMPLATE(const Col_type< Cell_Type > &, col) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(0u, i);
return this->el_ji[i];
}
BARRAY_TEMPLATE(Entries< Cell_Type >, get_entries) () const {
Entries<Cell_Type> res(NCells);
for (uint i = 0u; i < N; ++i) {
if (ROW(i).size() == 0u)
continue;
for (auto col = ROW(i).begin(); col != ROW(i).end(); ++col) {
res.source.push_back(i),
res.target.push_back(col->first),
res.val.push_back(col->second.value);
}
}
return res;
}
BARRAY_TEMPLATE(bool, is_empty) (
uint i,
uint j,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, j);
if (ROW(i).size() == 0u)
return true;
else if (COL(j).size() == 0u)
return true;
if (ROW(i).find(j) == ROW(i).end())
return true;
return false;
}
BARRAY_TEMPLATE(unsigned int, nrow) () const noexcept {
return N;
}
BARRAY_TEMPLATE(unsigned int, ncol) () const noexcept {
return M;
}
BARRAY_TEMPLATE(unsigned int, nnozero) () const noexcept {
return NCells;
}
BARRAY_TEMPLATE(Cell< Cell_Type >, default_val) () const {
return this->Cell_default;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator+=) (
const std::pair<uint,uint> & coords
) {
this->insert_cell(
coords.first,
coords.second,
this->Cell_default,
true, true
);
return *this;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator-=) (
const std::pair<uint,uint> & coords
) {
this->rm_cell(
coords.first,
coords.second,
true, true
);
return *this;
}
template BARRAY_TEMPLATE_ARGS()
inline BArrayCell<Cell_Type,Data_Type> BARRAY_TYPE()::operator()(
uint i,
uint j,
bool check_bounds
) {
return BArrayCell<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
template BARRAY_TEMPLATE_ARGS()
inline const BArrayCell_const<Cell_Type,Data_Type> BARRAY_TYPE()::operator() (
uint i,
uint j,
bool check_bounds
) const {
return BArrayCell_const<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
BARRAY_TEMPLATE(void, rm_cell) (
uint i,
uint j,
bool check_bounds,
bool check_exists
) {
// Checking the boundaries
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Checking the counter part
if (COL(j).size() == 0u)
return;
// Hard work, need to remove it from both, if it exist
if (ROW(i).find(j) == ROW(i).end())
return;
}
// Remove the pointer first (so it wont point to empty)
COL(j).erase(i);
ROW(i).erase(j);
NCells--;
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
const Cell< Cell_Type> & v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell< Cell_Type> && v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell_Type v,
bool check_bounds,
bool check_exists
) {
return insert_cell(i, j, Cell<Cell_Type>(v, visited), check_bounds, check_exists);
}
BARRAY_TEMPLATE(void, swap_cells) (
uint i0, uint j0,
uint i1, uint j1,
bool check_bounds,
int check_exists,
int * report
) {
if (check_bounds) {
out_of_range(i0,j0);
out_of_range(i1,j1);
}
// Simplest case, we know both exists, so we don't need to check anything
if (check_exists == CHECK::NONE)
{
// Just in case, if this was passed
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
// Using the initializing by move, after this, the cell becomes
// invalid. We use pointers instead as this way we access the Heap memory,
// which should be faster to access.
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
// Inserting the cells by reference, these will be deleted afterwards
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
return;
}
bool check0, check1;
if (check_exists == CHECK::BOTH)
{
check0 = !is_empty(i0, j0, false);
check1 = !is_empty(i1, j1, false);
} else if (check_exists == CHECK::ONE) {
check0 = !is_empty(i0, j0, false);
check1 = true;
} else if (check_exists == CHECK::TWO) {
check0 = true;
check1 = !is_empty(i1, j1, false);
}
if (report != nullptr)
(*report) = EXISTS::NONE;
// If both cells exists
if (check0 & check1)
{
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
} else if (!check0 & check1) { // If only the second exists
if (report != nullptr)
(*report) = EXISTS::TWO;
insert_cell(i0, j0, ROW(i1)[j1], false, false);
rm_cell(i1, j1, false, false);
} else if (check0 & !check1) {
if (report != nullptr)
(*report) = EXISTS::ONE;
insert_cell(i1, j1, ROW(i0)[j0], false, false);
rm_cell(i0, j0, false, false);
}
return;
}
BARRAY_TEMPLATE(void, toggle_cell) (
uint i,
uint j,
bool check_bounds,
int check_exists
) {
if (check_bounds)
out_of_range(i, j);
if (check_exists == EXISTS::UKNOWN) {
if (is_empty(i, j, false)) {
insert_cell(i, j, BArray<Cell_Type, Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
} else
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ONE) {
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ZERO) {
insert_cell(i, j, BArray<Cell_Type,Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
}
return;
}
BARRAY_TEMPLATE(void, swap_rows) (
uint i0,
uint i1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(i0,0u);
out_of_range(i1,0u);
}
bool move0=true, move1=true;
if (ROW(i0).size() == 0u) move0 = false;
if (ROW(i1).size() == 0u) move1 = false;
if (!move0 && !move1)
return;
// Swapping happens naturally, need to take care of the pointers
// though
ROW(i0).swap(ROW(i1));
// Delete the thing
if (move0)
for (auto& i: row(i1, false))
COL(i.first).erase(i0);
if (move1)
for (auto& i: row(i0, false))
COL(i.first).erase(i1);
// Now, point to the thing, if it has something to point at. Recall that
// the indices swapped.
if (move1)
for (auto& i: row(i0, false))
COL(i.first)[i0] = &ROW(i0)[i.first];
if (move0)
for (auto& i: row(i1, false))
COL(i.first)[i1] = &ROW(i1)[i.first];
return;
}
// This swapping is more expensive overall
BARRAY_TEMPLATE(void, swap_cols) (
uint j0,
uint j1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(0u, j0);
out_of_range(0u, j1);
}
// Which ones need to be checked
bool check0 = true, check1 = true;
if (COL(j0).size() == 0u) check0 = false;
if (COL(j1).size() == 0u) check1 = false;
if (check0 && check1) {
// Just swapping one at a time
int status;
Col_type<Cell_Type> col_tmp = COL(j1);
Col_type<Cell_Type> col1 = COL(j0);
for (auto iter = col1.begin(); iter != col1.end(); ++iter) {
// Swapping values (col-wise)
swap_cells(iter->first, j0, iter->first, j1, false, CHECK::TWO, &status);
// Need to remove it, so we don't swap that as well
if (status == EXISTS::BOTH)
col_tmp.erase(iter->first);
}
// If there's anything left to move, we start moving it, otherwise, we just
// skip it
if (col_tmp.size() != 0u) {
for (auto iter = col_tmp.begin(); iter != col_tmp.end(); ++iter) {
insert_cell(iter->first, j0, *iter->second, false, false);
rm_cell(iter->first, j1);
}
}
} else if (check0 && !check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j0).begin(); iter != COL(j0).begin(); ++iter)
insert_cell(iter->first, j1, *iter->second, false, false);
// Setting the column to be zero
COL(j0).empty();
} else if (!check0 && check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j1).begin(); iter != COL(j1).begin(); ++iter) {
// Swapping values (col-wise)
insert_cell(iter->first, j0, *iter->second, false, false);
}
// Setting the column to be zero
COL(j1).empty();
}
return;
}
BARRAY_TEMPLATE(void, zero_row) (
uint i,
bool check_bounds
) {
if (check_bounds)
out_of_range(i, 0u);
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Else, remove all elements
auto row0 = ROW(i);
for (auto row = row0.begin(); row != row0.end(); ++row)
rm_cell(i, row->first, false, false);
return;
}
BARRAY_TEMPLATE(void, zero_col) (
uint j,
bool check_bounds
) {
if (check_bounds)
out_of_range(0u, j);
// Nothing to do
if (COL(j).size() == 0u)
return;
// Else, remove all elements
auto col0 = COL(j);
for (auto col = col0.begin(); col != col0.end(); ++col)
rm_cell(col->first, j, false, false);
return;
}
BARRAY_TEMPLATE(void, transpose) () {
// Start by flipping the switch
visited = !visited;
// Do we need to resize (increase) either?
if (N > M) el_ji.resize(N);
else if (N < M) el_ij.resize(M);
// uint N0 = N, M0 = M;
int status;
for (uint i = 0u; i < N; ++i)
{
// Do we need to move anything?
if (ROW(i).size() == 0u)
continue;
// We now iterate changing rows
Row_type<Cell_Type> row = ROW(i);
for (auto col = row.begin(); col != row.end(); ++col)
{
// Skip if in the diagoal
if (i == col->first)
{
ROW(i)[i].visited = visited;
continue;
}
// We have not visited this yet, we need to change that
if (ROW(i)[col->first].visited != visited)
{
// First, swap the contents
swap_cells(i, col->first, col->first, i, false, CHECK::TWO, &status);
// Changing the switch
if (status == EXISTS::BOTH)
ROW(i)[col->first].visited = visited;
ROW(col->first)[i].visited = visited;
}
}
}
// Shreding. Note that no information should have been lost since, hence, no
// change in NCells.
if (N > M) el_ij.resize(M);
else if (N < M) el_ji.resize(N);
// Swapping the values
std::swap(N, M);
return;
}
BARRAY_TEMPLATE(void, clear) (
bool hard
) {
if (hard)
{
el_ji.clear();
el_ij.clear();
el_ij.resize(N);
el_ji.resize(M);
NCells = 0u;
} else {
for (unsigned int i = 0u; i < N; ++i)
zero_row(i, false);
}
return;
}
BARRAY_TEMPLATE(void, resize) (
uint N_,
uint M_
) {
// Removing rows
if (N_ < N)
for (uint i = N_; i < N; ++i)
zero_row(i, false);
// Removing cols
if (M_ < M)
for (uint j = M_; j < M; ++j)
zero_col(j, false);
// Resizing will invalidate pointers and values out of range
if (M_ != M) {
el_ji.resize(M_);
M = M_;
}
if (N_ != N) {
el_ij.resize(N_);
N = N_;
}
return;
}
BARRAY_TEMPLATE(void, reserve) () {
#ifdef BARRAY_USE_UNORDERED_MAP
for (uint i = 0u; i < N; i++)
ROW(i).reserve(M);
for (uint i = 0u; i < M; i++)
COL(i).reserve(N);
#endif
return;
}
BARRAY_TEMPLATE(void, print) (
const char * fmt,
...
) const {
std::va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
for (uint i = 0u; i < N; ++i)
{
#ifdef BARRY_DEBUG_LEVEL
#if BARRY_DEBUG_LEVEL > 1
printf_barry("%s [%3i,]", BARRY_DEBUG_HEADER, i);
#endif
#else
printf_barry("[%3i,] ", i);
#endif
for (uint j = 0u; j < M; ++j) {
if (this->is_empty(i, j, false))
printf_barry(" . ");
else
printf_barry(" %.2f ", static_cast<double>(this->get_cell(i, j, false)));
}
printf_barry("\n");
}
return;
}
#undef ROW
#undef COL
#undef BARRAY_TYPE
#undef BARRAY_TEMPLATE_ARGS
#undef BARRAY_TEMPLATE
#endif
| 21.968215 | 113 | 0.506733 |
287f82ec982f80d5bf005edffbe89f3e874bde45 | 5,060 | cxx | C++ | Charts/vtkContextActor.cxx | Lin1225/vtk_v5.10.0 | b54ac74f4716572862365fbff28cd0ecb8d08c3d | [
"BSD-3-Clause"
] | 2 | 2020-01-07T20:50:53.000Z | 2020-01-29T18:22:02.000Z | Charts/vtkContextActor.cxx | Armand0s/homemade_vtk | 6bc7b595a4a7f86e8fa969d067360450fa4e0a6a | [
"BSD-3-Clause"
] | null | null | null | Charts/vtkContextActor.cxx | Armand0s/homemade_vtk | 6bc7b595a4a7f86e8fa969d067360450fa4e0a6a | [
"BSD-3-Clause"
] | 5 | 2015-03-23T21:13:19.000Z | 2022-01-03T11:15:39.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkContextActor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkContextActor.h"
#include "vtkContext2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGL2ContextDevice2D.h"
#include "vtkContextScene.h"
#include "vtkTransform2D.h"
#include "vtkViewport.h"
#include "vtkWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkContextActor);
vtkCxxSetObjectMacro(vtkContextActor, Context, vtkContext2D);
vtkCxxSetObjectMacro(vtkContextActor, Scene, vtkContextScene);
//----------------------------------------------------------------------------
vtkContextActor::vtkContextActor()
{
this->Context = vtkContext2D::New();
this->Scene = vtkContextScene::New();
this->Initialized = false;
}
//----------------------------------------------------------------------------
// Destroy an actor2D.
vtkContextActor::~vtkContextActor()
{
if (this->Context)
{
this->Context->End();
this->Context->Delete();
this->Context = NULL;
}
if (this->Scene)
{
this->Scene->Delete();
this->Scene = NULL;
}
}
//----------------------------------------------------------------------------
void vtkContextActor::ReleaseGraphicsResources(vtkWindow *window)
{
vtkOpenGLContextDevice2D *device =
vtkOpenGLContextDevice2D::SafeDownCast(this->Context->GetDevice());
if (device)
{
device->ReleaseGraphicsResources(window);
}
if(this->Scene)
{
this->Scene->ReleaseGraphicsResources();
}
}
//----------------------------------------------------------------------------
// Renders an actor2D's property and then it's mapper.
int vtkContextActor::RenderOverlay(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkContextActor::RenderOverlay");
if (!this->Context)
{
vtkErrorMacro(<< "vtkContextActor::Render - No painter set");
return 0;
}
// Need to figure out how big the window is, taking into account tiling...
vtkWindow *window = viewport->GetVTKWindow();
int scale[2];
window->GetTileScale(scale);
int size[2];
size[0] = window->GetSize()[0];
size[1] = window->GetSize()[1];
int viewportInfo[4];
viewport->GetTiledSizeAndOrigin( &viewportInfo[0], &viewportInfo[1],
&viewportInfo[2], &viewportInfo[3] );
// The viewport is in normalized coordinates, and is the visible section of
// the scene.
vtkTransform2D* transform = this->Scene->GetTransform();
transform->Identity();
if (scale[0] > 1 || scale[1] > 1)
{
// Tiled display - work out the transform required
double *b = window->GetTileViewport();
int box[] = { vtkContext2D::FloatToInt(b[0] * size[0]),
vtkContext2D::FloatToInt(b[1] * size[1]),
vtkContext2D::FloatToInt(b[2] * size[0]),
vtkContext2D::FloatToInt(b[3] * size[1]) };
transform->Translate(-box[0], -box[1]);
if (this->Scene->GetScaleTiles())
{
transform->Scale(scale[0], scale[1]);
}
}
else if (viewportInfo[0] != size[0] || viewportInfo[1] != size[1] )
{
size[0]=viewportInfo[0];
size[1]=viewportInfo[1];
}
if (!this->Initialized)
{
this->Initialize(viewport);
}
// This is the entry point for all 2D rendering.
// First initialize the drawing device.
this->Context->GetDevice()->Begin(viewport);
this->Scene->SetGeometry(size);
this->Scene->Paint(this->Context);
this->Context->GetDevice()->End();
return 1;
}
//----------------------------------------------------------------------------
void vtkContextActor::Initialize(vtkViewport* viewport)
{
vtkContextDevice2D *device = NULL;
if (vtkOpenGL2ContextDevice2D::IsSupported(viewport))
{
vtkDebugMacro("Using OpenGL 2 for 2D rendering.")
device = vtkOpenGL2ContextDevice2D::New();
}
else
{
vtkDebugMacro("Using OpenGL 1 for 2D rendering.")
device = vtkOpenGLContextDevice2D::New();
}
if (device)
{
this->Context->Begin(device);
device->Delete();
this->Initialized = true;
}
else
{
// Failed
vtkErrorMacro("Error: failed to initialize the render device.")
}
}
//----------------------------------------------------------------------------
void vtkContextActor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Context: " << this->Context << "\n";
if (this->Context)
{
this->Context->PrintSelf(os, indent.GetNextIndent());
}
}
| 28.268156 | 78 | 0.588735 |
287f86cc257f7c6803d7226c36014d060a9e76fb | 4,800 | hxx | C++ | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 1 | 2022-03-15T22:54:39.000Z | 2022-03-15T22:54:39.000Z | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | null | null | null | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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.
*/
#pragma once
#include "access_log/Config.hxx"
#include "ssl/Config.hxx"
#include "net/SocketConfig.hxx"
#include "spawn/Config.hxx"
#include <forward_list>
#include <chrono>
#include <stddef.h>
struct StringView;
/**
* Configuration.
*/
struct BpConfig {
struct Listener : SocketConfig {
std::string tag;
#ifdef HAVE_AVAHI
std::string zeroconf_service;
std::string zeroconf_interface;
#endif
/**
* If non-empty, then this listener has its own
* translation server(s) and doesn't use the global
* server.
*/
std::forward_list<AllocatedSocketAddress> translation_sockets;
enum class Handler {
TRANSLATION,
PROMETHEUS_EXPORTER,
} handler = Handler::TRANSLATION;
bool auth_alt_host = false;
bool ssl = false;
SslConfig ssl_config;
Listener() {
listen = 64;
tcp_defer_accept = 10;
}
explicit Listener(SocketAddress _address) noexcept
:SocketConfig(_address)
{
listen = 64;
tcp_defer_accept = 10;
}
#ifdef HAVE_AVAHI
/**
* @return the name of the interface where the
* Zeroconf service shall be published
*/
[[gnu::pure]]
const char *GetZeroconfInterface() const noexcept {
if (!zeroconf_interface.empty())
return zeroconf_interface.c_str();
if (!interface.empty())
return interface.c_str();
return nullptr;
}
#endif
};
std::forward_list<Listener> listen;
AccessLogConfig access_log;
AccessLogConfig child_error_log;
std::string session_cookie = "beng_proxy_session";
std::chrono::seconds session_idle_timeout = std::chrono::minutes(30);
std::string session_save_path;
struct ControlListener : SocketConfig {
ControlListener() {
pass_cred = true;
}
explicit ControlListener(SocketAddress _bind_address)
:SocketConfig(_bind_address) {
pass_cred = true;
}
};
std::forward_list<ControlListener> control_listen;
std::forward_list<AllocatedSocketAddress> translation_sockets;
/** maximum number of simultaneous connections */
unsigned max_connections = 32768;
size_t http_cache_size = 512 * 1024 * 1024;
size_t filter_cache_size = 128 * 1024 * 1024;
size_t nfs_cache_size = 256 * 1024 * 1024;
unsigned translate_cache_size = 131072;
unsigned translate_stock_limit = 32;
unsigned tcp_stock_limit = 0;
unsigned lhttp_stock_limit = 0, lhttp_stock_max_idle = 8;
unsigned fcgi_stock_limit = 0, fcgi_stock_max_idle = 8;
unsigned was_stock_limit = 0, was_stock_max_idle = 16;
unsigned multi_was_stock_limit = 0, multi_was_stock_max_idle = 16;
unsigned remote_was_stock_limit = 0, remote_was_stock_max_idle = 16;
unsigned cluster_size = 0, cluster_node = 0;
enum class SessionCookieSameSite : uint8_t {
NONE,
STRICT,
LAX,
} session_cookie_same_site;
bool dynamic_session_cookie = false;
bool verbose_response = false;
bool emulate_mod_auth_easy = false;
bool http_cache_obey_no_cache = true;
SpawnConfig spawn;
SslClientConfig ssl_client;
BpConfig() {
#ifdef HAVE_LIBSYSTEMD
spawn.systemd_scope = "bp-spawn.scope";
spawn.systemd_scope_description = "The cm4all-beng-proxy child process spawner";
spawn.systemd_slice = "system-cm4all.slice";
#endif
}
void HandleSet(StringView name, const char *value);
void Finish(unsigned default_port);
};
/**
* Load and parse the specified configuration file. Throws an
* exception on error.
*/
void
LoadConfigFile(BpConfig &config, const char *path);
| 24.742268 | 82 | 0.74375 |
2880119cd99ce85a00042ad784d2634da983d136 | 3,381 | cpp | C++ | MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp | millerthegorilla/midi-blocks | b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac | [
"MIT"
] | null | null | null | MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp | millerthegorilla/midi-blocks | b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac | [
"MIT"
] | null | null | null | MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp | millerthegorilla/midi-blocks | b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac | [
"MIT"
] | null | null | null | /*
Copyright (C) 2013 Adam Nash
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "chordbankblock.h"
#include "ui_chordbankblockeditor.h"
#include "chorditemdelegate.h"
#include <QDebug>
ChordBankBlock::ChordBankBlock(QObject *parent) :
editorUi(new Ui::ChordBankBlockEditor)
{
if (parent)
{
setParent(parent);
}
editor = new QWidget();
editorUi->setupUi(editor);
editorUi->tv_chords->setModel(&m_model);
editorUi->tv_chords->setItemDelegateForColumn(0, new ChordItemDelegate(this));
editorUi->verticalLayout->insertWidget(0, &m_chordEditor);
connect(editorUi->pb_add, SIGNAL(clicked()),
this, SLOT(addChord()));
connect(editorUi->pb_remove, SIGNAL(clicked()),
this, SLOT(removeChord()));
}
ChordBankBlock::~ChordBankBlock()
{
delete editorUi;
delete editor;
}
QString ChordBankBlock::getName()
{
return "Chord Bank Block";
}
QString ChordBankBlock::getGroupName()
{
return "Chord Blocks";
}
QWidget* ChordBankBlock::getEditorWidget()
{
return editor;
}
ControlBlock* ChordBankBlock::createDefaultBlock()
{
return new ChordBankBlock();
}
void ChordBankBlock::receiveBeat(QByteArray message)
{
Q_UNUSED(message)
//take off all previous notes
if (!m_notes.isEmpty())
{
foreach(QByteArray note, m_notes)
{
note[0] = 128;
sendChord(note);
}
m_notes.clear();
}
m_model.incrementBeat();
QList<QVariant> notes = m_model.getChordForBeat();
foreach(QVariant note, notes)
{
QByteArray noteOn;
noteOn.push_back(static_cast<char>(144));
noteOn.push_back(static_cast<char>(note.toInt()));
noteOn.push_back(static_cast<char>(100));
m_notes.push_back(noteOn);
sendChord(noteOn);
}
}
//void ChordBankBlock::receiveToggle_Write_Mode(QByteArray message)
//{
// //TODO: engage chord writing mode
//}
//void ChordBankBlock::receiveWrite_Input(QByteArray message)
//{
// //TODO: write the chord if in chord writing mode
//}
void ChordBankBlock::addChord()
{
if (m_model.insertRows(m_model.rowCount(QModelIndex()), 1, QModelIndex()))
{
m_model.setData(m_model.index(m_model.rowCount(QModelIndex())-1, 0),
m_chordEditor.getValues(),
Qt::EditRole);
}
}
void ChordBankBlock::removeChord()
{
foreach (QModelIndex index, editorUi->tv_chords->selectionModel()->selectedRows())
{
m_model.removeRows(index.row(), 1, QModelIndex());
}
}
Q_EXPORT_PLUGIN2(chordbankblockplugin, ChordBankBlock)
| 25.421053 | 87 | 0.645075 |
2884713e818f042a181b5f03563ddcc2d3315a69 | 1,652 | cc | C++ | garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/lib/ui/gfx/resources/stereo_camera.h"
#include <lib/ui/scenic/cpp/commands.h>
#include <gtest/gtest.h>
#include "garnet/lib/ui/gfx/tests/session_test.h"
#include "src/ui/lib/escher/util/epsilon_compare.h"
#include <glm/gtc/type_ptr.hpp>
namespace scenic_impl {
namespace gfx {
namespace test {
using StereoCameraTest = SessionTest;
TEST_F(StereoCameraTest, Basic) {
constexpr ResourceId invalid_id = 0;
constexpr ResourceId scene_id = 1;
constexpr ResourceId camera_id = 2;
ASSERT_TRUE(Apply(scenic::NewCreateSceneCmd(scene_id)));
EXPECT_TRUE(Apply(scenic::NewCreateStereoCameraCmd(camera_id, scene_id)));
EXPECT_FALSE(Apply(scenic::NewCreateStereoCameraCmd(camera_id, invalid_id)));
// Not really projection matrices but we're just testing the setters
glm::mat4 left_projection = glm::mat4(2);
glm::mat4 right_projection = glm::mat4(3);
EXPECT_TRUE(Apply(scenic::NewSetStereoCameraProjectionCmd(
camera_id, glm::value_ptr(left_projection), glm::value_ptr(right_projection))));
auto camera = session()->resources()->FindResource<StereoCamera>(camera_id);
EXPECT_TRUE(camera);
EXPECT_TRUE(escher::CompareMatrix(left_projection,
camera->GetEscherCamera(StereoCamera::Eye::LEFT).projection()));
EXPECT_TRUE(escher::CompareMatrix(
right_projection, camera->GetEscherCamera(StereoCamera::Eye::RIGHT).projection()));
}
} // namespace test
} // namespace gfx
} // namespace scenic_impl
| 33.714286 | 100 | 0.746368 |
288511bf23e83f6efbf7f5bcf6be5bee633d6b90 | 8,823 | cpp | C++ | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | /*
* LinuxWindow.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <LLGL/Platform/NativeHandle.h>
#include <LLGL/Display.h>
#include "LinuxWindow.h"
#include "MapKey.h"
#include <exception>
namespace LLGL
{
static Offset2D GetScreenCenteredPosition(const Extent2D& size)
{
if (auto display = Display::InstantiatePrimary())
{
const auto resolution = display->GetDisplayMode().resolution;
return
{
static_cast<int>((resolution.width - size.width )/2),
static_cast<int>((resolution.height - size.height)/2),
};
}
return {};
}
std::unique_ptr<Window> Window::Create(const WindowDescriptor& desc)
{
return std::unique_ptr<Window>(new LinuxWindow(desc));
}
LinuxWindow::LinuxWindow(const WindowDescriptor& desc) :
desc_ { desc }
{
OpenWindow();
}
LinuxWindow::~LinuxWindow()
{
XDestroyWindow(display_, wnd_);
XCloseDisplay(display_);
}
void LinuxWindow::GetNativeHandle(void* nativeHandle) const
{
auto& handle = *reinterpret_cast<NativeHandle*>(nativeHandle);
handle.display = display_;
handle.window = wnd_;
handle.visual = visual_;
}
void LinuxWindow::ResetPixelFormat()
{
// dummy
}
Extent2D LinuxWindow::GetContentSize() const
{
/* Return the size of the client area */
return GetSize(true);
}
void LinuxWindow::SetPosition(const Offset2D& position)
{
/* Move window and store new position */
XMoveWindow(display_, wnd_, position.x, position.y);
desc_.position = position;
}
Offset2D LinuxWindow::GetPosition() const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return { attribs.x, attribs.y };
}
void LinuxWindow::SetSize(const Extent2D& size, bool useClientArea)
{
XResizeWindow(display_, wnd_, size.width, size.height);
}
Extent2D LinuxWindow::GetSize(bool useClientArea) const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return Extent2D
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
}
void LinuxWindow::SetTitle(const std::wstring& title)
{
/* Convert UTF16 to UTF8 string (X11 limitation) and set window title */
std::string s(title.begin(), title.end());
XStoreName(display_, wnd_, s.c_str());
}
std::wstring LinuxWindow::GetTitle() const
{
return std::wstring();
}
void LinuxWindow::Show(bool show)
{
if (show)
{
/* Map window and reset window position */
XMapWindow(display_, wnd_);
XMoveWindow(display_, wnd_, desc_.position.x, desc_.position.y);
}
else
XUnmapWindow(display_, wnd_);
if (desc_.borderless)
XSetInputFocus(display_, (show ? wnd_ : None), RevertToParent, CurrentTime);
}
bool LinuxWindow::IsShown() const
{
return false;
}
void LinuxWindow::SetDesc(const WindowDescriptor& desc)
{
//todo...
}
WindowDescriptor LinuxWindow::GetDesc() const
{
return desc_; //todo...
}
void LinuxWindow::OnProcessEvents()
{
XEvent event;
XPending(display_);
while (XQLength(display_))
{
XNextEvent(display_, &event);
switch (event.type)
{
case KeyPress:
ProcessKeyEvent(event.xkey, true);
break;
case KeyRelease:
ProcessKeyEvent(event.xkey, false);
break;
case ButtonPress:
ProcessMouseKeyEvent(event.xbutton, true);
break;
case ButtonRelease:
ProcessMouseKeyEvent(event.xbutton, false);
break;
case Expose:
ProcessExposeEvent();
break;
case MotionNotify:
ProcessMotionEvent(event.xmotion);
break;
case DestroyNotify:
PostQuit();
break;
case ClientMessage:
ProcessClientMessage(event.xclient);
break;
}
}
XFlush(display_);
}
/*
* ======= Private: =======
*/
void LinuxWindow::OpenWindow()
{
/* Get native context handle */
auto nativeHandle = reinterpret_cast<const NativeContextHandle*>(desc_.windowContext);
if (nativeHandle)
{
/* Get X11 display from context handle */
display_ = nativeHandle->display;
visual_ = nativeHandle->visual;
}
else
{
/* Open X11 display */
display_ = XOpenDisplay(nullptr);
visual_ = nullptr;
}
if (!display_)
throw std::runtime_error("failed to open X11 display");
/* Setup common parameters for window creation */
::Window rootWnd = (nativeHandle != nullptr ? nativeHandle->parentWindow : DefaultRootWindow(display_));
int screen = (nativeHandle != nullptr ? nativeHandle->screen : DefaultScreen(display_));
::Visual* visual = (nativeHandle != nullptr ? nativeHandle->visual->visual : DefaultVisual(display_, screen));
int depth = (nativeHandle != nullptr ? nativeHandle->visual->depth : DefaultDepth(display_, screen));
int borderSize = 0;
/* Setup window attributes */
XSetWindowAttributes attribs;
attribs.background_pixel = WhitePixel(display_, screen);
attribs.border_pixel = 0;
attribs.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
unsigned long valueMask = CWEventMask | CWBorderPixel;//(CWColormap | CWEventMask | CWOverrideRedirect)
if (nativeHandle)
{
valueMask |= CWColormap;
attribs.colormap = nativeHandle->colorMap;
}
else
valueMask |= CWBackPixel;
if (desc_.borderless) //WARNING -> input no longer works
{
valueMask |= CWOverrideRedirect;
attribs.override_redirect = true;
}
/* Get final window position */
if (desc_.centered)
desc_.position = GetScreenCenteredPosition(desc_.size);
/* Create X11 window */
wnd_ = XCreateWindow(
display_,
rootWnd,
desc_.position.x,
desc_.position.y,
desc_.size.width,
desc_.size.height,
borderSize,
depth,
InputOutput,
visual,
valueMask,
(&attribs)
);
/* Set title and show window (if enabled) */
SetTitle(desc_.title);
/* Show window */
if (desc_.visible)
Show();
/* Prepare borderless window */
if (desc_.borderless)
{
XGrabKeyboard(display_, wnd_, True, GrabModeAsync, GrabModeAsync, CurrentTime);
XGrabPointer(display_, wnd_, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, wnd_, None, CurrentTime);
}
/* Enable WM_DELETE_WINDOW protocol */
closeWndAtom_ = XInternAtom(display_, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display_, wnd_, &closeWndAtom_, 1);
}
void LinuxWindow::ProcessKeyEvent(XKeyEvent& event, bool down)
{
auto key = MapKey(event);
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
void LinuxWindow::ProcessMouseKeyEvent(XButtonEvent& event, bool down)
{
switch (event.button)
{
case Button1:
PostMouseKeyEvent(Key::LButton, down);
break;
case Button2:
PostMouseKeyEvent(Key::MButton, down);
break;
case Button3:
PostMouseKeyEvent(Key::RButton, down);
break;
case Button4:
PostWheelMotion(1);
break;
case Button5:
PostWheelMotion(-1);
break;
}
}
void LinuxWindow::ProcessExposeEvent()
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
const Extent2D size
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
PostResize(size);
}
void LinuxWindow::ProcessClientMessage(XClientMessageEvent& event)
{
Atom atom = static_cast<Atom>(event.data.l[0]);
if (atom == closeWndAtom_)
PostQuit();
}
void LinuxWindow::ProcessMotionEvent(XMotionEvent& event)
{
const Offset2D mousePos { event.x, event.y };
PostLocalMotion(mousePos);
PostGlobalMotion({ mousePos.x - prevMousePos_.x, mousePos.y - prevMousePos_.y });
prevMousePos_ = mousePos;
}
void LinuxWindow::PostMouseKeyEvent(Key key, bool down)
{
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
} // /namespace LLGL
// ================================================================================
| 24.714286 | 139 | 0.613737 |
2885e7fa9c064cb4a5913f9b8f8db37177f0bb98 | 323 | cpp | C++ | src/kits/debugger/source_language/c_family/CppLanguage.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/kits/debugger/source_language/c_family/CppLanguage.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/kits/debugger/source_language/c_family/CppLanguage.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Copyright 2012-2013, Rene Gollent, rene@gollent.com.
* Distributed under the terms of the MIT License.
*/
#include "CppLanguage.h"
CppLanguage::CppLanguage()
{
}
CppLanguage::~CppLanguage()
{
}
const char*
CppLanguage::Name() const
{
return "C++";
}
| 12.423077 | 55 | 0.690402 |
28860ae214f32e95d2218a6f6437461182ed6b67 | 872 | cxx | C++ | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 15 | 2020-04-22T15:18:28.000Z | 2022-03-24T07:48:28.000Z | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 25 | 2020-04-18T18:55:50.000Z | 2021-05-30T21:26:39.000Z | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 2 | 2020-09-16T05:55:54.000Z | 2021-01-09T12:09:43.000Z | /**
* @file KubelkaMunkTest.cxx
* @author thomas lindemeier
*
* @brief
*
* @date 2020-05-14
*
*/
#include "gtest/gtest.h"
#include "painty/core/KubelkaMunk.hxx"
TEST(KubelkaMunk, Reflectance) {
constexpr auto Eps = 0.00001;
const auto d = 0.5;
const painty::vec<double, 3U> k = {0.2, 0.1, 0.22};
const painty::vec<double, 3U> s = {0.124, 0.658, 0.123};
const painty::vec<double, 3U> r0 = {0.65, 0.2, 0.2146};
const auto r1 = painty::ComputeReflectance(k, s, r0, d);
EXPECT_NEAR(r1[0], 0.541596, Eps);
EXPECT_NEAR(r1[1], 0.343822, Eps);
EXPECT_NEAR(r1[2], 0.206651, Eps);
EXPECT_NEAR(painty::ComputeReflectance(k, s, r0, 0.0)[0], r0[0], Eps);
const painty::vec<double, 3U> s2 = {0.0, 0.0, 0.0};
EXPECT_NEAR(painty::ComputeReflectance(k, s2, r0, d)[0], 0.53217499727638173,
Eps);
}
| 27.25 | 79 | 0.598624 |
2887edc208ada4e07f89e8459df6bc8b4032330b | 6,198 | cpp | C++ | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 8 | 2018-03-05T04:14:44.000Z | 2021-12-22T03:18:16.000Z | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 10 | 2018-02-23T22:09:07.000Z | 2019-06-06T17:29:26.000Z | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 7 | 2018-04-06T00:16:43.000Z | 2020-06-26T13:32:47.000Z | //
// Created by sn0w1eo on 26.02.18.
//
#include <gtest/gtest.h>
#include <hash_table.hpp>
#include <enum_table.hpp>
#include "enum_record_set.hpp"
namespace {
using rapidjson::Value;
using namespace DBConvert::Structures;
class EnumRecordSetTest : public ::testing::Test {
protected:
void SetUp() {
any_value_ptr = new Value;
any_value_ptr->SetString("Any Value");
any_value_ptr2 = new Value;
any_value_ptr2->SetDouble(42.42);
parent_title = new Value;
parent_title->SetString("Parent Table");
child_title = new Value;
child_title->SetString("Child Table");
parent_table = new EnumTable(1, parent_title, 0, nullptr);
child_table = new EnumTable(2, child_title, 0, parent_table);
parent_rs = parent_table->get_record_set();
child_rs = child_table->get_record_set();
}
void TearDown() {
parent_rs = nullptr;
child_rs = nullptr;
delete parent_table;
delete child_table;
delete parent_title;
delete child_title;
delete any_value_ptr;
delete any_value_ptr2;
}
Value * parent_title;
Value * child_title;
Table * parent_table;
Table * child_table;
RecordSet * parent_rs;
RecordSet * child_rs;
Value * any_value_ptr;
Value * any_value_ptr2;
};
TEST_F(EnumRecordSetTest, CtorOwnerTableNullException) {
try {
EnumRecordSet ers(nullptr);
FAIL();
} catch (const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_Ctor_OwnerTableUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackIdFieldInCtorAsFirstElement) {
EnumRecordSet ers(parent_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(0)->get_title(), COLUMN_TITLES::PRIMARY_KEY_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackRefIdFieldAsSecondElementIfParentExists) { ;
EnumRecordSet ers(child_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(1)->get_title(), COLUMN_TITLES::REFERENCE_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsThirdElementIfParentExists) {
EnumRecordSet child_rs(child_table);
EXPECT_TRUE( strcmp(child_rs.get_fields()->at(2)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsSecondElementIfNoParent) {
EnumRecordSet parent_rs(parent_table);
EXPECT_TRUE( strcmp(parent_rs.get_fields()->at(1)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, AddRecordNullValuePtrException) {
try {
parent_rs->add_record(nullptr);
FAIL();
} catch (const ERROR_CODES err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ValueUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordIncreaseCurrentIdEachTime) {
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_current_id(), 1);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_current_id(), 2);
EXPECT_EQ(parent_rs->get_records()->size(), 2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdAndValueInEnumField) {
Field * id_field = parent_rs->get_fields()->at(0);
Field * enum_field = parent_rs->get_fields()->at(1); // if ParentTable exists enum_field will be ->at(2) otherwise ->at(1)
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 1);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdRefIfParentTableExists) {
parent_rs->add_record(any_value_ptr);
child_rs->add_record(any_value_ptr2);
Field * child_ref_id_field = child_rs->get_fields()->at(1);
uint64_t parent_current_id = parent_rs->get_current_id();
uint64_t child_ref_id = child_rs->get_records()->back()->get_value(child_ref_id_field)->GetUint64();
EXPECT_EQ(child_ref_id, parent_current_id);
}
TEST_F(EnumRecordSetTest, AddRecordExceptionIfParentExistsButParentCurrentIdRecordIsZero) {
try{
child_rs->add_record(any_value_ptr);
FAIL();
} catch(const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ParentTableCurrentIdRecordIsZero);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordUpdatesEnumField) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
EXPECT_EQ(enum_field->get_length(), 0);
Value v1; v1.SetInt(12); // length is sizeof(uint32_t)
parent_rs->add_record(&v1);
EXPECT_EQ(enum_field->get_length(), sizeof(uint32_t));
Value v2; v2.SetString("123456789"); // length is 9
parent_rs->add_record(&v2);
EXPECT_EQ(enum_field->get_length(), strlen(v2.GetString()));
}
TEST_F(EnumRecordSetTest, AddNullRecordAddsValueSetNullToRecords) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
parent_rs->add_null_record();
Record * added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
parent_rs->add_null_record();
added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
EXPECT_EQ( parent_rs->get_records()->size(), 2);
}
} | 38.496894 | 132 | 0.647306 |
288bc24fb2022d139bf8d20be6b86508c0df0c25 | 12,073 | cc | C++ | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | 1 | 2019-11-21T09:33:40.000Z | 2019-11-21T09:33:40.000Z | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | null | null | null | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | 2 | 2020-03-09T09:11:41.000Z | 2020-04-01T13:38:20.000Z | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "RequestManagerVirtualRouter.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerVirtualMachine.h"
#include "PoolObjectAuth.h"
#include "Nebula.h"
#include "DispatchManager.h"
#include "VirtualRouterPool.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
RequestManagerVirtualRouter::RequestManagerVirtualRouter(const string& method_name,
const string& help,
const string& params)
: Request(method_name, params, help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
auth_op = AuthRequest::MANAGE;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterInstantiate::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int n_vms = xmlrpc_c::value_int(paramList.getInt(2));
int tmpl_id = xmlrpc_c::value_int(paramList.getInt(3));
string name = xmlrpc_c::value_string(paramList.getString(4));
bool on_hold = xmlrpc_c::value_boolean(paramList.getBoolean(5));
string str_uattrs = xmlrpc_c::value_string(paramList.getString(6));
Nebula& nd = Nebula::instance();
VirtualRouterPool* vrpool = nd.get_vrouterpool();
VirtualRouter * vr;
DispatchManager* dm = nd.get_dm();
VMTemplatePool* tpool = nd.get_tpool();
PoolObjectAuth vr_perms;
Template* extra_attrs;
string error;
string vr_name, tmp_name;
ostringstream oss;
vector<int> vms;
vector<int>::iterator vmid;
int vid;
/* ---------------------------------------------------------------------- */
/* Get the Virtual Router NICs */
/* ---------------------------------------------------------------------- */
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
extra_attrs = vr->get_vm_template();
vr_name = vr->get_name();
if (tmpl_id == -1)
{
tmpl_id = vr->get_template_id();
}
vr->unlock();
if (tmpl_id == -1)
{
att.resp_msg = "A template ID was not provided, and the virtual router "
"does not have a default one";
failure_response(ACTION, att);
return;
}
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
VMTemplate * tmpl = tpool->get_ro(tmpl_id);
if ( tmpl == 0 )
{
att.resp_id = tmpl_id;
att.resp_obj = PoolObjectSQL::TEMPLATE;
failure_response(NO_EXISTS, att);
return;
}
bool is_vrouter = tmpl->is_vrouter();
tmpl->unlock();
if (!is_vrouter)
{
att.resp_msg = "Only virtual router templates are allowed";
failure_response(ACTION, att);
return;
}
if (name.empty())
{
name = "vr-" + vr_name + "-%i";
}
VMTemplateInstantiate tmpl_instantiate;
for (int i=0; i<n_vms; oss.str(""), i++)
{
oss << i;
tmp_name = one_util::gsub(name, "%i", oss.str());
ErrorCode ec = tmpl_instantiate.request_execute(tmpl_id, tmp_name,
true, str_uattrs, extra_attrs, vid, att);
if (ec != SUCCESS)
{
failure_response(ec, att);
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->delete_vm(*vmid, att, att.resp_msg);
}
return;
}
vms.push_back(vid);
}
vr = vrpool->get(vrid);
if (vr != 0)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
vr->add_vmid(*vmid);
}
vr->set_template_id(tmpl_id);
vrpool->update(vr);
vr->unlock();
}
// VMs are created on hold to wait for all of them to be created
// successfully, to avoid the rollback dm->finalize call on prolog
if (!on_hold)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->release(*vmid, att, att.resp_msg);
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterAttachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
VectorAttribute* nic;
VectorAttribute* nic_bck;
VirtualMachineTemplate tmpl;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
string str_tmpl = xmlrpc_c::value_string(paramList.getString(2));
// -------------------------------------------------------------------------
// Parse NIC template
// -------------------------------------------------------------------------
rc = tmpl.parse_str_or_xml(str_tmpl, att.resp_msg);
if ( rc != 0 )
{
failure_response(INTERNAL, att);
return;
}
// -------------------------------------------------------------------------
// Authorize the operation & check quotas
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
VirtualRouter::set_auth_request(att.uid, ar, &tmpl, true); // USE VNET
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
RequestAttributes att_quota(vr_perms.uid, vr_perms.gid, att);
if ( quota_authorization(&tmpl, Quotas::VIRTUALROUTER, att_quota) == false )
{
return;
}
// -------------------------------------------------------------------------
// Attach NIC to the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
nic = vr->attach_nic(&tmpl, att.resp_msg);
if ( nic != 0 )
{
nic_bck = nic->clone();
}
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (nic == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
failure_response(ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Attach NIC to each VM
// -------------------------------------------------------------------------
VirtualMachineAttachNic vm_attach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
VirtualMachineTemplate tmpl;
tmpl.set(nic_bck->clone());
ErrorCode ec = vm_attach_nic.request_execute(*vmid, tmpl, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
delete nic_bck;
failure_response(ACTION, att);
return;
}
}
delete nic_bck;
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterDetachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int nic_id = xmlrpc_c::value_int(paramList.getInt(2));
// -------------------------------------------------------------------------
// Authorize the operation
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
// -------------------------------------------------------------------------
// Detach the NIC from the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
rc = vr->detach_nic(nic_id);
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (rc != 0)
{
ostringstream oss;
oss << "NIC with NIC_ID " << nic_id << " does not exist.";
att.resp_msg = oss.str();
failure_response(Request::ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Detach NIC from each VM
// -------------------------------------------------------------------------
VirtualMachineDetachNic vm_detach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
ErrorCode ec = vm_detach_nic.request_execute(*vmid, nic_id, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
failure_response(Request::ACTION, att);
return;
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
| 28.745238 | 83 | 0.455562 |
288cfffdcaf3e3d50d5fe581c917ddd589663956 | 2,955 | cpp | C++ | Engine/databaseadmincsvformat.cpp | vadkasevas/BAS | 657f62794451c564c77d6f92b2afa9f5daf2f517 | [
"MIT"
] | 302 | 2016-05-20T12:55:23.000Z | 2022-03-29T02:26:14.000Z | Engine/databaseadmincsvformat.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 9 | 2016-07-21T09:04:50.000Z | 2021-05-16T07:34:42.000Z | Engine/databaseadmincsvformat.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 113 | 2016-05-18T07:48:37.000Z | 2022-02-26T12:59:39.000Z | #include "databaseadmincsvformat.h"
#include "ui_databaseadmincsvformat.h"
#include <QDir>
#include <QFileDialog>
#include <QDebug>
DatabaseAdminCsvFormat::DatabaseAdminCsvFormat(QWidget *parent) :
QDialog(parent),
ui(new Ui::DatabaseAdminCsvFormat)
{
ui->setupUi(this);
connect(ui->DragSectionCombo,SIGNAL(ChangedDragSection()),this,SLOT(ChangedDragSection()));
IsExport = true;
ui->LabelValidation->setVisible(false);
IsCsv = true;
}
QString DatabaseAdminCsvFormat::GetExtension()
{
return (IsCsv)?".csv":".xls";
}
void DatabaseAdminCsvFormat::SetXls()
{
IsCsv = false;
setWindowTitle("Xls");
}
QString DatabaseAdminCsvFormat::GetFileName()
{
return ui->FileName->text();
}
void DatabaseAdminCsvFormat::SetIsExport(bool IsExport)
{
this->IsExport = IsExport;
if(IsExport)
{
QString randomString;
{
QString possibleCharacters("abcdefghijklmnopqrstuvwxyz");
int randomStringLength = 10;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
}
ui->FileName->setText(QDir::cleanPath(QDir::currentPath() + QDir::separator() + randomString + GetExtension()));
}
}
void DatabaseAdminCsvFormat::ChangedDragSection()
{
QStringList res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Name);
}
ui->FormatResult->setText(res.join(":"));
}
void DatabaseAdminCsvFormat::SetDatabaseColumns(QList<DatabaseColumn> Columns)
{
this->Columns = Columns;
QStringList List;
QList<int> Items;
int index = 0;
foreach(DatabaseColumn Column, Columns)
{
List.append(Column.Description);
Items.append(index);
index++;
}
ui->DragSectionCombo->SetData(List,Items);
ChangedDragSection();
}
QList<int> DatabaseAdminCsvFormat::GetColumnIds()
{
QList<int> res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Id);
}
return res;
}
DatabaseAdminCsvFormat::~DatabaseAdminCsvFormat()
{
delete ui;
}
void DatabaseAdminCsvFormat::on_OpenFileButton_clicked()
{
QString fileName;
if(IsExport)
fileName = QFileDialog::getSaveFileName(this, tr("Save"), "", tr("Csv Files (*.csv);;All Files (*.*)"));
else
fileName = QFileDialog::getOpenFileName(this, tr("Save"), "", tr("All Files (*.*);;Csv Files (*.csv)"));
if(fileName.length()>0)
{
ui->FileName->setText(fileName);
}
}
void DatabaseAdminCsvFormat::on_Ok_clicked()
{
if (IsExport || QFile::exists(GetFileName()))
{
accept();
} else
{
ui->LabelValidation->setVisible(true);
}
}
void DatabaseAdminCsvFormat::on_Cancel_clicked()
{
reject();
}
| 21.727941 | 120 | 0.643316 |
288dbd960d6e8f1e0ae0e8e9da6520c15f44affb | 11,530 | cpp | C++ | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | 1 | 2015-11-15T08:20:33.000Z | 2018-03-04T09:48:23.000Z | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | /*
Valet, a generalized Butler scorer for bridge.
Copyright (C) 2015 by Soren Hein.
See LICENSE and README.
*/
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "valet.h"
#include "Pairs.h"
#include "Hand.h"
#include "scoring.h"
extern OptionsType options;
extern Pairs pairs;
typedef int (*fptrType)(int rawScore);
fptrType fptr;
//////////////////////////////////////////////////
// //
// General functions for all types of scoring //
// //
//////////////////////////////////////////////////
Hand::Hand()
{
Hand::Reset();
}
Hand::~Hand()
{
}
void Hand::Reset()
{
boardNo = 0;
numEntries = 0;
results.resize(HAND_CHUNK_SIZE);
length = HAND_CHUNK_SIZE;
}
int Hand::SetBoardNumber(
const unsigned n)
{
if (boardNo > 0 && n != boardNo)
return RETURN_BOARD_NUMBER_CHANGE;
boardNo = n;
GetVul(boardNo, vulNS, vulEW);
return RETURN_NO_FAULT;
}
unsigned Hand::GetBoardNumber()
{
return boardNo;
}
unsigned Hand::GetNumEntries()
{
return numEntries;
}
void Hand::AddResult(
const ResultType& res)
{
assert(boardNo > 0);
if (numEntries == length)
{
length += 8;
results.resize(length);
}
results[numEntries++] = res;
}
void Hand::ResetValetEntry(
ValetEntryType& entry)
{
entry.pairNo = 0;
entry.oppNo = 0;
entry.declFlag[0] = false;
entry.declFlag[1] = false;
entry.defFlag = false;
entry.leadFlag[0] = false;
entry.leadFlag[1] = false;
entry.overall = 0.;
entry.bidScore = 0.;
entry.playScore[0] = 0.;
entry.playScore[1] = 0.;
entry.leadScore[0] = 0.;
entry.leadScore[1] = 0.;
entry.defScore = 0.;
}
const unsigned Hswap[2][2] = { {0, 1}, {1, 0} };
void Hand::SetPairSwaps(
const ResultType& res,
ValetEntryType& entry,
unsigned& decl,
unsigned& leader)
{
// This function takes care of assigning the scores to the right
// players within a pair. pairNo is negative if the players are
// internally stored in the opposite order to the one that happens
// to be at the table.
unsigned swapNS, swapEW;
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
{
entry.pairNo = static_cast<unsigned>(-pairNoNS);
swapNS = 1;
}
else
{
entry.pairNo = static_cast<unsigned>(pairNoNS);
swapNS = 0;
}
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
{
entry.oppNo = static_cast<unsigned>(-pairNoEW);
swapEW = 1;
}
else
{
entry.oppNo = static_cast<unsigned>(pairNoEW);
swapEW = 0;
}
if (res.declarer == VALET_NORTH || res.declarer == VALET_SOUTH)
{
decl = Hswap[swapNS][res.declarer == VALET_SOUTH];
leader = Hswap[swapEW][res.declarer == VALET_SOUTH];
}
else if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
decl = Hswap[swapEW][res.declarer == VALET_WEST];
leader = Hswap[swapNS][res.declarer == VALET_EAST];
}
else
{
decl = 0;
leader = 0;
assert(false);
}
}
void Hand::SetPassout(
const ResultType& res,
const float totalIMPs,
ValetEntryType& entry)
{
// Pass-out.
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
pairNoNS = -pairNoNS; // Doesn't matter for pass-out
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
pairNoEW = -pairNoEW; // Doesn't matter for pass-out
entry.pairNo = static_cast<unsigned>(pairNoNS);
entry.oppNo = static_cast<unsigned>(pairNoEW);
entry.overall = totalIMPs;
entry.bidScore = totalIMPs;
}
void Hand::SetPlayResult(
const ResultType& res,
const float totalIMPs,
const float bidIMPs,
const float leadIMPs,
ValetEntryType& entry)
{
unsigned decl, leader;
Hand::SetPairSwaps(res, entry, decl, leader);
// All IMPs are seen from NS's side up to here.
float sign = 1.f;
if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
sign = -1.f;
unsigned tmp = entry.pairNo;
entry.pairNo = entry.oppNo;
entry.oppNo = tmp;
}
entry.declFlag[decl] = true;
entry.defFlag = true;
entry.leadFlag[leader] = true;
entry.overall = sign * totalIMPs;
entry.bidScore = sign * bidIMPs;
entry.playScore[decl] = sign * (totalIMPs - bidIMPs);
if (options.leadFlag && res.leadRank > 0)
{
entry.leadScore[leader] = - sign * leadIMPs;
entry.defScore = sign * (bidIMPs - totalIMPs + leadIMPs);
}
else
entry.defScore = sign * (bidIMPs - totalIMPs);
}
//////////////////////////////////////////////////
// //
// Functions only for datum scoring (Butler) //
// //
//////////////////////////////////////////////////
int Hand::GetDatum(
const vector<int>& rawScore)
{
// Datum score (average), rounded to nearest 10.
// This is used for Butler scoring.
int datum = 0;
int dmin = 9999, dmax = -9999;
for (unsigned i = 0; i < numEntries; i++)
{
if (rawScore[i] < dmin)
dmin = rawScore[i];
if (rawScore[i] > dmax)
dmax = rawScore[i];
datum += rawScore[i];
}
if (options.datumFilter && numEntries > 2)
datum = (datum-dmin-dmax) / static_cast<int>(numEntries-2);
else
datum = datum / static_cast<int>(numEntries);
return datum;
}
float Hand::GetDatumBidding(
const ResultType& res,
const unsigned vul,
const unsigned resMatrix[5][14],
const int datum)
{
// This is used for Butler scoring.
// We calculate the IMPs (across-the-field style) for our own
// contract if we get an average declarer of our denomination
// (playing from our side), and we compare this to the datum.
// This gives us the bidding performance, in a way.
float bidIMPs = 0.;
unsigned count = 0;
unsigned d = res.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
int artifScore = CalculateRawScore(res, vul, t);
bidIMPs += resMatrix[d][t] *
static_cast<float>(CalculateIMPs(artifScore - datum));
count += resMatrix[d][t];
}
assert(count > 0);
return (bidIMPs / count);
}
//////////////////////////////////////////////////
// //
// Functions only for IAF scoring and MPs //
// //
//////////////////////////////////////////////////
float Hand::GetOverallScore(
const vector<int> rawScore,
const int score)
{
// For a given score, we calculate the average number of IMPs/MPs
// against all the other pairs. If we've seen the score before,
// we use a cached value.
map<int, float>::iterator it = scoreLookup.find(score);
if (it != scoreLookup.end())
return it->second;
float result = 0;
unsigned count = 0;
bool seenSelfFlag = false;
for (unsigned i = 0; i < numEntries; i++)
{
// Skip own score.
if (! seenSelfFlag && rawScore[i] == score)
{
seenSelfFlag = true;
continue;
}
result += static_cast<float>((*fptr)(score - rawScore[i]));
count++;
}
assert(count > 0);
return (scoreLookup[score] = result / count);
}
float Hand::GetBiddingScore(
const vector<int> rawScore,
const unsigned no,
const unsigned vul,
const unsigned resMatrix[5][14],
const float overallResult)
{
// This is analogous to GetDatumBidding for Butler scoring.
// We compare to all other scores, not to the datum.
float bidResult = 0.;
unsigned count = 0;
ResultType resArtif = results[no];
unsigned d = resArtif.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
// Make a synthetic result of our contract with different
// declarers (including ourselves, but that scores 0).
resArtif.tricks = t;
int artifScore = CalculateRawScore(resArtif, vul, t);
bidResult +=
resMatrix[d][t] * Hand::GetOverallScore(rawScore, artifScore);
count += resMatrix[d][t];
}
// Special case: If we're the only ones to play in a denomination,
// we somewhat arbitrarily assign the full score to the bidding.
if (count == 0)
return overallResult;
else
return bidResult / count;
}
//////////////////////////////////////////////////
// //
// General scoring function, uses above //
// //
//////////////////////////////////////////////////
vector<ValetEntryType> Hand::CalculateScores()
{
vector<int> rawScore(numEntries);
vector<unsigned> vulList(numEntries);
unsigned resDeclMatrix[4][5][14] = {0};
unsigned resDeclLeadMatrix[4][4][5][14] = {0};
for (unsigned i = 0; i < numEntries; i++)
{
unsigned decl = results[i].declarer;
unsigned denom = results[i].denom;
unsigned tricks = results[i].tricks;
vulList[i] = (decl == VALET_NORTH ||
decl == VALET_SOUTH ? vulNS : vulEW);
rawScore[i] = CalculateRawScore(results[i], vulList[i]);
resDeclMatrix[decl][denom][tricks]++;
if (options.leadFlag && results[i].leadRank > 0)
{
unsigned lead = results[i].leadDenom;
resDeclLeadMatrix[decl][lead][denom][tricks]++;
}
}
vector<ValetEntryType> entries(numEntries);
if (numEntries == 0)
return entries;
if (options.valet == VALET_IMPS)
{
int datum = Hand::GetDatum(rawScore);
float bidIMPs, bidLeadIMPs, leadIMPs = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float butlerIMPs = static_cast<float>(
CalculateIMPs(rawScore[i] - datum));
if (res.level == 0)
Hand::SetPassout(res, butlerIMPs, entry);
else
{
bidIMPs = GetDatumBidding(res, vulList[i],
resDeclMatrix[res.declarer], datum);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIMPs = GetDatumBidding(res, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], datum);
leadIMPs = bidLeadIMPs - bidIMPs;
}
else
leadIMPs = 0.f;
Hand::SetPlayResult(res, butlerIMPs, bidIMPs, leadIMPs, entry);
}
}
}
else
{
if (options.valet == VALET_IMPS_ACROSS_FIELD)
fptr = &CalculateIMPs;
else if (options.valet == VALET_MATCHPOINTS)
fptr = &CalculateMPs;
else
assert(false);
scoreLookup.clear();
float bidIAF, bidLeadIAF, leadIAF = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float IAFs = Hand::GetOverallScore(rawScore, rawScore[i]);
if (res.level == 0)
Hand::SetPassout(res, IAFs, entry);
else
{
bidIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclMatrix[res.declarer], IAFs);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], IAFs);
leadIAF = bidLeadIAF - bidIAF;
}
else
leadIAF = 0.f;
Hand::SetPlayResult(res, IAFs, bidIAF, leadIAF, entry);
}
}
}
return entries;
}
| 23.06 | 71 | 0.590286 |
288f0fa771c4bfca6b7fab038801fc88bed55bd2 | 2,603 | hpp | C++ | include/eve/module/math/diff/impl/hypot.hpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | include/eve/module/math/diff/impl/hypot.hpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | include/eve/module/math/diff/impl/hypot.hpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/module/core.hpp>
#include <eve/module/core.hpp>
#include <eve/module/math/regular/hypot.hpp>
#include <eve/module/math/pedantic/hypot.hpp>
namespace eve::detail
{
template<int N, typename T0, typename T1, typename... Ts>
auto hypot_(EVE_SUPPORTS(cpu_), diff_type<N>
, T0 arg0, T1 arg1, Ts... args) noexcept
{
using r_t = common_compatible_t<T0,T1, Ts...>;
if constexpr(N > sizeof...(Ts)+2)
{
return zero(as<r_t >());
}
else
{
auto h = hypot(arg0, arg1, args...);
if constexpr(N==1) return arg0/h;
else if constexpr(N==2) return arg1/h;
else
{
auto getNth = []<std::size_t... I>(std::index_sequence<I...>, auto& that, auto... vs)
{
auto iff = [&that]<std::size_t J>(auto val, std::integral_constant<std::size_t,J>)
{
if constexpr(J==N) that = val;
};
((iff(vs, std::integral_constant<std::size_t,I+3>{})),...);
};
r_t that(0);
getNth(std::make_index_sequence<sizeof...(args)>{},that,args...);
return that/h;
}
}
}
template<int N, typename T0, typename T1, typename... Ts>
auto hypot_(EVE_SUPPORTS(cpu_), decorated<diff_<N>(pedantic_)> const &
, T0 arg0, T1 arg1, Ts... args) noexcept
{
using r_t = common_compatible_t<T0,T1, Ts...>;
if constexpr(N > sizeof...(Ts)+2)
{
return zero(as<r_t >());
}
else
{
if constexpr(N > sizeof...(Ts)+2) return zero(as<r_t>());
else
{
auto h = pedantic(hypot)(arg0, arg1, args...);
if constexpr(N==1) return arg0/h;
else if constexpr(N==2) return arg1/h;
else
{
auto getNth = []<std::size_t... I>(std::index_sequence<I...>, auto& that, auto... vs)
{
auto iff = [&that]<std::size_t J>(auto val, std::integral_constant<std::size_t,J>)
{
if constexpr(J==N) that = val;
};
((iff(vs, std::integral_constant<std::size_t,I+3>{})),...);
};
r_t that(0);
getNth(std::make_index_sequence<sizeof...(args)>{},that,args...);
return that/h;
}
}
}
}
}
| 29.91954 | 100 | 0.48713 |
2890a085007d30e34ab174ff9d044ef698241adf | 2,340 | hpp | C++ | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | /// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_ALGORITHM_COPY_HPP
#define RANGES_V3_ALGORITHM_COPY_HPP
#include <functional>
#include <utility>
#include <range/v3/range_fwd.hpp>
#include <range/v3/algorithm/result_types.hpp>
#include <range/v3/iterator/concepts.hpp>
#include <range/v3/iterator/traits.hpp>
#include <range/v3/range/access.hpp>
#include <range/v3/range/concepts.hpp>
#include <range/v3/range/dangling.hpp>
#include <range/v3/range/traits.hpp>
#include <range/v3/utility/copy.hpp>
#include <range/v3/utility/static_const.hpp>
namespace ranges
{
/// \addtogroup group-algorithms
/// @{
template<typename I, typename O>
using copy_result = detail::in_out_result<I, O>;
struct cpp20_copy_fn
{
template<typename I, typename S, typename O>
constexpr auto operator()(I begin, S end, O out) const
-> CPP_ret(copy_result<I, O>)( //
requires input_iterator<I> && sentinel_for<S, I> && weakly_incrementable<O> &&
indirectly_copyable<I, O>)
{
for(; begin != end; ++begin, ++out)
*out = *begin;
return {begin, out};
}
template<typename Rng, typename O>
constexpr auto operator()(Rng && rng, O out) const
-> CPP_ret(copy_result<safe_iterator_t<Rng>, O>)( //
requires input_range<Rng> && weakly_incrementable<O> &&
indirectly_copyable<iterator_t<Rng>, O>)
{
return (*this)(begin(rng), end(rng), std::move(out));
}
};
struct RANGES_EMPTY_BASES copy_fn
: aux::copy_fn
, cpp20_copy_fn
{
using aux::copy_fn::operator();
using cpp20_copy_fn::operator();
};
/// \sa `copy_fn`
/// \ingroup group-algorithms
RANGES_INLINE_VARIABLE(copy_fn, copy)
namespace cpp20
{
using ranges::copy_result;
RANGES_INLINE_VARIABLE(cpp20_copy_fn, copy)
} // namespace cpp20
/// @}
} // namespace ranges
#endif // include guard
| 28.536585 | 94 | 0.631624 |
2891692a139096ff3c00c7d928507f9dadc410ae | 1,338 | cpp | C++ | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | #include <obs-module.h>
#include <strsafe.h>
#include <strmif.h>
#include "virtualcam-guid.h"
OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("win-dshow", "en-US")
MODULE_EXPORT const char *obs_module_description(void)
{
return "Windows DirectShow source/encoder";
}
extern void RegisterDShowSource();
extern void RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
extern "C" struct obs_output_info virtualcam_info;
static bool vcam_installed(bool b64)
{
wchar_t cls_str[CHARS_IN_GUID];
wchar_t temp[MAX_PATH];
HKEY key = nullptr;
StringFromGUID2(CLSID_OBS_VirtualVideo, cls_str, CHARS_IN_GUID);
StringCbPrintf(temp, sizeof(temp), L"CLSID\\%s", cls_str);
DWORD flags = KEY_READ;
flags |= b64 ? KEY_WOW64_64KEY : KEY_WOW64_32KEY;
LSTATUS status = RegOpenKeyExW(HKEY_CLASSES_ROOT, temp, 0, flags, &key);
if (status != ERROR_SUCCESS) {
return false;
}
RegCloseKey(key);
return true;
}
#endif
bool obs_module_load(void)
{
RegisterDShowSource();
RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
obs_register_output(&virtualcam_info);
bool installed = vcam_installed(false);
#else
bool installed = false;
#endif
obs_data_t *obs_settings = obs_data_create();
obs_data_set_bool(obs_settings, "vcamEnabled", installed);
obs_apply_private_data(obs_settings);
obs_data_release(obs_settings);
return true;
}
| 22.3 | 73 | 0.775037 |
28935679d006eb45047dbffe3327df2b91e28bb4 | 2,348 | cpp | C++ | src/caffe/layers/swish_layer.cpp | adriengb/caffe | 864520713a4c5ffae7382ced5d34e4cadc608473 | [
"Intel",
"BSD-2-Clause"
] | 36,275 | 2015-01-01T01:59:21.000Z | 2022-03-31T22:23:56.000Z | src/caffe/layers/swish_layer.cpp | wangrui1996/caffeface | feeb1d7c40e4a065c947933d6fab6fb218449551 | [
"Intel",
"BSD-2-Clause"
] | 5,493 | 2015-01-01T09:07:53.000Z | 2022-03-31T10:19:53.000Z | src/caffe/layers/swish_layer.cpp | wangrui1996/caffeface | feeb1d7c40e4a065c947933d6fab6fb218449551 | [
"Intel",
"BSD-2-Clause"
] | 18,620 | 2015-01-01T01:40:01.000Z | 2022-03-31T11:17:59.000Z | #include <cmath>
#include <vector>
#include "caffe/layers/swish_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void SwishLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
NeuronLayer<Dtype>::LayerSetUp(bottom, top);
sigmoid_bottom_vec_.clear();
sigmoid_bottom_vec_.push_back(sigmoid_input_.get());
sigmoid_top_vec_.clear();
sigmoid_top_vec_.push_back(sigmoid_output_.get());
sigmoid_layer_->SetUp(sigmoid_bottom_vec_, sigmoid_top_vec_);
}
template <typename Dtype>
void SwishLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
NeuronLayer<Dtype>::Reshape(bottom, top);
sigmoid_input_->ReshapeLike(*bottom[0]);
sigmoid_layer_->Reshape(sigmoid_bottom_vec_, sigmoid_top_vec_);
}
template <typename Dtype>
void SwishLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* sigmoid_input_data = sigmoid_input_->mutable_cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
const int count = bottom[0]->count();
Dtype beta = this->layer_param_.swish_param().beta();
caffe_copy(count, bottom_data, sigmoid_input_data);
caffe_scal(count, beta, sigmoid_input_data);
sigmoid_layer_->Forward(sigmoid_bottom_vec_, sigmoid_top_vec_);
caffe_mul(count, bottom_data, sigmoid_output_->cpu_data(), top_data);
}
template <typename Dtype>
void SwishLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
if (propagate_down[0]) {
const Dtype* top_data = top[0]->cpu_data();
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* sigmoid_output_data = sigmoid_output_->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const int count = bottom[0]->count();
Dtype beta = this->layer_param_.swish_param().beta();
for (int i = 0; i < count; ++i) {
const Dtype swish_x = top_data[i];
bottom_diff[i] = top_diff[i] * (beta * swish_x + sigmoid_output_data[i]
* (1. - beta * swish_x));
}
}
}
#ifdef CPU_ONLY
STUB_GPU(SwishLayer);
#endif
INSTANTIATE_CLASS(SwishLayer);
REGISTER_LAYER_CLASS(Swish);
} // namespace caffe
| 34.028986 | 77 | 0.720187 |
28937011bddc59ba74593117e770a2f406a5a089 | 13,827 | cpp | C++ | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | 1 | 2018-07-29T17:53:50.000Z | 2018-07-29T17:53:50.000Z | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | //MIP_deamon.cpp
//Author: Sivert Andresen Cubedo
//C++
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <queue>
//LINUX
#include <signal.h>
//Local
#include "../include/LinuxException.hpp"
#include "../include/EventPoll.hpp"
#include "../include/RawSock.hpp"
#include "../include/AddressTypes.hpp"
#include "../include/MIPFrame.hpp"
#include "../include/CrossIPC.hpp"
#include "../include/CrossForkExec.hpp"
#include "../include/TimerWrapper.hpp"
enum update_sock_option
{
LOCAL_MIP = 1,
ARP_DISCOVERY = 2,
ARP_LOSTCONNECTION = 3,
ADVERTISEMENT = 4
};
struct ARPPair
{
bool reply; //if true then pair is not lost
MIPAddress mip; //dest mip
MACAddress mac; //dest mac
RawSock::MIPRawSock* sock; //socket to reach dest
};
/*
Globals
*/
std::vector<RawSock::MIPRawSock> raw_sock_vec; //(must keep order intact so not to invalidate ARPPairs)
std::vector<ARPPair> arp_pair_vec; //(can't have duplicates)
ChildProcess routing_deamon;
EventPoll epoll;
AnonymousSocketPacket transport_sock;
AnonymousSocket update_sock;
AnonymousSocket lookup_sock;
std::queue<std::pair<bool, MIPFrame>> lookup_queue; //pair <true if source mip is set, frame>
const int ARP_TIMEOUT = 2000; //in ms
/*
Send local mip discovery to update_sock.
Parameters:
mip local mip discovered
Return:
void
Global:
update_sock
*/
void sendLocalMip(MIPAddress mip)
{
std::uint8_t option = update_sock_option::LOCAL_MIP;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp discovery with update_sock.
Parameters:
mip discovered address
Return:
void
Glboal:
update_sock
*/
void sendArpDiscovery(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_DISCOVERY;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp lost connection with update_sock.
Parameters:
mip lost address
Return:
void
Global:
update_sock
*/
void sendArpLostConnection(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_LOSTCONNECTION;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Print arp_pair_vec.
Parameters:
Return:
void
Global:
arp_pair_vec
*/
void printARPTable()
{
std::printf("%s: %4s:\n", "MIP", "MAC");
for (auto & p : arp_pair_vec) {
std::printf("%d: %4x:%x:%x:%x:%x:%x\n", (int)p.mip, p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5]);
}
}
/*
Add pair to arp_pair_vec.
Parameters:
sock ref to sock that Node was discovered on
mip mip
mac mac
Return:
void
Global:
arp_pair_vec
*/
void addARPPair(RawSock::MIPRawSock & sock, MIPAddress mip, MACAddress mac)
{
ARPPair pair;
pair.reply = true;
pair.mip = mip;
pair.mac = mac;
pair.sock = &sock;
arp_pair_vec.push_back(pair);
printARPTable(); //debug
}
/*
Send response frame to pair.
Parameters:
pair ref to pair
Return:
void
*/
void sendResponseFrame(ARPPair & pair)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::ZERO);
mip_frame.setMipDest(pair.mip);
mip_frame.setMipSource(pair.sock->getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
MACAddress dest = pair.mac;
MACAddress source = pair.sock->getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
pair.sock->sendMipFrame(mip_frame);
}
/*
Send broadcast frame on sock.
Parameters:
sock ref to sock
Return:
void
*/
void sendBroadcastFrame(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::A);
mip_frame.setMipDest(0xff);
mip_frame.setMipSource(sock.getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
static MACAddress dest{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
MACAddress source = sock.getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
sock.sendMipFrame(mip_frame);
}
/*
Receive on transport_sock.
Parameters:
Return:
void
Global:
transport_sock
lookup_queue
raw_sock_vec
*/
void receiveTransportSock()
{
static MIPFrame frame;
if (frame.getMsgSize() != MIPFrame::MSG_MAX_SIZE) {
frame.setMsgSize(MIPFrame::MSG_MAX_SIZE);
}
MIPAddress dest;
std::size_t msg_size;
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, dest);
iov.setIndex(1, msg_size);
iov.setIndex(2, frame.getMsg(), frame.getMsgSize());
transport_sock.recviovec(iov);
if (frame.getMsgSize() != msg_size) {
frame.setMsgSize(msg_size);
}
//check if dest address is local, if so then send back to transport_deamon
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest; }) != raw_sock_vec.end()) {
transport_sock.sendiovec(iov);
}
else {
frame.setMipTRA(MIPFrame::T);
frame.setMipDest(dest);
frame.setMipTTL(0xff);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
lookup_queue.emplace(false, frame);
lookup_sock.write(reinterpret_cast<char*>(&dest), sizeof(dest));
}
}
/*
Receive on lookup_sock.
Parameters:
Return:
void
Global:
lookup_sock
*/
void receiveLookupSock()
{
bool success;
lookup_sock.read(reinterpret_cast<char*>(&success), sizeof(success));
if (success) {
MIPAddress via;
lookup_sock.read(reinterpret_cast<char*>(&via), sizeof(via));
//check outgoing sockets
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == via; });
if (pair_it != arp_pair_vec.end()) {
ARPPair pair = (*pair_it);
MIPFrame & frame = lookup_queue.front().second;
if (!lookup_queue.front().first) {
frame.setMipSource(pair.sock->getMip());
}
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
//check if via is target is local
lookup_queue.pop();
}
else {
lookup_queue.pop();
}
}
/*
Receive on update_sock.
Parameters:
Return:
void
Global:
update_sock
arp_pair_vec
*/
void receiveUpdateSock()
{
//receive:
// to
// ad size
// ad
static MIPFrame frame;
MIPAddress dest_mip;
std::size_t ad_size;
update_sock.read(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
update_sock.read(reinterpret_cast<char*>(&ad_size), sizeof(ad_size));
frame.setMsgSize(ad_size);
update_sock.read(frame.getMsg(), ad_size);
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == dest_mip; });
if (pair_it != arp_pair_vec.end()) {
ARPPair & pair = (*pair_it);
frame.setMipTRA(MIPFrame::R);
frame.setMipDest(pair.mip);
frame.setMipSource(pair.sock->getMip());
frame.setMipTTL(0xff);
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
}
/*
Receive on raw sock.
Parameters:
sock ref to sock
Return:
void
Global:
update_sock
*/
void receiveRawSock(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
sock.recvMipFrame(mip_frame);
int tra = mip_frame.getMipTRA();
MIPAddress source_mip = mip_frame.getMipSource();
MIPAddress dest_mip = mip_frame.getMipDest();
std::uint8_t option;
std::size_t msg_size = mip_frame.getMsgSize();
std::vector<ARPPair>::iterator arp_it;
switch (tra)
{
case MIPFrame::A:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
sendResponseFrame(arp_pair_vec.back());
}
else {
arp_it->reply = true;
sendResponseFrame((*arp_it));
}
break;
case MIPFrame::ZERO:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
}
else {
arp_it->reply = true;
}
break;
case MIPFrame::R:
//send ad to routing_deamon
//send:
// from
// ad size
// ad
option = update_sock_option::ADVERTISEMENT;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(std::uint8_t));
update_sock.write(reinterpret_cast<char*>(&source_mip), sizeof(source_mip));
update_sock.write(reinterpret_cast<char*>(&msg_size), sizeof(msg_size));
update_sock.write(mip_frame.getMsg(), msg_size);
break;
case MIPFrame::T:
//cache frame in lookup_queue
//send:
// mip
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest_mip; }) == raw_sock_vec.end()) {
int ttl = mip_frame.getMipTTL();
if (ttl <= 0) {
//drop frame
std::cout << "ttl 0, dropping frame\n";
}
else {
mip_frame.setMipTTL(ttl - 1);
lookup_queue.emplace(true, mip_frame);
lookup_sock.write(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
}
}
else {
//send to transport deamon
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, source_mip);
iov.setIndex(1, msg_size);
iov.setIndex(2, mip_frame.getMsg(), msg_size);
transport_sock.sendiovec(iov);
}
break;
default:
throw std::runtime_error("Invalid TRA");
break;
}
}
/*
Init raw_sock_vec.
Parameters:
mip_vec ref to vec containing mip
Return:
void
*/
void initRawSock(const std::vector<MIPAddress> & mip_vec)
{
auto inter_names = RawSock::getInterfaceNames(std::vector<int>{ AF_PACKET });
for (auto & mip : mip_vec) {
if (inter_names.empty()) {
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
return;
}
std::string & name = inter_names.back();
if (name == "lo") {
continue;
}
raw_sock_vec.push_back(RawSock::MIPRawSock(name, mip));
//debug
std::cout << raw_sock_vec.back().toString() << "\n";
inter_names.pop_back();
}
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
}
/*
Signal function.
*/
void sigintHandler(int signum)
{
epoll.closeResources();
}
/*
args: ./MIP_deamon <transport connection> [mip addresses ...]
*/
int main(int argc, char** argv)
{
//parse args
if (argc < 3) {
std::cerr << "Too few args\n";
return EXIT_FAILURE;
}
//signal
struct sigaction sa;
sa.sa_handler = &sigintHandler;
if (sigaction(SIGINT, &sa, NULL) == -1) {
throw LinuxException::Error("sigaction()");
}
//Connect transport_deamon
transport_sock = AnonymousSocketPacket(argv[1]);
//Connect routing_deamon
{
auto pair1 = AnonymousSocket::createPair();
auto pair2 = AnonymousSocket::createPair();
std::vector<std::string> args(2);
args[0] = pair1.second.toString();
args[1] = pair2.second.toString();
routing_deamon = ChildProcess::forkExec("./routing_deamon", args);
update_sock = pair1.first;
lookup_sock = pair2.first;
pair1.second.closeResources();
pair2.second.closeResources();
}
//Make MIPRawSock
{
std::vector<MIPAddress> mip_vec;
for (int i = 2; i < argc; ++i) {
mip_vec.push_back(std::atoi(argv[i]));
}
initRawSock(mip_vec);
}
//epoll
epoll = EventPoll(100);
for (auto & sock : raw_sock_vec) {
epoll.addFriend<RawSock::MIPRawSock>(sock);
}
epoll.addFriend<AnonymousSocketPacket>(transport_sock);
epoll.addFriend<AnonymousSocket>(update_sock);
epoll.addFriend<AnonymousSocket>(lookup_sock);
//send local mip addresses to routing_deamon
for (auto & s : raw_sock_vec) {
sendLocalMip(s.getMip());
}
//Send first broadcast frames
for (auto & s : raw_sock_vec) {
sendBroadcastFrame(s);
}
//timer
TimerWrapper timeout_timer;
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
epoll.addFriend(timeout_timer);
while (!epoll.isClosed()) {
try {
auto & event_vec = epoll.wait(20); //<- epoll exceptions will happen here
for (auto & ev : event_vec) {
int in_fd = ev.data.fd;
//check
if (in_fd == timeout_timer.getFd()) {
//std::cout << "Expired: " << timeout_timer.readExpiredTime() << "\n";
for (auto it = arp_pair_vec.begin(); it != arp_pair_vec.end(); ) {
if (!it->reply) {
sendArpLostConnection(it->mip);
arp_pair_vec.erase(it);
}
else {
it->reply = false;
++it;
}
}
for (RawSock::MIPRawSock & sock : raw_sock_vec) {
sendBroadcastFrame(sock);
}
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
}
else if (in_fd == transport_sock.getFd()) {
receiveTransportSock();
}
else if (in_fd == update_sock.getFd()) {
receiveUpdateSock();
}
else if (in_fd == lookup_sock.getFd()) {
receiveLookupSock();
}
else {
//check raw
auto raw_it = std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s){ return s.getFd() == in_fd; });
if (raw_it != raw_sock_vec.end()) {
receiveRawSock((*raw_it));
}
}
}
}
catch (LinuxException::InterruptedException & e) {
//if this then interrupted
std::cout << "MIP_deamon: epoll interrupted\n";
}
}
update_sock.closeResources();
lookup_sock.closeResources();
std::cout << "MIP_deamon: joining routing_deamon\n";
routing_deamon.join();
std::cout << "MIP_deamon: terminating\n";
return EXIT_SUCCESS;
}
| 24.300527 | 150 | 0.697621 |
28937fbfa133d011eabee2e20eb392f70358a729 | 1,533 | cc | C++ | third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/xml/document_xml_tree_viewer.h"
#include "third_party/blink/public/resources/grit/blink_resources.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/script/classic_script.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
namespace blink {
void TransformDocumentToXMLTreeView(Document& document) {
String script_string =
UncompressResourceAsASCIIString(IDR_DOCUMENTXMLTREEVIEWER_JS);
String css_string =
UncompressResourceAsASCIIString(IDR_DOCUMENTXMLTREEVIEWER_CSS);
v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate());
ClassicScript::CreateUnspecifiedScript(script_string,
ScriptSourceLocationType::kInternal)
->RunScriptInIsolatedWorldAndReturnValue(
document.domWindow(), IsolatedWorldId::kDocumentXMLTreeViewerWorldId);
Element* element = document.getElementById("xml-viewer-style");
if (element) {
element->setTextContent(css_string);
}
}
} // namespace blink
| 40.342105 | 80 | 0.782779 |
28944b8ff24d177b9155a38b7480e3264003a45e | 1,571 | hpp | C++ | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:00.000Z | 2020-03-04T10:38:00.000Z | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | null | null | null | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:01.000Z | 2020-03-04T10:38:01.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: EventUtils.hpp
* Author: ubuntu
*
* Created on February 17, 2018, 10:33 AM
*/
#ifndef EVENTUTILS_HPP
#define EVENTUTILS_HPP
#include <string>
#include <vector>
#include "keto/event/Event.hpp"
#include "keto/server_common/VectorUtils.hpp"
#include "keto/server_common/Exception.hpp"
namespace keto {
namespace server_common {
template<class PbType>
keto::event::Event toEvent(PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
keto::event::Event toEvent(const std::string& event, PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(event,VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
PbType fromEvent(const keto::event::Event& event) {
PbType pbValue;
keto::event::Event copyEvent = event;
if (!pbValue.ParseFromString(VectorUtils().copyVectorToString(copyEvent.getMessage()))) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffDeserializationException());
}
return pbValue;
}
}
}
#endif /* EVENTUTILS_HPP */
| 25.754098 | 93 | 0.721833 |
28965e844bd40bf2ec2d3b1d670fa2188ec31509 | 16,473 | cc | C++ | third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webtransport/outgoing_stream.h"
#include <utility>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_exception.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/modules/webtransport/web_transport_error.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "v8/include/v8.h"
namespace blink {
namespace {
using ::testing::ElementsAre;
using ::testing::StrictMock;
class MockClient : public GarbageCollected<MockClient>,
public OutgoingStream::Client {
public:
MOCK_METHOD0(SendFin, void());
MOCK_METHOD0(ForgetStream, void());
MOCK_METHOD1(Reset, void(uint8_t));
};
// The purpose of this class is to ensure that the data pipe is reset before the
// V8TestingScope is destroyed, so that the OutgoingStream object doesn't try to
// create a DOMException after the ScriptState has gone away.
class StreamCreator {
STACK_ALLOCATED();
public:
StreamCreator() = default;
~StreamCreator() {
Reset();
// Let the OutgoingStream object respond to the closure if it needs to.
test::RunPendingTasks();
}
// The default value of |capacity| means some sensible value selected by mojo.
OutgoingStream* Create(const V8TestingScope& scope, uint32_t capacity = 0) {
MojoCreateDataPipeOptions options;
options.struct_size = sizeof(MojoCreateDataPipeOptions);
options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
options.element_num_bytes = 1;
options.capacity_num_bytes = capacity;
mojo::ScopedDataPipeProducerHandle data_pipe_producer;
MojoResult result =
mojo::CreateDataPipe(&options, data_pipe_producer, data_pipe_consumer_);
if (result != MOJO_RESULT_OK) {
ADD_FAILURE() << "CreateDataPipe() returned " << result;
}
auto* script_state = scope.GetScriptState();
mock_client_ = MakeGarbageCollected<StrictMock<MockClient>>();
auto* outgoing_stream = MakeGarbageCollected<OutgoingStream>(
script_state, mock_client_, std::move(data_pipe_producer));
ExceptionState exception_state(scope.GetIsolate(),
ExceptionState::kConstructionContext,
"OutgoingStream");
outgoing_stream->Init(exception_state);
CHECK(!exception_state.HadException());
return outgoing_stream;
}
// Closes the pipe.
void Reset() { data_pipe_consumer_.reset(); }
// This is for use in EXPECT_CALL(), which is why it returns a reference.
MockClient& GetMockClient() { return *mock_client_; }
// Reads everything from |data_pipe_consumer_| and returns it in a vector.
Vector<uint8_t> ReadAllPendingData() {
Vector<uint8_t> data;
const void* buffer = nullptr;
uint32_t buffer_num_bytes = 0;
MojoResult result = data_pipe_consumer_->BeginReadData(
&buffer, &buffer_num_bytes, MOJO_BEGIN_READ_DATA_FLAG_NONE);
switch (result) {
case MOJO_RESULT_OK:
break;
case MOJO_RESULT_SHOULD_WAIT: // No more data yet.
return data;
default:
ADD_FAILURE() << "BeginReadData() failed: " << result;
return data;
}
data.Append(static_cast<const uint8_t*>(buffer), buffer_num_bytes);
data_pipe_consumer_->EndReadData(buffer_num_bytes);
return data;
}
Persistent<StrictMock<MockClient>> mock_client_;
mojo::ScopedDataPipeConsumerHandle data_pipe_consumer_;
};
TEST(OutgoingStreamTest, Create) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
EXPECT_TRUE(outgoing_stream->Writable());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
TEST(OutgoingStreamTest, WriteArrayBuffer) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* chunk = DOMArrayBuffer::Create("A", 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('A'));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
TEST(OutgoingStreamTest, WriteArrayBufferView) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* buffer = DOMArrayBuffer::Create("*B", 2);
// Create a view into the buffer with offset 1, ie. "B".
auto* chunk = DOMUint8Array::Create(buffer, 1, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('B'));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
bool IsAllNulls(base::span<const uint8_t> data) {
return std::all_of(data.begin(), data.end(), [](uint8_t c) { return !c; });
}
TEST(OutgoingStreamTest, AsyncWrite) {
V8TestingScope scope;
StreamCreator stream_creator;
// Set a large pipe capacity, so any platform-specific excess is dwarfed in
// size.
constexpr uint32_t kPipeCapacity = 512u * 1024u;
auto* outgoing_stream = stream_creator.Create(scope, kPipeCapacity);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
// Write a chunk that definitely will not fit in the pipe.
const size_t kChunkSize = kPipeCapacity * 3;
auto* chunk = DOMArrayBuffer::Create(kChunkSize, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
// Let the first pipe write complete.
test::RunPendingTasks();
// Let microtasks run just in case write() returns prematurely.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
EXPECT_FALSE(tester.IsFulfilled());
// Read the first part of the data.
auto data1 = stream_creator.ReadAllPendingData();
EXPECT_LT(data1.size(), kChunkSize);
// Verify the data wasn't corrupted.
EXPECT_TRUE(IsAllNulls(data1));
// Allow the asynchronous pipe write to happen.
test::RunPendingTasks();
// Read the second part of the data.
auto data2 = stream_creator.ReadAllPendingData();
EXPECT_TRUE(IsAllNulls(data2));
test::RunPendingTasks();
// Read the final part of the data.
auto data3 = stream_creator.ReadAllPendingData();
EXPECT_TRUE(IsAllNulls(data3));
EXPECT_EQ(data1.size() + data2.size() + data3.size(), kChunkSize);
// Now the write() should settle.
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
// Nothing should be left to read.
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
// Writing immediately followed by closing should not lose data.
TEST(OutgoingStreamTest, WriteThenClose) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* chunk = DOMArrayBuffer::Create("D", 1);
ScriptPromise write_promise =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
EXPECT_CALL(stream_creator.GetMockClient(), SendFin()).WillOnce([&]() {
// This needs to happen asynchronously.
scope.GetExecutionContext()
->GetTaskRunner(TaskType::kNetworking)
->PostTask(FROM_HERE, WTF::Bind(&OutgoingStream::OnOutgoingStreamClosed,
WrapWeakPersistent(outgoing_stream)));
});
ScriptPromise close_promise =
writer->close(script_state, ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(scope.GetScriptState(), write_promise);
ScriptPromiseTester close_tester(scope.GetScriptState(), close_promise);
// Make sure that write() and close() both run before the event loop is
// serviced.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsFulfilled());
close_tester.WaitUntilSettled();
EXPECT_TRUE(close_tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('D'));
}
TEST(OutgoingStreamTest, DataPipeClosed) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
ScriptPromise closed = writer->closed(script_state);
ScriptPromiseTester closed_tester(script_state, closed);
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
// Close the other end of the pipe.
stream_creator.Reset();
closed_tester.WaitUntilSettled();
EXPECT_TRUE(closed_tester.IsRejected());
DOMException* closed_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), closed_tester.Value().V8Value());
ASSERT_TRUE(closed_exception);
EXPECT_EQ(closed_exception->name(), "NetworkError");
EXPECT_EQ(closed_exception->message(),
"The stream was aborted by the remote server");
auto* chunk = DOMArrayBuffer::Create('C', 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(script_state, result);
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsRejected());
DOMException* write_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(write_exception);
EXPECT_EQ(write_exception->name(), "NetworkError");
EXPECT_EQ(write_exception->message(),
"The stream was aborted by the remote server");
}
TEST(OutgoingStreamTest, DataPipeClosedDuringAsyncWrite) {
V8TestingScope scope;
StreamCreator stream_creator;
constexpr uint32_t kPipeCapacity = 512 * 1024;
auto* outgoing_stream = stream_creator.Create(scope, kPipeCapacity);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
const size_t kChunkSize = kPipeCapacity * 2;
auto* chunk = DOMArrayBuffer::Create(kChunkSize, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(script_state, result);
ScriptPromise closed = writer->closed(script_state);
ScriptPromiseTester closed_tester(script_state, closed);
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
// Close the other end of the pipe.
stream_creator.Reset();
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsRejected());
DOMException* write_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(write_exception);
EXPECT_EQ(write_exception->name(), "NetworkError");
EXPECT_EQ(write_exception->message(),
"The stream was aborted by the remote server");
closed_tester.WaitUntilSettled();
EXPECT_TRUE(closed_tester.IsRejected());
DOMException* closed_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(closed_exception);
EXPECT_EQ(closed_exception->name(), "NetworkError");
EXPECT_EQ(closed_exception->message(),
"The stream was aborted by the remote server");
}
TEST(OutgoingStreamTest, Abort) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(0u));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, v8::Undefined(isolate)),
ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, AbortWithWebTransportError) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(0));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
v8::Local<v8::Value> error =
WebTransportError::Create(isolate,
/*stream_error_code=*/absl::nullopt, "foobar",
WebTransportError::Source::kStream);
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, error), ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, AbortWithWebTransportErrorWithCode) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(8));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
v8::Local<v8::Value> error = WebTransportError::Create(
isolate,
/*stream_error_code=*/8, "foobar", WebTransportError::Source::kStream);
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, error), ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, CloseAndConnectionError) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), SendFin());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
// Run microtasks to ensure that the underlying sink's close function is
// called immediately.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
writer->close(script_state, ASSERT_NO_EXCEPTION);
outgoing_stream->Error(ScriptValue(isolate, v8::Undefined(isolate)));
}
} // namespace
} // namespace blink
| 36.44469 | 83 | 0.742002 |
28978548b1829e7a11224ceb2e8f5153185fe842 | 1,972 | cpp | C++ | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | #include "Texture2DComponentWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
namespace editor::impl {
Texture2DComponentWidget::Texture2DComponentWidget(QWidget* parent)
: QWidget(parent)
, m_Entity(nullptr)
, m_Texture2D(nullptr)
, m_Color(nullptr)
, m_Texture2DLineEdit(nullptr)
, m_Texture2DLabel(nullptr) {
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* textureLayout = new QHBoxLayout();
m_Color = new Double3Widget("Color", glm::vec3(0.0f), this);
m_Color->SetMinMax(0.0, 1.0);
m_Texture2DLineEdit = new QLineEdit(this);
m_Texture2DLabel = new QLabel("Texture2D", this);
m_Texture2DLabel->setMinimumWidth(80);
textureLayout->addWidget(m_Texture2DLabel);
textureLayout->addWidget(m_Texture2DLineEdit);
layout->addWidget(m_Color);
layout->addLayout(textureLayout);
setLayout(layout);
InitConnections();
}
void Texture2DComponentWidget::OnColorChanged(glm::vec3 value) {
if (m_Texture2D) {
m_Texture2D->Color = value;
}
}
void Texture2DComponentWidget::SetEntity(pawn::engine::GameEntity* entity) {
m_Entity = entity;
}
void Texture2DComponentWidget::SetTexture2D(pawn::engine::Texture2DComponent* texture2D) {
m_Texture2D = texture2D;
m_Texture2DLineEdit->setText(texture2D->TextureName.c_str());
m_Color->SetValue(texture2D->Color);
}
void Texture2DComponentWidget::OnLineEditPress() {
QString& text{ m_Texture2DLineEdit->text() };
std::string& textureName{ m_Texture2D->TextureName };
textureName = text.toLocal8Bit().constData();
emit Texture2DModified(*m_Entity);
m_Texture2DLineEdit->clearFocus();
}
void Texture2DComponentWidget::InitConnections() {
connect(
m_Color,
SIGNAL(ValueChanged(glm::vec3)),
this,
SLOT(OnColorChanged(glm::vec3))
);
connect(
m_Texture2DLineEdit,
SIGNAL(returnPressed()),
this,
SLOT(OnLineEditPress())
);
}
}
| 24.04878 | 92 | 0.704868 |
2899c2100506c2105260479f6240a9baee92e541 | 652 | cpp | C++ | Src/SimRobotCore2/Simulation/Axis.cpp | bhuman/SimRobot | f7b2039e7b8c801cdbd74ea25346cf86b298ab06 | [
"MIT"
] | 3 | 2021-11-05T21:09:09.000Z | 2021-11-15T22:48:10.000Z | Src/SimRobotCore2/Simulation/Axis.cpp | bhuman/SimRobot | f7b2039e7b8c801cdbd74ea25346cf86b298ab06 | [
"MIT"
] | null | null | null | Src/SimRobotCore2/Simulation/Axis.cpp | bhuman/SimRobot | f7b2039e7b8c801cdbd74ea25346cf86b298ab06 | [
"MIT"
] | null | null | null | /**
* @file Simulation/Axis.cpp
* Implementation of class Axis
* @author Colin Graf
*/
#include "Axis.h"
#include "Platform/Assert.h"
#include "Simulation/Actuators/Joint.h"
#include "Simulation/Motors/Motor.h"
#include <cmath>
Axis::~Axis()
{
delete deflection;
delete motor;
}
void Axis::create()
{
// normalize axis
const float len = std::sqrt(x * x + y * y + z * z);
if(len == 0.f)
x = 1.f;
else
{
const float invLen = 1.f / len;
x *= invLen;
y *= invLen;
z *= invLen;
}
}
void Axis::addParent(Element& element)
{
joint = dynamic_cast<Joint*>(&element);
ASSERT(!joint->axis);
joint->axis = this;
}
| 16.3 | 53 | 0.613497 |
289e451ffa00b08f3d822915b75dff6d0df64895 | 7,873 | cpp | C++ | ext/botan/src/lib/hash/sha3/sha3.cpp | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 56 | 2019-04-25T19:06:11.000Z | 2022-03-25T20:26:25.000Z | ext/botan/src/lib/hash/sha3/sha3.cpp | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 184 | 2019-04-24T18:20:08.000Z | 2022-03-22T18:56:45.000Z | ext/botan/src/lib/hash/sha3/sha3.cpp | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 34 | 2019-04-03T15:21:16.000Z | 2022-03-20T04:26:53.000Z | /*
* SHA-3
* (C) 2010,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/sha3.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
#include <botan/exceptn.h>
#include <botan/cpuid.h>
#include <tuple>
namespace Botan {
namespace {
// This is a workaround for a suspected bug in clang 12 (and XCode 13)
// that caused a miscompile of the SHA3 implementation for optimization
// level -O2 and higher.
//
// For details, see: https://github.com/randombit/botan/issues/2802
#if defined(__clang__) && \
(( defined(__apple_build_version__) && __clang_major__ == 13) || \
(!defined(__apple_build_version__) && __clang_major__ == 12))
#define BOTAN_WORKAROUND_MAYBE_INLINE __attribute__((noinline))
#else
#define BOTAN_WORKAROUND_MAYBE_INLINE inline
#endif
BOTAN_WORKAROUND_MAYBE_INLINE std::tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>
xor_CNs(const uint64_t A[25])
{
return {
A[0] ^ A[5] ^ A[10] ^ A[15] ^ A[20],
A[1] ^ A[6] ^ A[11] ^ A[16] ^ A[21],
A[2] ^ A[7] ^ A[12] ^ A[17] ^ A[22],
A[3] ^ A[8] ^ A[13] ^ A[18] ^ A[23],
A[4] ^ A[9] ^ A[14] ^ A[19] ^ A[24]};
}
#undef BOTAN_WORKAROUND_MAYBE_INLINE
inline void SHA3_round(uint64_t T[25], const uint64_t A[25], uint64_t RC)
{
const auto Cs = xor_CNs(A);
const uint64_t D0 = rotl<1>(std::get<0>(Cs)) ^ std::get<3>(Cs);
const uint64_t D1 = rotl<1>(std::get<1>(Cs)) ^ std::get<4>(Cs);
const uint64_t D2 = rotl<1>(std::get<2>(Cs)) ^ std::get<0>(Cs);
const uint64_t D3 = rotl<1>(std::get<3>(Cs)) ^ std::get<1>(Cs);
const uint64_t D4 = rotl<1>(std::get<4>(Cs)) ^ std::get<2>(Cs);
const uint64_t B00 = A[ 0] ^ D1;
const uint64_t B01 = rotl<44>(A[ 6] ^ D2);
const uint64_t B02 = rotl<43>(A[12] ^ D3);
const uint64_t B03 = rotl<21>(A[18] ^ D4);
const uint64_t B04 = rotl<14>(A[24] ^ D0);
T[ 0] = B00 ^ (~B01 & B02) ^ RC;
T[ 1] = B01 ^ (~B02 & B03);
T[ 2] = B02 ^ (~B03 & B04);
T[ 3] = B03 ^ (~B04 & B00);
T[ 4] = B04 ^ (~B00 & B01);
const uint64_t B05 = rotl<28>(A[ 3] ^ D4);
const uint64_t B06 = rotl<20>(A[ 9] ^ D0);
const uint64_t B07 = rotl< 3>(A[10] ^ D1);
const uint64_t B08 = rotl<45>(A[16] ^ D2);
const uint64_t B09 = rotl<61>(A[22] ^ D3);
T[ 5] = B05 ^ (~B06 & B07);
T[ 6] = B06 ^ (~B07 & B08);
T[ 7] = B07 ^ (~B08 & B09);
T[ 8] = B08 ^ (~B09 & B05);
T[ 9] = B09 ^ (~B05 & B06);
const uint64_t B10 = rotl< 1>(A[ 1] ^ D2);
const uint64_t B11 = rotl< 6>(A[ 7] ^ D3);
const uint64_t B12 = rotl<25>(A[13] ^ D4);
const uint64_t B13 = rotl< 8>(A[19] ^ D0);
const uint64_t B14 = rotl<18>(A[20] ^ D1);
T[10] = B10 ^ (~B11 & B12);
T[11] = B11 ^ (~B12 & B13);
T[12] = B12 ^ (~B13 & B14);
T[13] = B13 ^ (~B14 & B10);
T[14] = B14 ^ (~B10 & B11);
const uint64_t B15 = rotl<27>(A[ 4] ^ D0);
const uint64_t B16 = rotl<36>(A[ 5] ^ D1);
const uint64_t B17 = rotl<10>(A[11] ^ D2);
const uint64_t B18 = rotl<15>(A[17] ^ D3);
const uint64_t B19 = rotl<56>(A[23] ^ D4);
T[15] = B15 ^ (~B16 & B17);
T[16] = B16 ^ (~B17 & B18);
T[17] = B17 ^ (~B18 & B19);
T[18] = B18 ^ (~B19 & B15);
T[19] = B19 ^ (~B15 & B16);
const uint64_t B20 = rotl<62>(A[ 2] ^ D3);
const uint64_t B21 = rotl<55>(A[ 8] ^ D4);
const uint64_t B22 = rotl<39>(A[14] ^ D0);
const uint64_t B23 = rotl<41>(A[15] ^ D1);
const uint64_t B24 = rotl< 2>(A[21] ^ D2);
T[20] = B20 ^ (~B21 & B22);
T[21] = B21 ^ (~B22 & B23);
T[22] = B22 ^ (~B23 & B24);
T[23] = B23 ^ (~B24 & B20);
T[24] = B24 ^ (~B20 & B21);
}
}
//static
void SHA_3::permute(uint64_t A[25])
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return permute_bmi2(A);
}
#endif
static const uint64_t RC[24] = {
0x0000000000000001, 0x0000000000008082, 0x800000000000808A,
0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008A,
0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800A, 0x800000008000000A, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
};
uint64_t T[25];
for(size_t i = 0; i != 24; i += 2)
{
SHA3_round(T, A, RC[i+0]);
SHA3_round(A, T, RC[i+1]);
}
}
//static
size_t SHA_3::absorb(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
const uint8_t input[], size_t length)
{
while(length > 0)
{
size_t to_take = std::min(length, bitrate / 8 - S_pos);
length -= to_take;
while(to_take && S_pos % 8)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
while(to_take && to_take % 8 == 0)
{
S[S_pos / 8] ^= load_le<uint64_t>(input, 0);
S_pos += 8;
input += 8;
to_take -= 8;
}
while(to_take)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
if(S_pos == bitrate / 8)
{
SHA_3::permute(S.data());
S_pos = 0;
}
}
return S_pos;
}
//static
void SHA_3::finish(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
uint8_t init_pad, uint8_t fini_pad)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
S[S_pos / 8] ^= static_cast<uint64_t>(init_pad) << (8 * (S_pos % 8));
S[(bitrate / 64) - 1] ^= static_cast<uint64_t>(fini_pad) << 56;
SHA_3::permute(S.data());
}
//static
void SHA_3::expand(size_t bitrate,
secure_vector<uint64_t>& S,
uint8_t output[], size_t output_length)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
const size_t byterate = bitrate / 8;
while(output_length > 0)
{
const size_t copying = std::min(byterate, output_length);
copy_out_vec_le(output, copying, S);
output += copying;
output_length -= copying;
if(output_length > 0)
{
SHA_3::permute(S.data());
}
}
}
SHA_3::SHA_3(size_t output_bits) :
m_output_bits(output_bits),
m_bitrate(1600 - 2*output_bits),
m_S(25),
m_S_pos(0)
{
// We only support the parameters for SHA-3 in this constructor
if(output_bits != 224 && output_bits != 256 &&
output_bits != 384 && output_bits != 512)
throw Invalid_Argument("SHA_3: Invalid output length " +
std::to_string(output_bits));
}
std::string SHA_3::name() const
{
return "SHA-3(" + std::to_string(m_output_bits) + ")";
}
std::string SHA_3::provider() const
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return "bmi2";
}
#endif
return "base";
}
std::unique_ptr<HashFunction> SHA_3::copy_state() const
{
return std::unique_ptr<HashFunction>(new SHA_3(*this));
}
HashFunction* SHA_3::clone() const
{
return new SHA_3(m_output_bits);
}
void SHA_3::clear()
{
zeroise(m_S);
m_S_pos = 0;
}
void SHA_3::add_data(const uint8_t input[], size_t length)
{
m_S_pos = SHA_3::absorb(m_bitrate, m_S, m_S_pos, input, length);
}
void SHA_3::final_result(uint8_t output[])
{
SHA_3::finish(m_bitrate, m_S, m_S_pos, 0x06, 0x80);
/*
* We never have to run the permutation again because we only support
* limited output lengths
*/
copy_out_vec_le(output, m_output_bits/8, m_S);
clear();
}
}
| 26.778912 | 90 | 0.572717 |
289ef8c8180d743574707a78d0201eb1a99f0e90 | 16,630 | cpp | C++ | editor/osm_auth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 1 | 2021-06-27T05:41:23.000Z | 2021-06-27T05:41:23.000Z | editor/osm_auth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | null | null | null | editor/osm_auth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | null | null | null | #include "editor/osm_auth.hpp"
#include "platform/http_client.hpp"
#include "coding/url.hpp"
#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include <iostream>
#include <map>
#include "private.h"
#include "3party/liboauthcpp/include/liboauthcpp/liboauthcpp.h"
using namespace std;
using platform::HttpClient;
namespace osm
{
constexpr char const * kApiVersion = "/api/0.6";
constexpr char const * kFacebookCallbackPart = "/auth/facebook_access_token/callback?access_token=";
constexpr char const * kGoogleCallbackPart = "/auth/google_oauth2_access_token/callback?access_token=";
constexpr char const * kFacebookOAuthPart = "/auth/facebook?referer=%2Foauth%2Fauthorize%3Foauth_token%3D";
constexpr char const * kGoogleOAuthPart = "/auth/google?referer=%2Foauth%2Fauthorize%3Foauth_token%3D";
namespace
{
string FindAuthenticityToken(string const & body)
{
auto pos = body.find("name=\"authenticity_token\"");
if (pos == string::npos)
return string();
string const kValue = "value=\"";
auto start = body.find(kValue, pos);
if (start == string::npos)
return string();
start += kValue.length();
auto const end = body.find("\"", start);
return end == string::npos ? string() : body.substr(start, end - start);
}
string BuildPostRequest(map<string, string> const & params)
{
string result;
for (auto it = params.begin(); it != params.end(); ++it)
{
if (it != params.begin())
result += "&";
result += it->first + "=" + url::UrlEncode(it->second);
}
return result;
}
} // namespace
// static
bool OsmOAuth::IsValid(KeySecret const & ks) noexcept
{
return !(ks.first.empty() || ks.second.empty());
}
// static
bool OsmOAuth::IsValid(UrlRequestToken const & urt) noexcept
{
return !(urt.first.empty() || urt.second.first.empty() || urt.second.second.empty());
}
OsmOAuth::OsmOAuth(string const & consumerKey, string const & consumerSecret,
string const & baseUrl, string const & apiUrl) noexcept
: m_consumerKeySecret(consumerKey, consumerSecret), m_baseUrl(baseUrl), m_apiUrl(apiUrl)
{
}
// static
OsmOAuth OsmOAuth::ServerAuth() noexcept
{
#ifdef DEBUG
return DevServerAuth();
#else
return ProductionServerAuth();
#endif
}
// static
OsmOAuth OsmOAuth::ServerAuth(KeySecret const & userKeySecret) noexcept
{
OsmOAuth auth = ServerAuth();
auth.SetKeySecret(userKeySecret);
return auth;
}
// static
OsmOAuth OsmOAuth::IZServerAuth() noexcept
{
constexpr char const * kIZTestServer = "http://test.osmz.ru";
constexpr char const * kIZConsumerKey = "F0rURWssXDYxtm61279rHdyu3iSLYSP3LdF6DL3Y";
constexpr char const * kIZConsumerSecret = "IoR5TAedXxcybtd5tIBZqAK07rDRAuFMsQ4nhAP6";
return OsmOAuth(kIZConsumerKey, kIZConsumerSecret, kIZTestServer, kIZTestServer);
}
// static
OsmOAuth OsmOAuth::DevServerAuth() noexcept
{
constexpr char const * kOsmDevServer = "https://master.apis.dev.openstreetmap.org";
constexpr char const * kOsmDevConsumerKey = "eRtN6yKZZf34oVyBnyaVbsWtHIIeptLArQKdTwN3";
constexpr char const * kOsmDevConsumerSecret = "lC124mtm2VqvKJjSh35qBpKfrkeIjpKuGe38Hd1H";
return OsmOAuth(kOsmDevConsumerKey, kOsmDevConsumerSecret, kOsmDevServer, kOsmDevServer);
}
// static
OsmOAuth OsmOAuth::ProductionServerAuth() noexcept
{
constexpr char const * kOsmMainSiteURL = "https://www.openstreetmap.org";
constexpr char const * kOsmApiURL = "https://api.openstreetmap.org";
return OsmOAuth(OSM_CONSUMER_KEY, OSM_CONSUMER_SECRET, kOsmMainSiteURL, kOsmApiURL);
}
void OsmOAuth::SetKeySecret(KeySecret const & keySecret) noexcept { m_tokenKeySecret = keySecret; }
KeySecret const & OsmOAuth::GetKeySecret() const noexcept { return m_tokenKeySecret; }
bool OsmOAuth::IsAuthorized() const noexcept{ return IsValid(m_tokenKeySecret); }
// Opens a login page and extract a cookie and a secret token.
OsmOAuth::SessionID OsmOAuth::FetchSessionId(string const & subUrl, string const & cookies) const
{
string const url = m_baseUrl + subUrl + (cookies.empty() ? "?cookie_test=true" : "");
HttpClient request(url);
request.SetCookies(cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FetchSessionId Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FetchSessionIdError, (DebugPrint(request)));
SessionID const sid = { request.CombinedCookies(), FindAuthenticityToken(request.ServerResponse()) };
if (sid.m_cookies.empty() || sid.m_token.empty())
MYTHROW(FetchSessionIdError, ("Cookies and/or token are empty for request", DebugPrint(request)));
return sid;
}
void OsmOAuth::LogoutUser(SessionID const & sid) const
{
HttpClient request(m_baseUrl + "/logout");
request.SetCookies(sid.m_cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LogoutUser Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(LogoutUserError, (DebugPrint(request)));
}
bool OsmOAuth::LoginUserPassword(string const & login, string const & password, SessionID const & sid) const
{
map<string, string> const params =
{
{"username", login},
{"password", password},
{"referer", "/"},
{"commit", "Login"},
{"authenticity_token", sid.m_token}
};
HttpClient request(m_baseUrl + "/login");
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded")
.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LoginUserPassword Network error while connecting to", request.UrlRequested()));
// At the moment, automatic redirects handling is buggy on Androids < 4.4.
// set_handle_redirects(false) works only for Android code, iOS one (and curl) still automatically follow all redirects.
if (request.ErrorCode() != HTTP::OK && request.ErrorCode() != HTTP::Found)
MYTHROW(LoginUserPasswordServerError, (DebugPrint(request)));
// Not redirected page is a 100% signal that login and/or password are invalid.
if (!request.WasRedirected())
return false;
// Check if we were redirected to some 3rd party site.
if (request.UrlReceived().find(m_baseUrl) != 0)
MYTHROW(UnexpectedRedirect, (DebugPrint(request)));
// m_baseUrl + "/login" means login and/or password are invalid.
return request.ServerResponse().find("/login") == string::npos;
}
bool OsmOAuth::LoginSocial(string const & callbackPart, string const & socialToken, SessionID const & sid) const
{
string const url = m_baseUrl + callbackPart + socialToken;
HttpClient request(url);
request.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LoginSocial Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK && request.ErrorCode() != HTTP::Found)
MYTHROW(LoginSocialServerError, (DebugPrint(request)));
// Not redirected page is a 100% signal that social login has failed.
if (!request.WasRedirected())
return false;
// Check if we were redirected to some 3rd party site.
if (request.UrlReceived().find(m_baseUrl) != 0)
MYTHROW(UnexpectedRedirect, (DebugPrint(request)));
// m_baseUrl + "/login" means login and/or password are invalid.
return request.ServerResponse().find("/login") == string::npos;
}
// Fakes a buttons press to automatically accept requested permissions.
string OsmOAuth::SendAuthRequest(string const & requestTokenKey, SessionID const & lastSid) const
{
// We have to get a new CSRF token, using existing cookies to open the correct page.
SessionID const & sid =
FetchSessionId("/oauth/authorize?oauth_token=" + requestTokenKey, lastSid.m_cookies);
map<string, string> const params =
{
{"oauth_token", requestTokenKey},
{"oauth_callback", ""},
{"authenticity_token", sid.m_token},
{"allow_read_prefs", "yes"},
{"allow_write_api", "yes"},
{"allow_write_gpx", "yes"},
{"allow_write_notes", "yes"},
{"commit", "Save changes"}
};
HttpClient request(m_baseUrl + "/oauth/authorize");
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded")
.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("SendAuthRequest Network error while connecting to", request.UrlRequested()));
string const callbackURL = request.UrlReceived();
string const vKey = "oauth_verifier=";
auto const pos = callbackURL.find(vKey);
if (pos == string::npos)
MYTHROW(SendAuthRequestError, ("oauth_verifier is not found", DebugPrint(request)));
auto const end = callbackURL.find("&", pos);
return callbackURL.substr(pos + vKey.length(), end == string::npos ? end : end - pos - vKey.length());
}
RequestToken OsmOAuth::FetchRequestToken() const
{
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Client oauth(&consumer);
string const requestTokenUrl = m_baseUrl + "/oauth/request_token";
string const requestTokenQuery = oauth.getURLQueryString(OAuth::Http::Get, requestTokenUrl + "?oauth_callback=oob");
HttpClient request(requestTokenUrl + "?" + requestTokenQuery);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FetchRequestToken Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FetchRequestTokenServerError, (DebugPrint(request)));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", request.UrlRequested()));
// Throws std::runtime_error.
OAuth::Token const reqToken = OAuth::Token::extract(request.ServerResponse());
return { reqToken.key(), reqToken.secret() };
}
KeySecret OsmOAuth::FinishAuthorization(RequestToken const & requestToken,
string const & verifier) const
{
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Token const reqToken(requestToken.first, requestToken.second, verifier);
OAuth::Client oauth(&consumer, &reqToken);
string const accessTokenUrl = m_baseUrl + "/oauth/access_token";
string const queryString = oauth.getURLQueryString(OAuth::Http::Get, accessTokenUrl, "", true);
HttpClient request(accessTokenUrl + "?" + queryString);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FinishAuthorization Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FinishAuthorizationServerError, (DebugPrint(request)));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", request.UrlRequested()));
OAuth::KeyValuePairs const responseData = OAuth::ParseKeyValuePairs(request.ServerResponse());
// Throws std::runtime_error.
OAuth::Token const accessToken = OAuth::Token::extract(responseData);
return { accessToken.key(), accessToken.secret() };
}
// Given a web session id, fetches an OAuth access token.
KeySecret OsmOAuth::FetchAccessToken(SessionID const & sid) const
{
// Aquire a request token.
RequestToken const requestToken = FetchRequestToken();
// Faking a button press for access rights.
string const pin = SendAuthRequest(requestToken.first, sid);
LogoutUser(sid);
// Got pin, exchange it for the access token.
return FinishAuthorization(requestToken, pin);
}
bool OsmOAuth::AuthorizePassword(string const & login, string const & password)
{
SessionID const sid = FetchSessionId();
if (!LoginUserPassword(login, password, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
bool OsmOAuth::AuthorizeFacebook(string const & facebookToken)
{
SessionID const sid = FetchSessionId();
if (!LoginSocial(kFacebookCallbackPart, facebookToken, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
bool OsmOAuth::AuthorizeGoogle(string const & googleToken)
{
SessionID const sid = FetchSessionId();
if (!LoginSocial(kGoogleCallbackPart, googleToken, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
OsmOAuth::UrlRequestToken OsmOAuth::GetFacebookOAuthURL() const
{
RequestToken const requestToken = FetchRequestToken();
string const url = m_baseUrl + kFacebookOAuthPart + requestToken.first;
return UrlRequestToken(url, requestToken);
}
OsmOAuth::UrlRequestToken OsmOAuth::GetGoogleOAuthURL() const
{
RequestToken const requestToken = FetchRequestToken();
string const url = m_baseUrl + kGoogleOAuthPart + requestToken.first;
return UrlRequestToken(url, requestToken);
}
bool OsmOAuth::ResetPassword(string const & email) const
{
string const kForgotPasswordUrlPart = "/user/forgot-password";
SessionID const sid = FetchSessionId(kForgotPasswordUrlPart);
map<string, string> const params =
{
{"user[email]", email},
{"authenticity_token", sid.m_token},
{"commit", "Reset password"}
};
HttpClient request(m_baseUrl + kForgotPasswordUrlPart);
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded");
request.SetCookies(sid.m_cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("ResetPassword Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(ResetPasswordServerError, (DebugPrint(request)));
if (request.WasRedirected() && request.UrlReceived().find(m_baseUrl) != string::npos)
return true;
return false;
}
OsmOAuth::Response OsmOAuth::Request(string const & method, string const & httpMethod, string const & body) const
{
if (!IsValid(m_tokenKeySecret))
MYTHROW(InvalidKeySecret, ("User token (key and secret) are empty."));
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Token const oatoken(m_tokenKeySecret.first, m_tokenKeySecret.second);
OAuth::Client oauth(&consumer, &oatoken);
OAuth::Http::RequestType reqType;
if (httpMethod == "GET")
reqType = OAuth::Http::Get;
else if (httpMethod == "POST")
reqType = OAuth::Http::Post;
else if (httpMethod == "PUT")
reqType = OAuth::Http::Put;
else if (httpMethod == "DELETE")
reqType = OAuth::Http::Delete;
else
MYTHROW(UnsupportedApiRequestMethod, ("Unsupported OSM API request method", httpMethod));
string url = m_apiUrl + kApiVersion + method;
string const query = oauth.getURLQueryString(reqType, url);
auto const qPos = url.find('?');
if (qPos != string::npos)
url = url.substr(0, qPos);
HttpClient request(url + "?" + query);
if (httpMethod != "GET")
request.SetBodyData(body, "application/xml", httpMethod);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("Request Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
return Response(request.ErrorCode(), request.ServerResponse());
}
OsmOAuth::Response OsmOAuth::DirectRequest(string const & method, bool api) const
{
string const url = api ? m_apiUrl + kApiVersion + method : m_baseUrl + method;
HttpClient request(url);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("DirectRequest Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
return Response(request.ErrorCode(), request.ServerResponse());
}
string DebugPrint(OsmOAuth::Response const & code)
{
string r;
switch (code.first)
{
case OsmOAuth::HTTP::OK: r = "OK"; break;
case OsmOAuth::HTTP::BadXML: r = "BadXML"; break;
case OsmOAuth::HTTP::BadAuth: r = "BadAuth"; break;
case OsmOAuth::HTTP::Redacted: r = "Redacted"; break;
case OsmOAuth::HTTP::NotFound: r = "NotFound"; break;
case OsmOAuth::HTTP::WrongMethod: r = "WrongMethod"; break;
case OsmOAuth::HTTP::Conflict: r = "Conflict"; break;
case OsmOAuth::HTTP::Gone: r = "Gone"; break;
case OsmOAuth::HTTP::PreconditionFailed: r = "PreconditionFailed"; break;
case OsmOAuth::HTTP::URITooLong: r = "URITooLong"; break;
case OsmOAuth::HTTP::TooMuchData: r = "TooMuchData"; break;
default:
// No data from server in case of NetworkError.
if (code.first < 0)
return "NetworkError " + strings::to_string(code.first);
r = "HTTP " + strings::to_string(code.first);
}
return r + ": " + code.second;
}
} // namespace osm
| 37.881549 | 122 | 0.725797 |
80bcde2c3c2754065b9a3d053ef6b1e9273b93b7 | 2,410 | cpp | C++ | RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp | jeongjoonyoo/AMD_RGA | 26c6bfdf83f372eeadb1874420aa2ed55569d50f | [
"MIT"
] | 2 | 2019-05-18T11:39:59.000Z | 2019-05-18T11:40:05.000Z | RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | // C++.
#include <cassert>
#include <sstream>
// Local
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgSourceEditorTitlebar.h>
#include <RadeonGPUAnalyzerGUI/Include/rgStringConstants.h>
#include <RadeonGPUAnalyzerGUI/Include/rgUtils.h>
rgSourceEditorTitlebar::rgSourceEditorTitlebar(QWidget* pParent) :
QFrame(pParent)
{
ui.setupUi(this);
// Initialize the title bar text and tooltip.
std::stringstream titlebarText;
titlebarText << STR_SOURCE_EDITOR_TITLEBAR_CORRELATION_DISABLED_A;
titlebarText << STR_SOURCE_EDITOR_TITLEBAR_CORRELATION_DISABLED_B;
ui.sourceCorrelationLabel->setText(titlebarText.str().c_str());
// Initialize the title bar contents to be hidden.
SetTitlebarContentsVisibility(false);
// Set the mouse cursor to pointing hand cursor.
SetCursor();
// Connect the signals.
ConnectSignals();
// Prep the dismiss message push button.
ui.dismissMessagePushButton->setIcon(QIcon(":/icons/deleteIcon.svg"));
ui.dismissMessagePushButton->setStyleSheet("border: none");
}
void rgSourceEditorTitlebar::ConnectSignals()
{
bool isConnected = connect(ui.dismissMessagePushButton, &QPushButton::clicked, this, &rgSourceEditorTitlebar::HandleDismissMessagePushButtonClicked);
assert(isConnected);
isConnected = connect(ui.dismissMessagePushButton, &QPushButton::clicked, this, &rgSourceEditorTitlebar::DismissMsgButtonClicked);
assert(isConnected);
}
void rgSourceEditorTitlebar::HandleDismissMessagePushButtonClicked(/* bool checked */)
{
SetTitlebarContentsVisibility(false);
}
void rgSourceEditorTitlebar::SetIsCorrelationEnabled(bool isEnabled)
{
// Only show the title bar content if source line correlation is disabled.
SetTitlebarContentsVisibility(!isEnabled);
}
void rgSourceEditorTitlebar::ShowMessage(const std::string& msg)
{
ui.sourceCorrelationLabel->setText(msg.c_str());
SetTitlebarContentsVisibility(true);
}
void rgSourceEditorTitlebar::SetCursor()
{
// Set the mouse cursor to pointing hand cursor.
ui.viewMaximizeButton->setCursor(Qt::PointingHandCursor);
ui.dismissMessagePushButton->setCursor(Qt::PointingHandCursor);
}
void rgSourceEditorTitlebar::SetTitlebarContentsVisibility(bool isVisible)
{
ui.sourceCorrelationIcon->setVisible(isVisible);
ui.sourceCorrelationLabel->setVisible(isVisible);
ui.dismissMessagePushButton->setVisible(isVisible);
} | 33.013699 | 153 | 0.777178 |
80bd855e82392e09fc83f2c2ad73beb0cbcd3730 | 9,648 | cpp | C++ | src/test/fixtures.cpp | KuroGuo/firo | dbce40b3c7edb21fbebb014e6fe7ab700e649b6f | [
"MIT"
] | null | null | null | src/test/fixtures.cpp | KuroGuo/firo | dbce40b3c7edb21fbebb014e6fe7ab700e649b6f | [
"MIT"
] | null | null | null | src/test/fixtures.cpp | KuroGuo/firo | dbce40b3c7edb21fbebb014e6fe7ab700e649b6f | [
"MIT"
] | null | null | null | #include "util.h"
#include "clientversion.h"
#include "primitives/transaction.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utilmoneystr.h"
#include "test/test_bitcoin.h"
#include <stdint.h>
#include <vector>
#include <iostream>
#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "sigma/openssl_context.h"
#include "validation.h"
#include "miner.h"
#include "pubkey.h"
#include "random.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "test/testutil.h"
#include "test/fixtures.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include "sigma.h"
#include "lelantus.h"
ZerocoinTestingSetupBase::ZerocoinTestingSetupBase():
TestingSetup(CBaseChainParams::REGTEST, "1") {
// Crean sigma state, just in case someone forgot to do so.
sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();
sigmaState->Reset();
};
ZerocoinTestingSetupBase::~ZerocoinTestingSetupBase() {
// Clean sigma state after us.
sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();
sigmaState->Reset();
}
CBlock ZerocoinTestingSetupBase::CreateBlock(const CScript& scriptPubKey) {
const CChainParams& chainparams = Params();
std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);
CBlock block = pblocktemplate->block;
// IncrementExtraNonce creates a valid coinbase and merkleRoot
unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
return block;
}
bool ZerocoinTestingSetupBase::ProcessBlock(const CBlock &block) {
const CChainParams& chainparams = Params();
return ProcessNewBlock(chainparams, std::make_shared<const CBlock>(block), true, NULL);
}
// Create a new block with just given transactions, coinbase paying to
// scriptPubKey, and try to add it to the current chain.
CBlock ZerocoinTestingSetupBase::CreateAndProcessBlock(const CScript& scriptPubKey) {
CBlock block = CreateBlock(scriptPubKey);
BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
return block;
}
void ZerocoinTestingSetupBase::CreateAndProcessEmptyBlocks(size_t block_numbers, const CScript& script) {
while (block_numbers--) {
CreateAndProcessBlock(script);
}
}
ZerocoinTestingSetup200::ZerocoinTestingSetup200()
{
BOOST_CHECK(pwalletMain->GetKeyFromPool(pubkey));
std::string strAddress = CBitcoinAddress(pubkey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
//Mine 200 blocks so that we have funds for creating mints and we are over these limits:
//mBlockHeightConstants["ZC_V1_5_STARTING_BLOCK"] = 150;
//mBlockHeightConstants["ZC_CHECK_BUG_FIXED_AT_BLOCK"] = 140;
// Since sigma V3 implementation also over consensus.nMintV3SigmaStartBlock = 180;
scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
for (int i = 0; i < 200; i++)
{
CBlock b = CreateAndProcessBlock(scriptPubKey);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
ZerocoinTestingSetup109::ZerocoinTestingSetup109()
{
CPubKey newKey;
BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));
std::string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
scriptPubKey = CScript() << ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
for (int i = 0; i < 109; i++)
{
CBlock b = CreateAndProcessBlock(scriptPubKey);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
MtpMalformedTestingSetup::MtpMalformedTestingSetup()
{
CPubKey newKey;
BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));
std::string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
scriptPubKey = CScript() << ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
bool mtp = false;
CBlock b;
for (int i = 0; i < 150; i++)
{
b = CreateAndProcessBlock(scriptPubKey, mtp);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
CBlock MtpMalformedTestingSetup::CreateBlock(
const CScript& scriptPubKeyMtpMalformed, bool mtp = false) {
const CChainParams& chainparams = Params();
std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyMtpMalformed);
CBlock block = pblocktemplate->block;
// IncrementExtraNonce creates a valid coinbase and merkleRoot
unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
if(mtp) {
while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){
block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);
}
}
else {
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
}
//delete pblocktemplate;
return block;
}
// Create a new block with just given transactions, coinbase paying to
// scriptPubKeyMtpMalformed, and try to add it to the current chain.
CBlock MtpMalformedTestingSetup::CreateAndProcessBlock(
const CScript& scriptPubKeyMtpMalformed,
bool mtp = false) {
CBlock block = CreateBlock(scriptPubKeyMtpMalformed, mtp);
BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
return block;
}
LelantusTestingSetup::LelantusTestingSetup() :
params(lelantus::Params::get_default()) {
CPubKey key;
{
LOCK(pwalletMain->cs_wallet);
key = pwalletMain->GenerateNewKey();
}
script = GetScriptForDestination(key.GetID());
}
CBlockIndex* LelantusTestingSetup::GenerateBlock(std::vector<CMutableTransaction> const &txns, CScript *script) {
auto last = chainActive.Tip();
CreateAndProcessBlock(txns, script ? *script : this->script);
auto block = chainActive.Tip();
if (block != last) {
pwalletMain->ScanForWalletTransactions(block, true);
}
return block != last ? block : nullptr;
}
void LelantusTestingSetup::GenerateBlocks(size_t blocks, CScript *script) {
while (blocks--) {
GenerateBlock({}, script);
}
}
std::vector<lelantus::PrivateCoin> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts) {
auto const &p = lelantus::Params::get_default();
std::vector<lelantus::PrivateCoin> coins;
for (auto a : amounts) {
std::vector<unsigned char> k(32);
GetRandBytes(k.data(), k.size());
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_create(OpenSSLContext::get_context(), &pubkey, k.data())) {
throw std::runtime_error("Fail to create public key");
}
auto serial = lelantus::PrivateCoin::serialNumberFromSerializedPublicKey(
OpenSSLContext::get_context(), &pubkey);
Scalar randomness;
randomness.randomize();
coins.emplace_back(p, serial, a, randomness, k, 0);
}
return coins;
}
std::vector<CHDMint> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts,
std::vector<CMutableTransaction> &txs) {
std::vector<lelantus::PrivateCoin> coins;
return GenerateMints(amounts, txs, coins);
}
std::vector<CHDMint> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts,
std::vector<CMutableTransaction> &txs,
std::vector<lelantus::PrivateCoin> &coins) {
std::vector<CHDMint> hdMints;
CWalletDB walletdb(pwalletMain->strWalletFile);
for (auto a : amounts) {
std::vector<std::pair<CWalletTx, CAmount>> wtxAndFee;
std::vector<CHDMint> mints;
auto result = pwalletMain->MintAndStoreLelantus(a, wtxAndFee, mints);
if (result != "") {
throw std::runtime_error(_("Fail to generate mints, ") + result);
}
for(auto itr : wtxAndFee)
txs.emplace_back(itr.first);
hdMints.insert(hdMints.end(), mints.begin(), mints.end());
}
return hdMints;
}
CPubKey LelantusTestingSetup::GenerateAddress() {
LOCK(pwalletMain->cs_wallet);
return pwalletMain->GenerateNewKey();
}
LelantusTestingSetup::~LelantusTestingSetup() {
lelantus::CLelantusState::GetState()->Reset();
}
| 31.42671 | 122 | 0.671953 |
80be5327b4a40ed528ee97850b6ce595bc80ce65 | 17,311 | cpp | C++ | test/test_file.cpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | 977 | 2016-09-27T12:54:24.000Z | 2022-03-29T08:08:47.000Z | test/test_file.cpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | 2,265 | 2016-09-27T13:01:26.000Z | 2022-03-31T17:55:37.000Z | test/test_file.cpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | 154 | 2016-09-27T14:02:56.000Z | 2022-03-27T14:51:00.000Z | /*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* 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 "testsettings.hpp"
#ifdef TEST_FILE
#include <ostream>
#include <sstream>
#include <realm/util/file.hpp>
#include <realm/util/file_mapper.hpp>
#include "test.hpp"
#if REALM_PLATFORM_APPLE
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
using namespace realm::util;
using namespace realm::test_util;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
TEST(File_ExistsAndRemove)
{
TEST_PATH(path);
File(path, File::mode_Write);
CHECK(File::exists(path));
CHECK(File::try_remove(path));
CHECK(!File::exists(path));
CHECK(!File::try_remove(path));
}
TEST(File_IsSame)
{
TEST_PATH(path_1);
TEST_PATH(path_2);
// exFAT does not allocate inode numbers until the file is first non-empty,
// so all never-written-to files appear to be the same file
File(path_1, File::mode_Write).resize(1);
File(path_2, File::mode_Write).resize(1);
File f1(path_1, File::mode_Append);
File f2(path_1, File::mode_Read);
File f3(path_2, File::mode_Append);
CHECK(f1.is_same_file(f1));
CHECK(f1.is_same_file(f2));
CHECK(!f1.is_same_file(f3));
CHECK(!f2.is_same_file(f3));
}
TEST(File_Streambuf)
{
TEST_PATH(path);
{
File f(path, File::mode_Write);
File::Streambuf b(&f);
std::ostream out(&b);
out << "Line " << 1 << std::endl;
out << "Line " << 2 << std::endl;
}
{
File f(path, File::mode_Read);
char buffer[256];
size_t n = f.read(buffer);
std::string s_1(buffer, buffer + n);
std::ostringstream out;
out << "Line " << 1 << std::endl;
out << "Line " << 2 << std::endl;
std::string s_2 = out.str();
CHECK(s_1 == s_2);
}
}
TEST(File_Map)
{
TEST_PATH(path);
const char data[4096] = "12345678901234567890";
size_t len = strlen(data);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(len);
File::Map<char> map(f, File::access_ReadWrite, len);
realm::util::encryption_read_barrier(map, 0, len);
memcpy(map.get_addr(), data, len);
realm::util::encryption_write_barrier(map, 0, len);
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
File::Map<char> map(f, File::access_ReadOnly, len);
realm::util::encryption_read_barrier(map, 0, len);
CHECK(memcmp(map.get_addr(), data, len) == 0);
}
}
TEST(File_MapMultiplePages)
{
// two blocks of IV tables
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
TEST_PATH(path);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(count * sizeof(size_t));
File::Map<size_t> map(f, File::access_ReadWrite, count * sizeof(size_t));
realm::util::encryption_read_barrier(map, 0, count);
for (size_t i = 0; i < count; ++i)
map.get_addr()[i] = i;
realm::util::encryption_write_barrier(map, 0, count);
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
File::Map<size_t> map(f, File::access_ReadOnly, count * sizeof(size_t));
realm::util::encryption_read_barrier(map, 0, count);
for (size_t i = 0; i < count; ++i) {
CHECK_EQUAL(map.get_addr()[i], i);
if (map.get_addr()[i] != i)
return;
}
}
}
TEST(File_ReaderAndWriter)
{
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
TEST_PATH(path);
File writer(path, File::mode_Write);
writer.set_encryption_key(crypt_key());
writer.resize(count * sizeof(size_t));
File reader(path, File::mode_Read);
reader.set_encryption_key(crypt_key());
CHECK_EQUAL(writer.get_size(), reader.get_size());
File::Map<size_t> write(writer, File::access_ReadWrite, count * sizeof(size_t));
File::Map<size_t> read(reader, File::access_ReadOnly, count * sizeof(size_t));
for (size_t i = 0; i < count; i += 100) {
realm::util::encryption_read_barrier(write, i);
write.get_addr()[i] = i;
realm::util::encryption_write_barrier(write, i);
realm::util::encryption_read_barrier(read, i);
CHECK_EQUAL(read.get_addr()[i], i);
if (read.get_addr()[i] != i)
return;
}
}
TEST(File_Offset)
{
const size_t size = page_size();
const size_t count_per_page = size / sizeof(size_t);
// two blocks of IV tables
const size_t page_count = 256 * 2 / (size / 4096);
TEST_PATH(path);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(page_count * size);
for (size_t i = 0; i < page_count; ++i) {
File::Map<size_t> map(f, i * size, File::access_ReadWrite, size);
for (size_t j = 0; j < count_per_page; ++j) {
realm::util::encryption_read_barrier(map, j);
map.get_addr()[j] = i * size + j;
realm::util::encryption_write_barrier(map, j);
}
}
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
for (size_t i = 0; i < page_count; ++i) {
File::Map<size_t> map(f, i * size, File::access_ReadOnly, size);
for (size_t j = 0; j < count_per_page; ++j) {
realm::util::encryption_read_barrier(map, j);
CHECK_EQUAL(map.get_addr()[j], i * size + j);
if (map.get_addr()[j] != i * size + j)
return;
}
}
}
}
TEST(File_MultipleWriters)
{
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
#if defined(_WIN32) && defined(REALM_ENABLE_ENCRYPTION)
// This test runs really slow on Windows with encryption
const size_t increments = 3000;
#else
const size_t increments = 100;
#endif
TEST_PATH(path);
{
File w1(path, File::mode_Write);
w1.set_encryption_key(crypt_key());
w1.resize(count * sizeof(size_t));
File w2(path, File::mode_Write);
w2.set_encryption_key(crypt_key());
w2.resize(count * sizeof(size_t));
File::Map<size_t> map1(w1, File::access_ReadWrite, count * sizeof(size_t));
File::Map<size_t> map2(w2, File::access_ReadWrite, count * sizeof(size_t));
for (size_t i = 0; i < count; i += increments) {
realm::util::encryption_read_barrier(map1, i);
++map1.get_addr()[i];
realm::util::encryption_write_barrier(map1, i);
realm::util::encryption_read_barrier(map2, i);
++map2.get_addr()[i];
realm::util::encryption_write_barrier(map2, i);
}
}
File reader(path, File::mode_Read);
reader.set_encryption_key(crypt_key());
File::Map<size_t> read(reader, File::access_ReadOnly, count * sizeof(size_t));
realm::util::encryption_read_barrier(read, 0, count);
for (size_t i = 0; i < count; i += increments) {
CHECK_EQUAL(read.get_addr()[i], 2);
if (read.get_addr()[i] != 2)
return;
}
}
TEST(File_SetEncryptionKey)
{
TEST_PATH(path);
File f(path, File::mode_Write);
const char key[64] = {0};
#if REALM_ENABLE_ENCRYPTION
f.set_encryption_key(key); // should not throw
#else
CHECK_THROW(f.set_encryption_key(key), std::runtime_error);
#endif
}
TEST(File_ReadWrite)
{
TEST_PATH(path);
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(100);
for (char i = 0; i < 100; ++i)
f.write(&i, 1);
f.seek(0);
for (char i = 0; i < 100; ++i) {
char read;
f.read(&read, 1);
CHECK_EQUAL(i, read);
}
}
TEST(File_Resize)
{
TEST_PATH(path);
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(page_size() * 2);
CHECK_EQUAL(page_size() * 2, f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadWrite, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
// Resizing away the first write is indistinguishable in encrypted files
// from the process being interrupted before it does the first write,
// but with subsequent writes it can tell that there was once valid
// encrypted data there, so flush and write a second time
m.sync();
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
}
f.resize(page_size());
CHECK_EQUAL(page_size(), f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadOnly, page_size());
for (unsigned int i = 0; i < page_size(); ++i) {
realm::util::encryption_read_barrier(m, i);
CHECK_EQUAL(static_cast<unsigned char>(i), m.get_addr()[i]);
if (static_cast<unsigned char>(i) != m.get_addr()[i])
return;
}
}
f.resize(page_size() * 2);
CHECK_EQUAL(page_size() * 2, f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadWrite, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
}
{
File::Map<unsigned char> m(f, File::access_ReadOnly, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
CHECK_EQUAL(static_cast<unsigned char>(i), m.get_addr()[i]);
if (static_cast<unsigned char>(i) != m.get_addr()[i])
return;
}
}
}
TEST(File_NotFound)
{
TEST_PATH(path);
File file;
CHECK_THROW_EX(file.open(path), File::NotFound, e.get_path() == std::string(path));
}
TEST(File_PathNotFound)
{
File file;
CHECK_THROW(file.open(""), File::NotFound);
}
TEST(File_Exists)
{
TEST_PATH(path);
File file;
file.open(path, File::mode_Write); // Create the file
file.close();
CHECK_THROW_EX(file.open(path, File::access_ReadWrite, File::create_Must, File::flag_Trunc), File::Exists,
e.get_path() == std::string(path));
}
TEST(File_Move)
{
TEST_PATH(path);
File file_1(path, File::mode_Write);
CHECK(file_1.is_attached());
File file_2(std::move(file_1));
CHECK_NOT(file_1.is_attached());
CHECK(file_2.is_attached());
file_1 = std::move(file_2);
CHECK(file_1.is_attached());
CHECK_NOT(file_2.is_attached());
}
#if 0
TEST(File_PreallocResizing)
{
TEST_PATH(path);
File file(path, File::mode_Write);
CHECK(file.is_attached());
// we cannot test this with encryption...prealloc always allocates a full page
file.prealloc(0); // this is allowed
CHECK_EQUAL(file.get_size(), 0);
file.prealloc(100);
CHECK_EQUAL(file.get_size(), 100);
file.prealloc(50);
CHECK_EQUAL(file.get_size(), 100); // prealloc does not reduce size
// To expose the preallocation bug, we need to iterate over a large numbers, less than 4096.
// If the bug is present, we will allocate additional space to the file on every call, but if it is
// not present, the OS will preallocate 4096 only on the first call.
constexpr size_t init_size = 2048;
constexpr size_t dest_size = 3000;
for (size_t prealloc_space = init_size; prealloc_space <= dest_size; ++prealloc_space) {
file.prealloc(prealloc_space);
CHECK_EQUAL(file.get_size(), prealloc_space);
}
#if REALM_PLATFORM_APPLE
int fd = ::open(path.c_str(), O_RDONLY);
CHECK(fd >= 0);
struct stat statbuf;
CHECK(fstat(fd, &statbuf) == 0);
size_t allocated_size = statbuf.st_blocks;
CHECK_EQUAL(statbuf.st_size, dest_size);
CHECK(!int_multiply_with_overflow_detect(allocated_size, S_BLKSIZE));
// When performing prealloc, the OS has the option to preallocate more than the requeted space
// but we need to check that the preallocated space is within a reasonable bound.
// If space is being incorrectly preallocated (growing on each call) then we will have more than 3000KB
// of preallocated space, but if it is being allocated correctly (only when we need to expand) then we'll have
// a multiple of the optimal file system I/O operation (`stat -f %k .`) which is 4096 on HSF+.
// To give flexibility for file system prealloc implementations we check that the preallocated space is within
// at least 16 times the nominal requested size.
CHECK_LESS(allocated_size, 4096 * 16);
CHECK(::close(fd) == 0);
#endif
}
#endif
TEST(File_PreallocResizingAPFSBug)
{
TEST_PATH(path);
File file(path, File::mode_Write);
CHECK(file.is_attached());
file.write("aaaaaaaaaaaaaaaaaaaa"); // 20 a's
// calling prealloc on a newly created file would sometimes fail on APFS with EINVAL via fcntl(F_PREALLOCATE)
// this may not be the only way to trigger the error, but it does seem to be timing dependant.
file.prealloc(100);
CHECK_EQUAL(file.get_size(), 100);
// let's write past the first prealloc block (@ 4096) and verify it reads correctly too.
file.write("aaaaa");
// this will change the file size, but likely won't preallocate more space since the first call to prealloc
// will probably have allocated a whole 4096 block.
file.prealloc(200);
CHECK_EQUAL(file.get_size(), 200);
file.write("aa");
file.prealloc(5020); // expands to another 4096 block
constexpr size_t insert_pos = 5000;
const char* insert_str = "hello";
file.seek(insert_pos);
file.write(insert_str);
file.seek(insert_pos);
CHECK_EQUAL(file.get_size(), 5020);
constexpr size_t input_size = 6;
char input[input_size];
file.read(input, input_size);
CHECK_EQUAL(strncmp(input, insert_str, input_size), 0);
}
#ifndef _WIN32
TEST(File_GetUniqueID)
{
TEST_PATH(path_1);
TEST_PATH(path_2);
TEST_PATH(path_3);
File file1_1;
File file1_2;
File file2_1;
file1_1.open(path_1, File::mode_Write);
file1_2.open(path_1, File::mode_Read);
file2_1.open(path_2, File::mode_Write);
// exFAT does not allocate inode numbers until the file is first non-empty
file1_1.resize(1);
file2_1.resize(1);
File::UniqueID uid1_1 = file1_1.get_unique_id();
File::UniqueID uid1_2 = file1_2.get_unique_id();
File::UniqueID uid2_1 = file2_1.get_unique_id();
File::UniqueID uid2_2;
CHECK(File::get_unique_id(path_2, uid2_2));
CHECK(uid1_1 == uid1_2);
CHECK(uid2_1 == uid2_2);
CHECK(uid1_1 != uid2_1);
// Path doesn't exist
File::UniqueID uid3_1;
CHECK_NOT(File::get_unique_id(path_3, uid3_1));
// Test operator<
File::UniqueID uid4_1{0, 5};
File::UniqueID uid4_2{1, 42};
CHECK(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
uid4_1 = {0, 1};
uid4_2 = {0, 2};
CHECK(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
uid4_1 = uid4_2;
CHECK_NOT(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
}
#endif
#endif // TEST_FILE
| 31.190991 | 114 | 0.621455 |
80be77e6041f1ac2db954c1ec238a0dc33252bf1 | 3,186 | cpp | C++ | Gui/VtkVis/VtkCompositeThresholdFilter.cpp | WenjieXu/ogs | 0cd1b72ec824833bf949a8bbce073c82158ee443 | [
"BSD-4-Clause"
] | 1 | 2021-11-21T17:29:38.000Z | 2021-11-21T17:29:38.000Z | Gui/VtkVis/VtkCompositeThresholdFilter.cpp | WenjieXu/ogs | 0cd1b72ec824833bf949a8bbce073c82158ee443 | [
"BSD-4-Clause"
] | null | null | null | Gui/VtkVis/VtkCompositeThresholdFilter.cpp | WenjieXu/ogs | 0cd1b72ec824833bf949a8bbce073c82158ee443 | [
"BSD-4-Clause"
] | null | null | null | /**
* \file
* \author Lars Bilke
* \date 2010-10-25
* \brief Implementation of the VtkCompositeThresholdFilter class.
*
* \copyright
* Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
// ** INCLUDES **
#include "VtkCompositeThresholdFilter.h"
#include <vtkCellData.h>
#include <vtkThreshold.h>
#include <vtkUnstructuredGrid.h>
#include <vtkIntArray.h>
#include <vtkSmartPointer.h>
#include <limits>
VtkCompositeThresholdFilter::VtkCompositeThresholdFilter( vtkAlgorithm* inputAlgorithm )
: VtkCompositeFilter(inputAlgorithm)
{
this->init();
}
VtkCompositeThresholdFilter::~VtkCompositeThresholdFilter()
{
}
void VtkCompositeThresholdFilter::init()
{
// Set meta information about input and output data types
this->_inputDataObjectType = VTK_DATA_SET;
this->_outputDataObjectType = VTK_UNSTRUCTURED_GRID;
// Because this is the only filter here we cannot use vtkSmartPointer
vtkThreshold* threshold = vtkThreshold::New();
threshold->SetInputConnection(_inputAlgorithm->GetOutputPort());
// Sets a filter property which will be user editable
threshold->SetSelectedComponent(0);
// Setting the threshold to min / max values to ensure that the whole data
// is first processed. This is needed for correct lookup table generation.
const double dMin = std::numeric_limits<double>::lowest();
const double dMax = std::numeric_limits<double>::max();
threshold->ThresholdBetween(dMin, dMax);
// Create a list for the ThresholdBetween (vector) property.
QList<QVariant> thresholdRangeList;
// Insert the values (same values as above)
thresholdRangeList.push_back(dMin);
thresholdRangeList.push_back(dMax);
// Put that list in the property map
(*_algorithmUserVectorProperties)["Range"] = thresholdRangeList;
// Make a new entry in the property map for the SelectedComponent property
(*_algorithmUserProperties)["Selected Component"] = 0;
// Must all scalars match the criterium
threshold->SetAllScalars(1);
(*_algorithmUserProperties)["Evaluate all points"] = true;
// The threshold filter is last one and so it is also the _outputAlgorithm
_outputAlgorithm = threshold;
}
void VtkCompositeThresholdFilter::SetUserProperty( QString name, QVariant value )
{
VtkAlgorithmProperties::SetUserProperty(name, value);
// Use the same name as in init()
if (name.compare("Selected Component") == 0)
// Set the property on the algorithm
static_cast<vtkThreshold*>(_outputAlgorithm)->SetSelectedComponent(value.toInt());
else if (name.compare("Evaluate all points") == 0)
static_cast<vtkThreshold*>(_outputAlgorithm)->SetAllScalars(value.toBool());
}
void VtkCompositeThresholdFilter::SetUserVectorProperty( QString name, QList<QVariant> values )
{
VtkAlgorithmProperties::SetUserVectorProperty(name, values);
// Use the same name as in init()
if (name.compare("Range") == 0)
// Set the vector property on the algorithm
static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween(
values[0].toDouble(), values[1].toDouble());
}
| 33.1875 | 95 | 0.752982 |
80bfc03dca82f82722b71c57beed4f51541cc900 | 4,805 | cpp | C++ | alloctrace/test_main.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | alloctrace/test_main.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | alloctrace/test_main.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2009 Google Inc.
// Copyright (c) 2006-2007 Jaiku Ltd.
// Copyright (c) 2002-2006 Mika Raento and Renaud Petit
//
// This software is licensed at your choice under either 1 or 2 below.
//
// 1. MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// 2. Gnu General Public license 2.0
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//
// This file is part of the JaikuEngine mobile client.
#include <f32file.h>
#include "symbian_auto_ptr.h"
#include "app_context_impl.h"
void run_basic_and_interleaving(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("a0_top_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
char *a1=0;
{
CALLSTACKITEM_N(_CL(""), _CL("a1_top_1000"));
a1=(char*)User::Alloc(1000);
}
User::Free(a1);
char *a2=0;
{
CALLSTACKITEM_N(_CL(""), _CL("a2_top_1000"));
a2=(char*)User::Alloc(1000);
}
{
CALLSTACKITEM_N(_CL(""), _CL("a3_top_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
User::Free(a2);
}
void run_nested(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("b0_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b0_top_1000_own_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
}
{
CALLSTACKITEM_N(_CL(""), _CL("b10_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b11_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b12_top_1000_own_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
}
}
}
void run_seq(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("c0_top_250_own_250_count_4"));
char* p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
}
{
CALLSTACKITEM_N(_CL(""), _CL("c1_top_1000_own_1000_count_4"));
char *p0=0, *p1=0, *p2=0, *p3=0;
p0=(char*)User::Alloc(250);
p1=(char*)User::Alloc(250);
p2=(char*)User::Alloc(250);
p3=(char*)User::Alloc(250);
User::Free(p0); p0=0;
User::Free(p1); p1=0;
User::Free(p2); p2=0;
User::Free(p3); p3=0;
}
}
void run_realloc(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("d0_top_1000_own_1000_count_2"));
char *p=0;
p=(char*)User::Alloc(250);
p=(char*)User::ReAlloc(p, 1000);
User::Free(p);
}
}
#ifdef __S60V3__
#include "allocator.h"
#endif
void run_tests(void)
{
#ifdef __S60V3__
RAllocator* orig=SwitchToLoggingAllocator();
#endif
RHeap *h=&(User::Heap());
TAny* (RHeap::* p)(TInt)=h->Alloc;
auto_ptr<CApp_context> c(CApp_context::NewL(false, _L("alloctest")));
run_basic_and_interleaving();
run_nested();
run_seq();
run_realloc();
#ifdef __S60V3__
SwitchBackAllocator(orig);
#endif
}
GLDEF_C int E32Main(void)
{
CTrapCleanup* cleanupStack = CTrapCleanup::New();
TRAPD(err, run_tests());
delete cleanupStack;
return 0;
}
//extern "C" {
#ifndef __S60V3__
void __stdcall _E32Startup(void);
#else
void __stdcall _E32Bootstrap(void);
#endif
void InstallHooks(void);
void __stdcall _TraceStartup(void) {
InstallHooks();
#ifndef __S60V3__
_E32Startup();
#else
_E32Bootstrap();
#endif
}
//};
| 25.972973 | 82 | 0.690739 |
80c24217e0114cb19af7e90b9f5d29c34d9537ad | 5,933 | cc | C++ | net/cert/jwk_serializer_unittest.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/cert/jwk_serializer_unittest.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/cert/jwk_serializer_unittest.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/jwk_serializer.h"
#include "base/base64.h"
#include "base/values.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
#if !defined(USE_OPENSSL)
// This is the ASN.1 prefix for a P-256 public key. Specifically it's:
// SEQUENCE
// SEQUENCE
// OID id-ecPublicKey
// OID prime256v1
// BIT STRING, length 66, 0 trailing bits: 0x04
//
// The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
// public key. Following that are the two field elements as 32-byte,
// big-endian numbers, as required by the Channel ID.
static const unsigned char kP256SpkiPrefix[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04
};
static const unsigned int kEcCoordinateSize = 32U;
#endif
// This is a valid P-256 public key.
static const unsigned char kSpkiEc[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04,
0x29, 0x5d, 0x6e, 0xfe, 0x33, 0x77, 0x26, 0xea,
0x5b, 0xa4, 0xe6, 0x1b, 0x34, 0x6e, 0x7b, 0xa0,
0xa3, 0x8f, 0x33, 0x49, 0xa0, 0x9c, 0xae, 0x98,
0xbd, 0x46, 0x0d, 0xf6, 0xd4, 0x5a, 0xdc, 0x8a,
0x1f, 0x8a, 0xb2, 0x20, 0x51, 0xb7, 0xd2, 0x87,
0x0d, 0x53, 0x7e, 0x5d, 0x94, 0xa3, 0xe0, 0x34,
0x16, 0xa1, 0xcc, 0x10, 0x48, 0xcd, 0x70, 0x9c,
0x05, 0xd3, 0xd2, 0xca, 0xdf, 0x44, 0x2f, 0xf4
};
#if !defined(USE_OPENSSL)
// This is a P-256 public key with 0 X and Y values.
static const unsigned char kSpkiEcWithZeroXY[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
TEST(JwkSerializerNSSTest, ConvertSpkiFromDerToJwkEc) {
base::StringPiece spki;
base::DictionaryValue public_key_jwk;
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
// Test the result of a "normal" point on this curve.
spki.set(reinterpret_cast<const char*>(kSpkiEc), sizeof(kSpkiEc));
EXPECT_TRUE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
std::string string_value;
EXPECT_TRUE(public_key_jwk.GetString("alg", &string_value));
EXPECT_STREQ("EC", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("crv", &string_value));
EXPECT_STREQ("P-256", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("x", &string_value));
std::string decoded_coordinate;
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEc + sizeof(kP256SpkiPrefix),
kEcCoordinateSize));
EXPECT_TRUE(public_key_jwk.GetString("y", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEc + sizeof(kP256SpkiPrefix) + kEcCoordinateSize,
kEcCoordinateSize));
// Test the result of a corner case: leading 0s in the x, y coordinates are
// not trimmed, but the point is fixed-length encoded.
spki.set(reinterpret_cast<const char*>(kSpkiEcWithZeroXY),
sizeof(kSpkiEcWithZeroXY));
EXPECT_TRUE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.GetString("alg", &string_value));
EXPECT_STREQ("EC", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("crv", &string_value));
EXPECT_STREQ("P-256", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("x", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEcWithZeroXY + sizeof(kP256SpkiPrefix),
kEcCoordinateSize));
EXPECT_TRUE(public_key_jwk.GetString("y", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEcWithZeroXY + sizeof(kP256SpkiPrefix) + kEcCoordinateSize,
kEcCoordinateSize));
}
#else
// For OpenSSL, JwkSerializer::ConvertSpkiFromDerToJwk() is not yet implemented
// and should return false. This unit test ensures that a stub implementation
// is present.
TEST(JwkSerializerOpenSSLTest, ConvertSpkiFromDerToJwkNotImplemented) {
base::StringPiece spki;
base::DictionaryValue public_key_jwk;
// The empty SPKI is trivially non-convertible...
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
// but even a valid SPKI is non-convertible via the stub OpenSSL
// implementation.
spki.set(reinterpret_cast<const char*>(kSpkiEc), sizeof(kSpkiEc));
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
}
#endif // !defined(USE_OPENSSL)
} // namespace net
| 39.553333 | 79 | 0.707062 |